babylon.viewer.max.js 5.2 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907100908100909100910100911100912100913100914100915100916100917100918100919100920100921100922100923100924100925100926100927100928100929100930100931100932100933100934100935100936100937100938100939100940100941100942100943100944100945100946100947100948100949100950100951100952100953100954100955100956100957100958100959100960100961100962100963100964100965100966100967100968100969100970100971100972100973100974100975100976100977100978100979100980100981100982100983100984100985100986100987100988100989100990100991100992100993100994100995100996100997100998100999101000101001101002101003101004101005101006101007101008101009101010101011101012101013101014101015101016101017101018101019101020101021101022101023101024101025101026101027101028101029101030101031101032101033101034101035101036101037101038101039101040101041101042101043101044101045101046101047101048101049101050101051101052101053101054101055101056101057101058101059101060101061101062101063101064101065101066101067101068101069101070101071101072101073101074101075101076101077101078101079101080101081101082101083101084101085101086101087101088101089101090101091101092101093101094101095101096101097101098101099101100101101101102101103101104101105101106101107101108101109101110101111101112101113101114101115101116101117101118101119101120101121101122101123101124101125101126101127101128101129101130101131101132101133101134101135101136101137101138101139101140101141101142101143101144101145101146101147101148101149101150101151101152101153101154101155101156101157101158101159101160101161101162101163101164101165101166101167101168101169101170101171101172101173101174101175101176101177101178101179101180101181101182101183101184101185101186101187101188101189101190101191101192101193101194101195101196101197101198101199101200101201101202101203101204101205101206101207101208101209101210101211101212101213101214101215101216101217101218101219101220101221101222101223101224101225101226101227101228101229101230101231101232101233101234101235101236101237101238101239101240101241101242101243101244101245101246101247101248101249101250101251101252101253101254101255101256101257101258101259101260101261101262101263101264101265101266101267101268101269101270101271101272101273101274101275101276101277101278101279101280101281101282101283101284101285101286101287101288101289101290101291101292101293101294101295101296101297101298101299101300101301101302101303101304101305101306101307101308101309101310101311101312101313101314101315101316101317101318101319101320101321101322101323101324101325101326101327101328101329101330101331101332101333101334101335101336101337101338101339101340101341101342101343101344101345101346101347101348101349101350101351101352101353101354101355101356101357101358101359101360101361101362101363101364101365101366101367101368101369101370101371101372101373101374101375101376101377101378101379101380101381101382101383101384101385101386101387101388101389101390101391101392101393101394101395101396101397101398101399101400101401101402101403101404101405101406101407101408101409101410101411101412101413101414101415101416101417101418101419101420101421101422101423101424101425101426101427101428101429101430101431101432101433101434101435101436101437101438101439101440101441101442101443101444101445101446101447101448101449101450101451101452101453101454101455101456101457101458101459101460101461101462101463101464101465101466101467101468101469101470101471101472101473101474101475101476101477101478101479101480101481101482101483101484101485101486101487101488101489101490101491101492101493101494101495101496101497101498101499101500101501101502101503101504101505101506101507101508101509101510101511101512101513101514101515101516101517101518101519101520101521101522101523101524101525101526101527101528101529101530101531101532101533101534101535101536101537101538101539101540101541101542101543101544101545101546101547101548101549101550101551101552101553101554101555101556101557101558101559101560101561101562101563101564101565101566101567101568101569101570101571101572101573101574101575101576101577101578101579101580101581101582101583101584101585101586101587101588101589101590101591101592101593101594101595101596101597101598101599101600101601101602101603101604101605101606101607101608101609101610101611101612101613101614101615101616101617101618101619101620101621101622101623101624101625101626101627101628101629101630101631101632101633101634101635101636101637101638101639101640101641101642101643101644101645101646101647101648101649101650101651101652101653101654101655101656101657101658101659101660101661101662101663101664101665101666101667101668101669101670101671101672101673101674101675101676101677101678101679101680101681101682101683101684101685101686101687101688101689101690101691101692101693101694101695101696101697101698101699101700101701101702101703101704101705101706101707101708101709101710101711101712101713101714101715101716101717101718101719101720101721101722101723101724101725101726101727101728101729101730101731101732101733101734101735101736101737101738101739101740101741101742101743101744101745101746101747101748101749101750101751101752101753101754101755101756101757101758101759101760101761101762101763101764101765101766101767101768101769101770101771101772101773101774101775101776101777101778101779101780101781101782101783101784101785101786101787101788101789101790101791101792101793101794101795101796101797101798101799101800101801101802101803101804101805101806101807101808101809101810101811101812101813101814101815101816101817101818101819101820101821101822101823101824101825101826101827101828101829101830101831101832101833101834101835101836101837101838101839101840101841101842101843101844101845101846101847101848101849101850101851101852101853101854101855101856101857101858101859101860101861101862101863101864101865101866101867101868101869101870101871101872101873101874101875101876101877101878101879101880101881101882101883101884101885101886101887101888101889101890101891101892101893101894101895101896101897101898101899101900101901101902101903101904101905101906101907101908101909101910101911101912101913101914101915101916101917101918101919101920101921101922101923101924101925101926101927101928101929101930101931101932101933101934101935101936101937101938101939101940101941101942101943101944101945101946101947101948101949101950101951101952101953101954101955101956101957101958101959101960101961101962101963101964101965101966101967101968101969101970101971101972101973101974101975101976101977101978101979101980101981101982101983101984101985101986101987101988101989101990101991101992101993101994101995101996101997101998101999102000102001102002102003102004102005102006102007102008102009102010102011102012102013102014102015102016102017102018102019102020102021102022102023102024102025102026102027102028102029102030102031102032102033102034102035102036102037102038102039102040102041102042102043102044102045102046102047102048102049102050102051102052102053102054102055102056102057102058102059102060102061102062102063102064102065102066102067102068102069102070102071102072102073102074102075102076102077102078102079102080102081102082102083102084102085102086102087102088102089102090102091102092102093102094102095102096102097102098102099102100102101102102102103102104102105102106102107102108102109102110102111102112102113102114102115102116102117102118102119102120102121102122102123102124102125102126102127102128102129102130102131102132102133102134102135102136102137102138102139102140102141102142102143102144102145102146102147102148102149102150102151102152102153102154102155102156102157102158102159102160102161102162102163102164102165102166102167102168102169102170102171102172102173102174102175102176102177102178102179102180102181102182102183102184102185102186102187102188102189102190102191102192102193102194102195102196102197102198102199102200102201102202102203102204102205102206102207102208102209102210102211102212102213102214102215102216102217102218102219102220102221102222102223102224102225102226102227102228102229102230102231102232102233102234102235102236102237102238102239102240102241102242102243102244102245102246102247102248102249102250102251102252102253102254102255102256102257102258102259102260102261102262102263102264102265102266102267102268102269102270102271102272102273102274102275102276102277102278102279102280102281102282102283102284102285102286102287102288102289102290102291102292102293102294102295102296102297102298102299102300102301102302102303102304102305102306102307102308102309102310102311102312102313102314102315102316102317102318102319102320102321102322102323102324102325102326102327102328102329102330102331102332102333102334102335102336102337102338102339102340102341102342102343102344102345102346102347102348102349102350102351102352102353102354102355102356102357102358102359102360102361102362102363102364102365102366102367102368102369102370102371102372102373102374102375102376102377102378102379102380102381102382102383102384102385102386102387102388102389102390102391102392102393102394102395102396102397102398102399102400102401102402102403102404102405102406102407102408102409102410102411102412102413102414102415102416102417102418102419102420102421102422102423102424102425102426102427102428102429102430102431102432102433102434102435102436102437102438102439102440102441102442102443102444102445102446102447102448102449102450102451102452102453102454102455102456102457102458102459102460102461102462102463102464102465102466102467102468102469102470102471102472102473102474102475102476102477102478102479102480102481102482102483102484102485102486102487102488102489102490102491102492102493102494102495102496102497102498102499102500102501102502102503102504102505102506102507102508102509102510102511102512102513102514102515102516102517102518102519102520102521102522102523102524102525102526102527102528102529102530102531102532102533102534102535102536102537102538102539102540102541102542102543102544102545102546102547102548102549102550102551102552102553102554102555102556102557102558102559102560102561102562102563102564102565102566102567102568102569102570102571102572102573102574102575102576102577102578102579102580102581102582102583102584102585102586102587102588102589102590102591102592102593102594102595102596102597102598102599102600102601102602102603102604102605102606102607102608102609102610102611102612102613102614102615102616102617102618102619102620102621102622102623102624102625102626102627102628102629102630102631102632102633102634102635102636102637102638102639102640102641102642102643102644102645102646102647102648102649102650102651102652102653102654102655102656102657102658102659102660102661102662102663102664102665102666102667102668102669102670102671102672102673102674102675102676102677102678102679102680102681102682102683102684102685102686102687102688102689102690102691102692102693102694102695102696102697102698102699102700102701102702102703102704102705102706102707102708102709102710102711102712102713102714102715102716102717102718102719102720102721102722102723102724102725102726102727102728102729102730102731102732102733102734102735102736102737102738102739102740102741102742102743102744102745102746102747102748102749102750102751102752102753102754102755102756102757102758102759102760102761102762102763102764102765102766102767102768102769102770102771102772102773102774102775102776102777102778102779102780102781102782102783102784102785102786102787102788102789102790102791102792102793102794102795102796102797102798102799102800102801102802102803102804102805102806102807102808102809102810102811102812102813102814102815102816102817102818102819102820102821102822102823102824102825102826102827102828102829102830102831102832102833102834102835102836102837102838102839102840102841102842102843102844102845102846102847102848102849102850102851102852102853102854102855102856102857102858102859102860102861102862102863102864102865102866102867102868102869102870102871102872102873102874102875102876102877102878102879102880102881102882102883102884102885102886102887102888102889102890102891102892102893102894102895102896102897102898102899102900102901102902102903102904102905102906102907102908102909102910102911102912102913102914102915102916102917102918102919102920102921102922102923102924102925102926102927102928102929102930102931102932102933102934102935102936102937102938102939102940102941102942102943102944102945102946102947102948102949102950102951102952102953102954102955102956102957102958102959102960102961102962102963102964102965102966102967102968102969102970102971102972102973102974102975102976102977102978102979102980102981102982102983102984102985102986102987102988102989102990102991102992102993102994102995102996102997102998102999103000103001103002103003103004103005103006103007103008103009103010103011103012103013103014103015103016103017103018103019103020103021103022103023103024103025103026103027103028103029103030103031103032103033103034103035103036103037103038103039103040103041103042103043103044103045103046103047103048103049103050103051103052103053103054103055103056103057103058103059103060103061103062103063103064103065103066103067103068103069103070103071103072103073103074103075103076103077103078103079103080103081103082103083103084103085103086103087103088103089103090103091103092103093103094103095103096103097103098103099103100103101103102103103103104103105103106103107103108103109103110103111103112103113103114103115103116103117103118103119103120103121103122103123103124103125103126103127103128103129103130103131103132103133103134103135103136103137103138103139103140103141103142103143103144103145103146103147103148103149103150103151103152103153103154103155103156103157103158103159103160103161103162103163103164103165103166103167103168103169103170103171103172103173103174103175103176103177103178103179103180103181103182103183103184103185103186103187103188103189103190103191103192103193103194103195103196103197103198103199103200103201103202103203103204103205103206103207103208103209103210103211103212103213103214103215103216103217103218103219103220103221103222103223103224103225103226103227103228103229103230103231103232103233103234103235103236103237103238103239103240103241103242103243103244103245103246103247103248103249103250103251103252103253103254103255103256103257103258103259103260103261103262103263103264103265103266103267103268103269103270103271103272103273103274103275103276103277103278103279103280103281103282103283103284103285103286103287103288103289103290103291103292103293103294103295103296103297103298103299103300103301103302103303103304103305103306103307103308103309103310103311103312103313103314103315103316103317103318103319103320103321103322103323103324103325103326103327103328103329103330103331103332103333103334103335103336103337103338103339103340103341103342103343103344103345103346103347103348103349103350103351103352103353103354103355103356103357103358103359103360103361103362103363103364103365103366103367103368103369103370103371103372103373103374103375103376103377103378103379103380103381103382103383103384103385103386103387103388103389103390103391103392103393103394103395103396103397103398103399103400103401103402103403103404103405103406103407103408103409103410103411103412103413103414103415103416103417103418103419103420103421103422103423103424103425103426103427103428103429103430103431103432103433103434103435103436103437103438103439103440103441103442103443103444103445103446103447103448103449103450103451103452103453103454103455103456103457103458103459103460103461103462103463103464103465103466103467103468103469103470103471103472103473103474103475103476103477103478103479103480103481103482103483103484103485103486103487103488103489103490103491103492103493103494103495103496103497103498103499103500103501103502103503103504103505103506103507103508103509103510103511103512103513103514103515103516103517103518103519103520103521103522103523103524103525103526103527103528103529103530103531103532103533103534103535103536103537103538103539103540103541103542103543103544103545103546103547103548103549103550103551103552103553103554103555103556103557103558103559103560103561103562103563103564103565103566103567103568103569103570103571103572103573103574103575103576103577103578103579103580103581103582103583103584103585103586103587103588103589103590103591103592103593103594103595103596103597103598103599103600103601103602103603103604103605103606103607103608103609103610103611103612103613103614103615103616103617103618103619103620103621103622103623103624103625103626103627103628103629103630103631103632103633103634103635103636103637103638103639103640103641103642103643103644103645103646103647103648103649103650103651103652103653103654103655103656103657103658103659103660103661103662103663103664103665103666103667103668103669103670103671103672103673103674103675103676103677103678103679103680103681103682103683103684103685103686103687103688103689103690103691103692103693103694103695103696103697103698103699103700103701103702103703103704103705103706103707103708103709103710103711103712103713103714103715103716103717103718103719103720103721103722103723103724103725103726103727103728103729103730103731103732103733103734103735103736103737103738103739103740103741103742103743103744103745103746103747103748103749103750103751103752103753103754103755103756103757103758103759103760103761103762103763103764103765103766103767103768103769103770103771103772103773103774103775103776103777103778103779103780103781103782103783103784103785103786103787103788103789103790103791103792103793103794103795103796103797103798103799103800103801103802103803103804103805103806103807103808103809103810103811103812103813103814103815103816103817103818103819103820103821103822103823103824103825103826103827103828103829103830103831103832103833103834103835103836103837103838103839103840103841103842103843103844103845103846103847103848103849103850103851103852103853103854103855103856103857103858103859103860103861103862103863103864103865103866103867103868103869103870103871103872103873103874103875103876103877103878103879103880103881103882103883103884103885103886103887103888103889103890103891103892103893103894103895103896103897103898103899103900103901103902103903103904103905103906103907103908103909103910103911103912103913103914103915103916103917103918103919103920103921103922103923103924103925103926103927103928103929103930103931103932103933103934103935103936103937103938103939103940103941103942103943103944103945103946103947103948103949103950103951103952103953103954103955103956103957103958103959103960103961103962103963103964103965103966103967103968103969103970103971103972103973103974103975103976103977103978103979103980103981103982103983103984103985103986103987103988103989103990103991103992103993103994103995103996103997103998103999104000104001104002104003104004104005104006104007104008104009104010104011104012104013104014104015104016104017104018104019104020104021104022104023104024104025104026104027104028104029104030104031104032104033104034104035104036104037104038104039104040104041104042104043104044104045104046104047104048104049104050104051104052104053104054104055104056104057104058104059104060104061104062104063104064104065104066104067104068104069104070104071104072104073104074104075104076104077104078104079104080104081104082104083104084104085104086104087104088104089104090104091104092104093104094104095104096104097104098104099104100104101104102104103104104104105104106104107104108104109104110104111104112104113104114104115104116104117104118104119104120104121104122104123104124104125104126104127104128104129104130104131104132104133104134104135104136104137104138104139104140104141104142104143104144104145104146104147104148104149104150104151104152104153104154104155104156104157104158104159104160104161104162104163104164104165104166104167104168104169104170104171104172104173104174104175104176104177104178104179104180104181104182104183104184104185104186104187104188104189104190104191104192104193104194104195104196104197104198104199104200104201104202104203104204104205104206104207104208104209104210104211104212104213104214104215104216104217104218104219104220104221104222104223104224104225104226104227104228104229104230104231104232104233104234104235104236104237104238104239104240104241104242104243104244104245104246104247104248104249104250104251104252104253104254104255104256104257104258104259104260104261104262104263104264104265104266104267104268104269104270104271104272104273104274104275104276104277104278104279104280104281104282104283104284104285104286104287104288104289104290104291104292104293104294104295104296104297104298104299104300104301104302104303104304104305104306104307104308104309104310104311104312104313104314104315104316104317104318104319104320104321104322104323104324104325104326104327104328104329104330104331104332104333104334104335104336104337104338104339104340104341104342104343104344104345104346104347104348104349104350104351104352104353104354104355104356104357104358104359104360104361104362104363104364104365104366104367104368104369104370104371104372104373104374104375104376104377104378104379104380104381104382104383104384104385104386104387104388104389104390104391104392104393104394104395104396104397104398104399104400104401104402104403104404104405104406104407104408104409104410104411104412104413104414104415104416104417104418104419104420104421104422104423104424104425104426104427104428104429104430104431104432104433104434104435104436104437104438104439104440104441104442104443104444104445104446104447104448104449104450104451104452104453104454104455104456104457104458104459104460104461104462104463104464104465104466104467104468104469104470104471104472104473104474104475104476104477104478104479104480104481104482104483104484104485104486104487104488104489104490104491104492104493104494104495104496104497104498104499104500104501104502104503104504104505104506104507104508104509104510104511104512104513104514104515104516104517104518104519104520104521104522104523104524104525104526104527104528104529104530104531104532104533104534104535104536104537104538104539104540104541104542104543104544104545104546104547104548104549104550104551104552104553104554104555104556104557104558104559104560104561104562104563104564104565104566104567104568104569104570104571104572104573104574104575104576104577104578104579104580104581104582104583104584104585104586104587104588104589104590104591104592104593104594104595104596104597104598104599104600104601104602104603104604104605104606104607104608104609104610104611104612104613104614104615104616104617104618104619104620104621104622104623104624104625104626104627104628104629104630104631104632104633104634104635104636104637104638104639104640104641104642104643104644104645104646104647104648104649104650104651104652104653104654104655104656104657104658104659104660104661104662104663104664104665104666104667104668104669104670104671104672104673104674104675104676104677104678104679104680104681104682104683104684104685104686104687104688104689104690104691104692104693104694104695104696104697104698104699104700104701104702104703104704104705104706104707104708104709104710104711104712104713104714104715104716104717104718104719104720104721104722104723104724104725104726104727104728104729104730104731104732104733104734104735104736104737104738104739104740104741104742104743104744104745104746104747104748104749104750104751104752104753104754104755104756104757104758104759104760104761104762104763104764104765104766104767104768104769104770104771104772104773104774104775104776104777104778104779104780104781104782104783104784104785104786104787104788104789104790104791104792104793104794104795104796104797104798104799104800104801104802104803104804104805104806104807104808104809104810104811104812104813104814104815104816104817104818104819104820104821104822104823104824104825104826104827104828104829104830104831104832104833104834104835104836104837104838104839104840104841104842104843104844104845104846104847104848104849104850104851104852104853104854104855104856104857104858104859104860104861104862104863104864104865104866104867104868104869104870104871104872104873104874104875104876104877104878104879104880104881104882104883104884104885104886104887104888104889104890104891104892104893104894104895104896104897104898104899104900104901104902104903104904104905104906104907104908104909104910104911104912104913104914104915104916104917104918104919104920104921104922104923104924104925104926104927104928104929104930104931104932104933104934104935104936104937104938104939104940104941104942104943104944104945104946104947104948104949104950104951104952104953104954104955104956104957104958104959104960104961104962104963104964104965104966104967104968104969104970104971104972104973104974104975104976104977104978104979104980104981104982104983104984104985104986104987104988104989104990104991104992104993104994104995104996104997104998104999105000105001105002105003105004105005105006105007105008105009105010105011105012105013105014105015105016105017105018105019105020105021105022105023105024105025105026105027105028105029105030105031105032105033105034105035105036105037105038105039105040105041105042105043105044105045105046105047105048105049105050105051105052105053105054105055105056105057105058105059105060105061105062105063105064105065105066105067105068105069105070105071105072105073105074105075105076105077105078105079105080105081105082105083105084105085105086105087105088105089105090105091105092105093105094105095105096105097105098105099105100105101105102105103105104105105105106105107105108105109105110105111105112105113105114105115105116105117105118105119105120105121105122105123105124105125105126105127105128105129105130105131105132105133105134105135105136105137105138105139105140105141105142105143105144105145105146105147105148105149105150105151105152105153105154105155105156105157105158105159105160105161105162105163105164105165105166105167105168105169105170105171105172105173105174105175105176105177105178105179105180105181105182105183105184105185105186105187105188105189105190105191105192105193105194105195105196105197105198105199105200105201105202105203105204105205105206105207105208105209105210105211105212105213105214105215105216105217105218105219105220105221105222105223105224105225105226105227105228105229105230105231105232105233105234105235105236105237105238105239105240105241105242105243105244105245105246105247105248105249105250105251105252105253105254105255105256105257105258105259105260105261105262105263105264105265105266105267105268105269105270105271105272105273105274105275105276105277105278105279105280105281105282105283105284105285105286105287105288105289105290105291105292105293105294105295105296105297105298105299105300105301105302105303105304105305105306105307105308105309105310105311105312105313105314105315105316105317105318105319105320105321105322105323105324105325105326105327105328105329105330105331105332105333105334105335105336105337105338105339105340105341105342105343105344105345105346105347105348105349105350105351105352105353105354105355105356105357105358105359105360105361105362105363105364105365105366105367105368105369105370105371105372105373105374105375105376105377105378105379105380105381105382105383105384105385105386105387105388105389105390105391105392105393105394105395105396105397105398105399105400105401105402105403105404105405105406105407105408105409105410105411105412105413105414105415105416105417105418105419105420105421105422105423105424105425105426105427105428105429105430105431105432105433105434105435105436105437105438105439105440105441105442105443105444105445105446105447105448105449105450105451105452105453105454105455105456105457105458105459105460105461105462105463105464105465105466105467105468105469105470105471105472105473105474105475105476105477105478105479105480105481105482105483105484105485105486105487105488105489105490105491105492105493105494105495105496105497105498105499105500105501105502105503105504105505105506105507105508105509105510105511105512105513105514105515105516105517105518105519105520105521105522105523105524105525105526105527105528105529105530105531105532105533105534105535105536105537105538105539105540105541105542105543105544105545105546105547105548105549105550105551105552105553105554105555105556105557105558105559105560105561105562105563105564105565105566105567105568105569105570105571105572105573105574105575105576105577105578105579105580105581105582105583105584105585105586105587105588105589105590105591105592105593105594105595105596105597105598105599105600105601105602105603105604105605105606105607105608105609105610105611105612105613105614105615105616105617105618105619105620105621105622105623105624105625105626105627105628105629105630105631105632105633105634105635105636105637105638105639105640105641105642105643105644105645105646105647105648105649105650105651105652105653105654105655105656105657105658105659105660105661105662105663105664105665105666105667105668105669105670105671105672105673105674105675105676105677105678105679105680105681105682105683105684105685105686105687105688105689105690105691105692105693105694105695105696105697105698105699105700105701105702105703105704105705105706105707105708105709105710105711105712105713105714105715105716105717105718105719105720105721105722105723105724105725105726105727105728105729105730105731105732105733105734105735105736105737105738105739105740105741105742105743105744105745105746105747105748105749105750105751105752105753105754105755105756105757105758105759105760105761105762105763105764105765105766105767105768105769105770105771105772105773105774105775105776105777105778105779105780105781105782105783105784105785105786105787105788105789105790105791105792105793105794105795105796105797105798105799105800105801105802105803105804105805105806105807105808105809105810105811105812105813105814105815105816105817105818105819105820105821105822105823105824105825105826105827105828105829105830105831105832105833105834105835105836105837105838105839105840105841105842105843105844105845105846105847105848105849105850105851105852105853105854105855105856105857105858105859105860105861105862105863105864105865105866105867105868105869105870105871105872105873105874105875105876105877105878105879105880105881105882105883105884105885105886105887105888105889105890105891105892105893105894105895105896105897105898105899105900105901105902105903105904105905105906105907105908105909105910105911105912105913105914105915105916105917105918105919105920105921105922105923105924105925105926105927105928105929105930105931105932105933105934105935105936105937105938105939105940105941105942105943105944105945105946105947105948105949105950105951105952105953105954105955105956105957105958105959105960105961105962105963105964105965105966105967105968105969105970105971105972105973105974105975105976105977105978105979105980105981105982105983105984105985105986105987105988105989105990105991105992105993105994105995105996105997105998105999106000106001106002106003106004106005106006106007106008106009106010106011106012106013106014106015106016106017106018106019106020106021106022106023106024106025106026106027106028106029106030106031106032106033106034106035106036106037106038106039106040106041106042106043106044106045106046106047106048106049106050106051106052106053106054106055106056106057106058106059106060106061106062106063106064106065106066106067106068106069106070106071106072106073106074106075106076106077106078106079106080106081106082106083106084106085106086106087106088106089106090106091106092106093106094106095106096106097106098106099106100106101106102106103106104106105106106106107106108106109106110106111106112106113106114106115106116106117106118106119106120106121106122106123106124106125106126106127106128106129106130106131106132106133106134106135106136106137106138106139106140106141106142106143106144106145106146106147106148106149106150106151106152106153106154106155106156106157106158106159106160106161106162106163106164106165106166106167106168106169106170106171106172106173106174106175106176106177106178106179106180106181106182106183106184106185106186106187106188106189106190106191106192106193106194106195106196106197106198106199106200106201106202106203106204106205106206106207106208106209106210106211106212106213106214106215106216106217106218106219106220106221106222106223106224106225106226106227106228106229106230106231106232106233106234106235106236106237106238106239106240106241106242106243106244106245106246106247106248106249106250106251106252106253106254106255106256106257106258106259106260106261106262106263106264106265106266106267106268106269106270106271106272106273106274106275106276106277106278106279106280106281106282106283106284106285106286106287106288106289106290106291106292106293106294106295106296106297106298106299106300106301106302106303106304106305106306106307106308106309106310106311106312106313106314106315106316106317106318106319106320106321106322106323106324106325106326106327106328106329106330106331106332106333106334106335106336106337106338106339106340106341106342106343106344106345106346106347106348106349106350106351106352106353106354106355106356106357106358106359106360106361106362106363106364106365106366106367106368106369106370106371106372106373106374106375106376106377106378106379106380106381106382106383106384106385106386106387106388106389106390106391106392106393106394106395106396106397106398106399106400106401106402106403106404106405106406106407106408106409106410106411106412106413106414106415106416106417106418106419106420106421106422106423106424106425106426106427106428106429106430106431106432106433106434106435106436106437106438106439106440106441106442106443106444106445106446106447106448106449106450106451106452106453106454106455106456106457106458106459106460106461106462106463106464106465106466106467106468106469106470106471106472106473106474106475106476106477106478106479106480106481106482106483106484106485106486106487106488106489106490106491106492106493106494106495106496106497106498106499106500106501106502106503106504106505106506106507106508106509106510106511106512106513106514106515106516106517106518106519106520106521106522106523106524106525106526106527106528106529106530106531106532106533106534106535106536106537106538106539106540106541106542106543106544106545106546106547106548106549106550106551106552106553106554106555106556106557106558106559106560106561106562106563106564106565106566106567106568106569106570106571106572106573106574106575106576106577106578106579106580106581106582106583106584106585106586106587106588106589106590106591106592106593106594106595106596106597106598106599106600106601106602106603106604106605106606106607106608106609106610106611106612106613106614106615106616106617106618106619106620106621106622106623106624106625106626106627106628106629106630106631106632106633106634106635106636106637106638106639106640106641106642106643106644106645106646106647106648106649106650106651106652106653106654106655106656106657106658106659106660106661106662106663106664106665106666106667106668106669106670106671106672106673106674106675106676106677106678106679106680106681106682106683106684106685106686106687106688106689106690106691106692106693106694106695106696106697106698106699106700106701106702106703106704106705106706106707106708106709106710106711106712106713106714106715106716106717106718106719106720106721106722106723106724106725106726106727106728106729106730106731106732106733106734106735106736106737106738106739106740106741106742106743106744106745106746106747106748106749106750106751106752106753106754106755106756106757106758106759106760106761106762106763106764106765106766106767106768106769106770106771106772106773106774106775106776106777106778106779106780106781106782106783106784106785106786106787106788106789106790106791106792106793106794106795106796106797106798106799106800106801106802106803106804106805106806106807106808106809106810106811106812106813106814106815106816106817106818106819106820106821106822106823106824106825106826106827106828106829106830106831106832106833106834106835106836106837106838106839106840106841106842106843106844106845106846106847106848106849106850106851106852106853106854106855106856106857106858106859106860106861106862106863106864106865106866106867106868106869106870106871106872106873106874106875106876106877106878106879106880106881106882106883106884106885106886106887106888106889106890106891106892106893106894106895106896106897106898106899106900106901106902106903106904106905106906106907106908106909106910106911106912106913106914106915106916106917106918106919106920106921106922106923106924106925106926106927106928106929106930106931106932106933106934106935106936106937106938106939106940106941106942106943106944106945106946106947106948106949106950106951106952106953106954106955106956106957106958106959106960106961106962106963106964106965106966106967106968106969106970106971106972106973106974106975106976106977106978106979106980106981106982106983106984106985106986106987106988106989106990106991106992106993106994106995106996106997106998106999107000107001107002107003107004107005107006107007107008107009107010107011107012107013107014107015107016107017107018107019107020107021107022107023107024107025107026107027107028107029107030107031107032107033107034107035107036107037107038107039107040107041107042107043107044107045107046107047107048107049107050107051107052107053107054107055107056107057107058107059107060107061107062107063107064107065107066107067107068107069107070107071107072107073107074107075107076107077107078107079107080107081107082107083107084107085107086107087107088107089107090107091107092107093107094107095107096107097107098107099107100107101107102107103107104107105107106107107107108107109107110107111107112107113107114107115107116107117107118107119107120107121107122107123107124107125107126107127107128107129107130107131107132107133107134107135107136107137107138107139107140107141107142107143107144107145107146107147107148107149107150107151107152107153107154107155107156107157107158107159107160107161107162107163107164107165107166107167107168107169107170107171107172107173107174107175107176107177107178107179107180107181107182107183107184107185107186107187107188107189107190107191107192107193107194107195107196107197107198107199107200107201107202107203107204107205107206107207107208107209107210107211107212107213107214107215107216107217107218107219107220107221107222107223107224107225107226107227107228107229107230107231107232107233107234107235107236107237107238107239107240107241107242107243107244107245107246107247107248107249107250107251107252107253107254107255107256107257107258107259107260107261107262107263107264107265107266107267107268107269107270107271107272107273107274107275107276107277107278107279107280107281107282107283107284107285107286107287107288107289107290107291107292107293107294107295107296107297107298107299107300107301107302107303107304107305107306107307107308107309107310107311107312107313107314107315107316107317107318107319107320107321107322107323107324107325107326107327107328107329107330107331107332107333107334107335107336107337107338107339107340107341107342107343107344107345107346107347107348107349107350107351107352107353107354107355107356107357107358107359107360107361107362107363107364107365107366107367107368107369107370107371107372107373107374107375107376107377107378107379107380107381107382107383107384107385107386107387107388107389107390107391107392107393107394107395107396107397107398107399107400107401107402107403107404107405107406107407107408107409107410107411107412107413107414107415107416107417107418107419107420107421107422107423107424107425107426107427107428107429107430107431107432107433107434107435107436107437107438107439107440107441107442107443107444107445107446107447107448107449107450107451107452107453107454107455107456107457107458107459107460107461107462107463107464107465107466107467107468107469107470107471107472107473107474107475107476107477107478107479107480107481107482107483107484107485107486107487107488107489107490107491107492107493107494107495107496107497107498107499107500107501107502107503107504107505107506107507107508107509107510107511107512107513107514107515107516107517107518107519107520107521107522107523107524107525107526107527107528107529107530107531107532107533107534107535107536107537107538107539107540107541107542107543107544107545107546107547107548107549107550107551107552107553107554107555107556107557107558107559107560107561107562107563107564107565107566107567107568107569107570107571107572107573107574107575107576107577107578107579107580107581107582107583107584107585107586107587107588107589107590107591107592107593107594107595107596107597107598107599107600107601107602107603107604107605107606107607107608107609107610107611107612107613107614107615107616107617107618107619107620107621107622107623107624107625107626107627107628107629107630107631107632107633107634107635107636107637107638107639107640107641107642107643107644107645107646107647107648107649107650107651107652107653107654107655107656107657107658107659107660107661107662107663107664107665107666107667107668107669107670107671107672107673107674107675107676107677107678107679107680107681107682107683107684107685107686107687107688107689107690107691107692107693107694107695107696107697107698107699107700107701107702107703107704107705107706107707107708107709107710107711107712107713107714107715107716107717107718107719107720107721107722107723107724107725107726107727107728107729107730107731107732107733107734107735107736107737107738107739107740107741107742107743107744107745107746107747107748107749107750107751107752107753107754107755107756107757107758107759107760107761107762107763107764107765107766107767107768107769107770107771107772107773107774107775107776107777107778107779107780107781107782107783107784107785107786107787107788107789107790107791107792107793107794107795107796107797107798107799107800107801107802107803107804107805107806107807107808107809107810107811107812107813107814107815107816107817107818107819107820107821107822107823107824107825107826107827107828107829107830107831107832107833107834107835107836107837107838107839107840107841107842107843107844107845107846107847107848107849107850107851107852107853107854107855107856107857107858107859107860107861107862107863107864107865107866107867107868107869107870107871107872107873107874107875107876107877107878107879107880107881107882107883107884107885107886107887107888107889107890107891107892107893107894107895107896107897107898107899107900107901107902107903107904107905107906107907107908107909107910107911107912107913107914107915107916107917107918107919107920107921107922107923107924107925107926107927107928107929107930107931107932107933107934107935107936107937107938107939107940107941107942107943107944107945107946107947107948107949107950107951107952107953107954107955107956107957107958107959107960107961107962107963107964107965107966107967107968107969107970107971107972107973107974107975107976107977107978107979107980107981107982107983107984107985107986107987107988107989107990107991107992107993107994107995107996107997107998107999108000108001108002108003108004108005108006108007108008108009108010108011108012108013108014108015108016108017108018108019108020108021108022108023108024108025108026108027108028108029108030108031108032108033108034108035108036108037108038108039108040108041108042108043108044108045108046108047108048108049108050108051108052108053108054108055108056108057108058108059108060108061108062108063108064108065108066108067108068108069108070108071108072108073108074108075108076108077108078108079108080108081108082108083108084108085108086108087108088108089108090108091108092108093108094108095108096108097108098108099108100108101108102108103108104108105108106108107108108108109108110108111108112108113108114108115108116108117108118108119108120108121108122108123108124108125108126108127108128108129108130108131108132108133108134108135108136108137108138108139108140108141108142108143108144108145108146108147108148108149108150108151108152108153108154108155108156108157108158108159108160108161108162108163108164108165108166108167108168108169108170108171108172108173108174108175108176108177108178108179108180108181108182108183108184108185108186108187108188108189108190108191108192108193108194108195108196108197108198108199108200108201108202108203108204108205108206108207108208108209108210108211108212108213108214108215108216108217108218108219108220108221108222108223108224108225108226108227108228108229108230108231108232108233108234108235108236108237108238108239108240108241108242108243108244108245108246108247108248108249108250108251108252108253108254108255108256108257108258108259108260108261108262108263108264108265108266108267108268108269108270108271108272108273108274108275108276108277108278108279108280108281108282108283108284108285108286108287108288108289108290108291108292108293108294108295108296108297108298108299108300108301108302108303108304108305108306108307108308108309108310108311108312108313108314108315108316108317108318108319108320108321108322108323108324108325108326108327108328108329108330108331108332108333108334108335108336108337108338108339108340108341108342108343108344108345108346108347108348108349108350108351108352108353108354108355108356108357108358108359108360108361108362108363108364108365108366108367108368108369108370108371108372108373108374108375108376108377108378108379108380108381108382108383108384108385108386108387108388108389108390108391108392108393108394108395108396108397108398108399108400108401108402108403108404108405108406108407108408108409108410108411108412108413108414108415108416108417108418108419108420108421108422108423108424108425108426108427108428108429108430108431108432108433108434108435108436108437108438108439108440108441108442108443108444108445108446108447108448108449108450108451108452108453108454108455108456108457108458108459108460108461108462108463108464108465108466108467108468108469108470108471108472108473108474108475108476108477108478108479108480108481108482108483108484108485108486108487108488108489108490108491108492108493108494108495108496108497108498108499108500108501108502108503108504108505108506108507108508108509108510108511108512108513108514108515108516108517108518108519108520108521108522108523108524108525108526108527108528108529108530108531108532108533108534108535108536108537108538108539108540108541108542108543108544108545108546108547108548108549108550108551108552108553108554108555108556108557108558108559108560108561108562108563108564108565108566108567108568108569108570108571108572108573108574108575108576108577108578108579108580108581108582108583108584108585108586108587108588108589108590108591108592108593108594108595108596108597108598108599108600108601108602108603108604108605108606108607108608108609108610108611108612108613108614108615108616108617108618108619108620108621108622108623108624108625108626108627108628108629108630108631108632108633108634108635108636108637108638108639108640108641108642108643108644108645108646108647108648108649108650108651108652108653108654108655108656108657108658108659108660108661108662108663108664108665108666108667108668108669108670108671108672108673108674108675108676108677108678108679108680108681108682108683108684108685108686108687108688108689108690108691108692108693108694108695108696108697108698108699108700108701108702108703108704108705108706108707108708108709108710108711108712108713108714108715108716108717108718108719108720108721108722108723108724108725108726108727108728108729108730108731108732108733108734108735108736108737108738108739108740108741108742108743108744108745108746108747108748108749108750108751108752108753108754108755108756108757108758108759108760108761108762108763108764108765108766108767108768108769108770108771108772108773108774108775108776108777108778108779108780108781108782108783108784108785108786108787108788108789108790108791108792108793108794108795108796108797108798108799108800108801108802108803108804108805108806108807108808108809108810108811108812108813108814108815108816108817108818108819108820108821108822108823108824108825108826108827108828108829108830108831108832108833108834108835108836108837108838108839108840108841108842108843108844108845108846108847108848108849108850108851108852108853108854108855108856108857108858108859108860108861108862108863108864108865108866108867108868108869108870108871108872108873108874108875108876108877108878108879108880108881108882108883108884108885108886108887108888108889108890108891108892108893108894108895108896108897108898108899108900108901108902108903108904108905108906108907108908108909108910108911108912108913108914108915108916108917108918108919108920108921108922108923108924108925108926108927108928108929108930108931108932108933108934108935108936108937108938108939108940108941108942108943108944108945108946108947108948108949108950108951108952108953108954108955108956108957108958108959108960108961108962108963108964108965108966108967108968108969108970108971108972108973108974108975108976108977108978108979108980108981108982108983108984108985108986108987108988108989108990108991108992108993108994108995108996108997108998108999109000109001109002109003109004109005109006109007109008109009109010109011109012109013109014109015109016109017109018109019109020109021109022109023109024109025109026109027109028109029109030109031109032109033109034109035109036109037109038109039109040109041109042109043109044109045109046109047109048109049109050109051109052109053109054109055109056109057109058109059109060109061109062109063109064109065109066109067109068109069109070109071109072109073109074109075109076109077109078109079109080109081109082109083109084109085109086109087109088109089109090109091109092109093109094109095109096109097109098109099109100109101109102109103109104109105109106109107109108109109109110109111109112109113109114109115109116109117109118109119109120109121109122109123109124109125109126109127109128109129109130109131109132109133109134109135109136109137109138109139109140109141109142109143109144109145109146109147109148109149109150109151109152109153109154109155109156109157109158109159109160109161109162109163109164109165109166109167109168109169109170109171109172109173109174109175109176109177109178109179109180109181109182109183109184109185109186109187109188109189109190109191109192109193109194109195109196109197109198109199109200109201109202109203109204109205109206109207109208109209109210109211109212109213109214109215109216109217109218109219109220109221109222109223109224109225109226109227109228109229109230109231109232109233109234109235109236109237109238109239109240109241109242109243109244109245109246109247109248109249109250109251109252109253109254109255109256109257109258109259109260109261109262109263109264109265109266109267109268109269109270109271109272109273109274109275109276109277109278109279109280109281109282109283109284109285109286109287109288109289109290109291109292109293109294109295109296109297109298109299109300109301109302109303109304109305109306109307109308109309109310109311109312109313109314109315109316109317109318109319109320109321109322109323109324109325109326109327109328109329109330109331109332109333109334109335109336109337109338109339109340109341109342109343109344109345109346109347109348109349109350109351109352109353109354109355109356109357109358109359109360109361109362109363109364109365109366109367109368109369109370109371109372109373109374109375109376109377109378109379109380109381109382109383109384109385109386109387109388109389109390109391109392109393109394109395109396109397109398109399109400109401109402109403109404109405109406109407109408109409109410109411109412109413109414109415109416109417109418109419109420109421109422109423109424109425109426109427109428109429109430109431109432109433109434109435109436109437109438109439109440109441109442109443109444109445109446109447109448109449109450109451109452109453109454109455109456109457109458109459109460109461109462109463109464109465109466109467109468109469109470109471109472109473109474109475109476109477109478109479109480109481109482109483109484109485109486109487109488109489109490109491109492109493109494109495109496109497109498109499109500109501109502109503109504109505109506109507109508109509109510109511109512109513109514109515109516109517109518109519109520109521109522109523109524109525109526109527109528109529109530109531109532109533109534109535109536109537109538109539109540109541109542109543109544109545109546109547109548109549109550109551109552109553109554109555109556109557109558109559109560109561109562109563109564109565109566109567109568109569109570109571109572109573109574109575109576109577109578109579109580109581109582109583109584109585109586109587109588109589109590109591109592109593109594109595109596109597109598109599109600109601109602109603109604109605109606109607109608109609109610109611109612109613109614109615109616109617109618109619109620109621109622109623109624109625109626109627109628109629109630109631109632109633109634109635109636109637109638109639109640109641109642109643109644109645109646109647109648109649109650109651109652109653109654109655109656109657109658109659109660109661109662109663109664109665109666109667109668109669109670109671109672109673109674109675109676109677109678109679109680109681109682109683109684109685109686109687109688109689109690109691109692109693109694109695109696109697109698109699109700109701109702109703109704109705109706109707109708109709109710109711109712109713109714109715109716109717109718109719109720109721109722109723109724109725109726109727109728109729109730109731109732109733109734109735109736109737109738109739109740109741109742109743109744109745109746109747109748109749109750109751109752109753109754109755109756109757109758109759109760109761109762109763109764109765109766109767109768109769109770109771109772109773109774109775109776109777109778109779109780109781109782109783109784109785109786109787109788109789109790109791109792109793109794109795109796109797109798109799109800109801109802109803109804109805109806109807109808109809109810109811109812109813109814109815109816109817109818109819109820109821109822109823109824109825109826109827109828109829109830109831109832109833109834109835109836109837109838109839109840109841109842109843109844109845109846109847109848109849109850109851109852109853109854109855109856109857109858109859109860109861109862109863109864109865109866109867109868109869109870109871109872109873109874109875109876109877109878109879109880109881109882109883109884109885109886109887109888109889109890109891109892109893109894109895109896109897109898109899109900109901109902109903109904109905109906109907109908109909109910109911109912109913109914109915109916109917109918109919109920109921109922109923109924109925109926109927109928109929109930109931109932109933109934109935109936109937109938109939109940109941109942109943109944109945109946109947109948109949109950109951109952109953109954109955109956109957109958109959109960109961109962109963109964109965109966109967109968109969109970109971109972109973109974109975109976109977109978109979109980109981109982109983109984109985109986109987109988109989109990109991109992109993109994109995109996109997109998109999110000110001110002110003110004110005110006110007110008110009110010110011110012110013110014110015110016110017110018110019110020110021110022110023110024110025110026110027110028110029110030110031110032110033110034110035110036110037110038110039110040110041110042110043110044110045110046110047110048110049110050110051110052110053110054110055110056110057110058110059110060110061110062110063110064110065110066110067110068110069110070110071110072110073110074110075110076110077110078110079110080110081110082110083110084110085110086110087110088110089110090110091110092110093110094110095110096110097110098110099110100110101110102110103110104110105110106110107110108110109110110110111110112110113110114110115110116110117110118110119110120110121110122110123110124110125110126110127110128110129110130110131110132110133110134110135110136110137110138110139110140110141110142110143110144110145110146110147110148110149110150110151110152110153110154110155110156110157110158110159110160110161110162110163110164110165110166110167110168110169110170110171110172110173110174110175110176110177110178110179110180110181110182110183110184110185110186110187110188110189110190110191110192110193110194110195110196110197110198110199110200110201110202110203110204110205110206110207110208110209110210110211110212110213110214110215110216110217110218110219110220110221110222110223110224110225110226110227110228110229110230110231110232110233110234110235110236110237110238110239110240110241110242110243110244110245110246110247110248110249110250110251110252110253110254110255110256110257110258110259110260110261110262110263110264110265110266110267110268110269110270110271110272110273110274110275110276110277110278110279110280110281110282110283110284110285110286110287110288110289110290110291110292110293110294110295110296110297110298110299110300110301110302110303110304110305110306110307110308110309110310110311110312110313110314110315110316110317110318110319110320110321110322110323110324110325110326110327110328110329110330110331110332110333110334110335110336110337110338110339110340110341110342110343110344110345110346110347110348110349110350110351110352110353110354110355110356110357110358110359110360110361110362110363110364110365110366110367110368110369110370110371110372110373110374110375110376110377110378110379110380110381110382110383110384110385110386110387110388110389110390110391110392110393110394110395110396110397110398110399110400110401110402110403110404110405110406110407110408110409110410110411110412110413110414110415110416110417110418110419110420110421110422110423110424110425110426110427110428110429110430110431110432110433110434110435110436110437110438110439110440110441110442110443110444110445110446110447110448110449110450110451110452110453110454110455110456110457110458110459110460110461110462110463110464110465110466110467110468110469110470110471110472110473110474110475110476110477110478110479110480110481110482110483110484110485110486110487110488110489110490110491110492110493110494110495110496110497110498110499110500110501110502110503110504110505110506110507110508110509110510110511110512110513110514110515110516110517110518110519110520110521110522110523110524110525110526110527110528110529110530110531110532110533110534110535110536110537110538110539110540110541110542110543110544110545110546110547110548110549110550110551110552110553110554110555110556110557110558110559110560110561110562110563110564110565110566110567110568110569110570110571110572110573110574110575110576110577110578110579110580110581110582110583110584110585110586110587110588110589110590110591110592110593110594110595110596110597110598110599110600110601110602110603110604110605110606110607110608110609110610110611110612110613110614110615110616110617110618110619110620110621110622110623110624110625110626110627110628110629110630110631110632110633110634110635110636110637110638110639110640110641110642110643110644110645110646110647110648110649110650110651110652110653110654110655110656110657110658110659110660110661110662110663110664110665110666110667110668110669110670110671110672110673110674110675110676110677110678110679110680110681110682110683110684110685110686110687110688110689110690110691110692110693110694110695110696110697110698110699110700110701110702110703110704110705110706110707110708110709110710110711110712110713110714110715110716110717110718110719110720110721110722110723110724110725110726110727110728110729110730110731110732110733110734110735110736110737110738110739110740110741110742110743110744110745110746110747110748110749110750110751110752110753110754110755110756110757110758110759110760110761110762110763110764110765110766110767110768110769110770110771110772110773110774110775110776110777110778110779110780110781110782110783110784110785110786110787110788110789110790110791110792110793110794110795110796110797110798110799110800110801110802110803110804110805110806110807110808110809110810110811110812110813110814110815110816110817110818110819110820110821110822110823110824110825110826110827110828110829110830110831110832110833110834110835110836110837110838110839110840110841110842110843110844110845110846110847110848110849110850110851110852110853110854110855110856110857110858110859110860110861110862110863110864110865110866110867110868110869110870110871110872110873110874110875110876110877110878110879110880110881110882110883110884110885110886110887110888110889110890110891110892110893110894110895110896110897110898110899110900110901110902110903110904110905110906110907110908110909110910110911110912110913110914110915110916110917110918110919110920110921110922110923110924110925110926110927110928110929110930110931110932110933110934110935110936110937110938110939110940110941110942110943110944110945110946110947110948110949110950110951110952110953110954110955110956110957110958110959110960110961110962110963110964110965110966110967110968110969110970110971110972110973110974110975110976110977110978110979110980110981110982110983110984110985110986110987110988110989110990110991110992110993110994110995110996110997110998110999111000111001111002111003111004111005111006111007111008111009111010111011111012111013111014111015111016111017111018111019111020111021111022111023111024111025111026111027111028111029111030111031111032111033111034111035111036111037111038111039111040111041111042111043111044111045111046111047111048111049111050111051111052111053111054111055111056111057111058111059111060111061111062111063111064111065111066111067111068111069111070111071111072111073111074111075111076111077111078111079111080111081111082111083111084111085111086111087111088111089111090111091111092111093111094111095111096111097111098111099111100111101111102111103111104111105111106111107111108111109111110111111111112111113111114111115111116111117111118111119111120111121111122111123111124111125111126111127111128111129111130111131111132111133111134111135111136111137111138111139111140111141111142111143111144111145111146111147111148111149111150111151111152111153111154111155111156111157111158111159111160111161111162111163111164111165111166111167111168111169111170111171111172111173111174111175111176111177111178111179111180111181111182111183111184111185111186111187111188111189111190111191111192111193111194111195111196111197111198111199111200111201111202111203111204111205111206111207111208111209111210111211111212111213111214111215111216111217111218111219111220111221111222111223111224111225111226111227111228111229111230111231111232111233111234111235111236111237111238111239111240111241111242111243111244111245111246111247111248111249111250111251111252111253111254111255111256111257111258111259111260111261111262111263111264111265111266111267111268111269111270111271111272111273111274111275111276111277111278111279111280111281111282111283111284111285111286111287111288111289111290111291111292111293111294111295111296111297111298111299111300111301111302111303111304111305111306111307111308111309111310111311111312111313111314111315111316111317111318111319111320111321111322111323111324111325111326111327111328111329111330111331111332111333111334111335111336111337111338111339111340111341111342111343111344111345111346111347111348111349111350111351111352111353111354111355111356111357111358111359111360111361111362111363111364111365111366111367111368111369111370111371111372111373111374111375111376111377111378111379111380111381111382111383111384111385111386111387111388111389111390111391111392111393111394111395111396111397111398111399111400111401111402111403111404111405111406111407111408111409111410111411111412111413111414111415111416111417111418111419111420111421111422111423111424111425111426111427111428111429111430111431111432111433111434111435111436111437111438111439111440
  1. var BabylonViewer =
  2. /******/ (function(modules) { // webpackBootstrap
  3. /******/ // The module cache
  4. /******/ var installedModules = {};
  5. /******/
  6. /******/ // The require function
  7. /******/ function __webpack_require__(moduleId) {
  8. /******/
  9. /******/ // Check if module is in cache
  10. /******/ if(installedModules[moduleId]) {
  11. /******/ return installedModules[moduleId].exports;
  12. /******/ }
  13. /******/ // Create a new module (and put it into the cache)
  14. /******/ var module = installedModules[moduleId] = {
  15. /******/ i: moduleId,
  16. /******/ l: false,
  17. /******/ exports: {}
  18. /******/ };
  19. /******/
  20. /******/ // Execute the module function
  21. /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
  22. /******/
  23. /******/ // Flag the module as loaded
  24. /******/ module.l = true;
  25. /******/
  26. /******/ // Return the exports of the module
  27. /******/ return module.exports;
  28. /******/ }
  29. /******/
  30. /******/
  31. /******/ // expose the modules object (__webpack_modules__)
  32. /******/ __webpack_require__.m = modules;
  33. /******/
  34. /******/ // expose the module cache
  35. /******/ __webpack_require__.c = installedModules;
  36. /******/
  37. /******/ // define getter function for harmony exports
  38. /******/ __webpack_require__.d = function(exports, name, getter) {
  39. /******/ if(!__webpack_require__.o(exports, name)) {
  40. /******/ Object.defineProperty(exports, name, {
  41. /******/ configurable: false,
  42. /******/ enumerable: true,
  43. /******/ get: getter
  44. /******/ });
  45. /******/ }
  46. /******/ };
  47. /******/
  48. /******/ // getDefaultExport function for compatibility with non-harmony modules
  49. /******/ __webpack_require__.n = function(module) {
  50. /******/ var getter = module && module.__esModule ?
  51. /******/ function getDefault() { return module['default']; } :
  52. /******/ function getModuleExports() { return module; };
  53. /******/ __webpack_require__.d(getter, 'a', getter);
  54. /******/ return getter;
  55. /******/ };
  56. /******/
  57. /******/ // Object.prototype.hasOwnProperty.call
  58. /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
  59. /******/
  60. /******/ // __webpack_public_path__
  61. /******/ __webpack_require__.p = "";
  62. /******/
  63. /******/ // Load entry module and return exports
  64. /******/ return __webpack_require__(__webpack_require__.s = 15);
  65. /******/ })
  66. /************************************************************************/
  67. /******/ ([
  68. /* 0 */
  69. /***/ (function(module, exports, __webpack_require__) {
  70. /* WEBPACK VAR INJECTION */(function(global) {var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  71. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  72. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  73. 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;
  74. return c > 3 && r && Object.defineProperty(target, key, r), r;
  75. };
  76. var __extends = (this && this.__extends) || (function () {
  77. var extendStatics = Object.setPrototypeOf ||
  78. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  79. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  80. return function (d, b) {
  81. extendStatics(d, b);
  82. function __() { this.constructor = d; }
  83. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  84. };
  85. })();
  86. var BABYLON;
  87. (function (BABYLON) {
  88. /**
  89. * EffectFallbacks can be used to add fallbacks (properties to disable) to certain properties when desired to improve performance.
  90. * (Eg. Start at high quality with reflection and fog, if fps is low, remove reflection, if still low remove fog)
  91. */
  92. var EffectFallbacks = /** @class */ (function () {
  93. function EffectFallbacks() {
  94. this._defines = {};
  95. this._currentRank = 32;
  96. this._maxRank = -1;
  97. }
  98. /**
  99. * Removes the fallback from the bound mesh.
  100. */
  101. EffectFallbacks.prototype.unBindMesh = function () {
  102. this._mesh = null;
  103. };
  104. /**
  105. * Adds a fallback on the specified property.
  106. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  107. * @param define The name of the define in the shader
  108. */
  109. EffectFallbacks.prototype.addFallback = function (rank, define) {
  110. if (!this._defines[rank]) {
  111. if (rank < this._currentRank) {
  112. this._currentRank = rank;
  113. }
  114. if (rank > this._maxRank) {
  115. this._maxRank = rank;
  116. }
  117. this._defines[rank] = new Array();
  118. }
  119. this._defines[rank].push(define);
  120. };
  121. /**
  122. * Sets the mesh to use CPU skinning when needing to fallback.
  123. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  124. * @param mesh The mesh to use the fallbacks.
  125. */
  126. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  127. this._mesh = mesh;
  128. if (rank < this._currentRank) {
  129. this._currentRank = rank;
  130. }
  131. if (rank > this._maxRank) {
  132. this._maxRank = rank;
  133. }
  134. };
  135. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  136. /**
  137. * Checks to see if more fallbacks are still availible.
  138. */
  139. get: function () {
  140. return this._currentRank <= this._maxRank;
  141. },
  142. enumerable: true,
  143. configurable: true
  144. });
  145. /**
  146. * Removes the defines that shoould be removed when falling back.
  147. * @param currentDefines defines the current define statements for the shader.
  148. * @param effect defines the current effect we try to compile
  149. * @returns The resulting defines with defines of the current rank removed.
  150. */
  151. EffectFallbacks.prototype.reduce = function (currentDefines, effect) {
  152. // First we try to switch to CPU skinning
  153. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0 && this._mesh.material) {
  154. this._mesh.computeBonesUsingShaders = false;
  155. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  156. var scene = this._mesh.getScene();
  157. for (var index = 0; index < scene.meshes.length; index++) {
  158. var otherMesh = scene.meshes[index];
  159. if (!otherMesh.material) {
  160. continue;
  161. }
  162. if (!otherMesh.computeBonesUsingShaders || otherMesh.numBoneInfluencers === 0) {
  163. continue;
  164. }
  165. if (otherMesh.material.getEffect() === effect) {
  166. otherMesh.computeBonesUsingShaders = false;
  167. }
  168. else {
  169. for (var _i = 0, _a = otherMesh.subMeshes; _i < _a.length; _i++) {
  170. var subMesh = _a[_i];
  171. var subMeshEffect = subMesh.effect;
  172. if (subMeshEffect === effect) {
  173. otherMesh.computeBonesUsingShaders = false;
  174. break;
  175. }
  176. }
  177. }
  178. }
  179. }
  180. else {
  181. var currentFallbacks = this._defines[this._currentRank];
  182. if (currentFallbacks) {
  183. for (var index = 0; index < currentFallbacks.length; index++) {
  184. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  185. }
  186. }
  187. this._currentRank++;
  188. }
  189. return currentDefines;
  190. };
  191. return EffectFallbacks;
  192. }());
  193. BABYLON.EffectFallbacks = EffectFallbacks;
  194. /**
  195. * Options to be used when creating an effect.
  196. */
  197. var EffectCreationOptions = /** @class */ (function () {
  198. function EffectCreationOptions() {
  199. }
  200. return EffectCreationOptions;
  201. }());
  202. BABYLON.EffectCreationOptions = EffectCreationOptions;
  203. /**
  204. * Effect containing vertex and fragment shader that can be executed on an object.
  205. */
  206. var Effect = /** @class */ (function () {
  207. /**
  208. * Instantiates an effect.
  209. * An effect can be used to create/manage/execute vertex and fragment shaders.
  210. * @param baseName Name of the effect.
  211. * @param attributesNamesOrOptions List of attribute names that will be passed to the shader or set of all options to create the effect.
  212. * @param uniformsNamesOrEngine List of uniform variable names that will be passed to the shader or the engine that will be used to render effect.
  213. * @param samplers List of sampler variables that will be passed to the shader.
  214. * @param engine Engine to be used to render the effect
  215. * @param defines Define statements to be added to the shader.
  216. * @param fallbacks Possible fallbacks for this effect to improve performance when needed.
  217. * @param onCompiled Callback that will be called when the shader is compiled.
  218. * @param onError Callback that will be called if an error occurs during shader compilation.
  219. * @param indexParameters Parameters to be used with Babylons include syntax to iterate over an array (eg. {lights: 10})
  220. */
  221. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  222. if (samplers === void 0) { samplers = null; }
  223. if (defines === void 0) { defines = null; }
  224. if (fallbacks === void 0) { fallbacks = null; }
  225. if (onCompiled === void 0) { onCompiled = null; }
  226. if (onError === void 0) { onError = null; }
  227. var _this = this;
  228. /**
  229. * Unique ID of the effect.
  230. */
  231. this.uniqueId = 0;
  232. /**
  233. * Observable that will be called when the shader is compiled.
  234. */
  235. this.onCompileObservable = new BABYLON.Observable();
  236. /**
  237. * Observable that will be called if an error occurs during shader compilation.
  238. */
  239. this.onErrorObservable = new BABYLON.Observable();
  240. /**
  241. * Observable that will be called when effect is bound.
  242. */
  243. this.onBindObservable = new BABYLON.Observable();
  244. this._uniformBuffersNames = {};
  245. this._isReady = false;
  246. this._compilationError = "";
  247. this.name = baseName;
  248. if (attributesNamesOrOptions.attributes) {
  249. var options = attributesNamesOrOptions;
  250. this._engine = uniformsNamesOrEngine;
  251. this._attributesNames = options.attributes;
  252. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  253. this._samplers = options.samplers;
  254. this.defines = options.defines;
  255. this.onError = options.onError;
  256. this.onCompiled = options.onCompiled;
  257. this._fallbacks = options.fallbacks;
  258. this._indexParameters = options.indexParameters;
  259. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  260. if (options.uniformBuffersNames) {
  261. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  262. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  263. }
  264. }
  265. }
  266. else {
  267. this._engine = engine;
  268. this.defines = defines;
  269. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  270. this._samplers = samplers;
  271. this._attributesNames = attributesNamesOrOptions;
  272. this.onError = onError;
  273. this.onCompiled = onCompiled;
  274. this._indexParameters = indexParameters;
  275. this._fallbacks = fallbacks;
  276. }
  277. this.uniqueId = Effect._uniqueIdSeed++;
  278. var vertexSource;
  279. var fragmentSource;
  280. if (baseName.vertexElement) {
  281. vertexSource = document.getElementById(baseName.vertexElement);
  282. if (!vertexSource) {
  283. vertexSource = baseName.vertexElement;
  284. }
  285. }
  286. else {
  287. vertexSource = baseName.vertex || baseName;
  288. }
  289. if (baseName.fragmentElement) {
  290. fragmentSource = document.getElementById(baseName.fragmentElement);
  291. if (!fragmentSource) {
  292. fragmentSource = baseName.fragmentElement;
  293. }
  294. }
  295. else {
  296. fragmentSource = baseName.fragment || baseName;
  297. }
  298. var finalVertexCode;
  299. this._loadVertexShaderAsync(vertexSource)
  300. .then(function (vertexCode) {
  301. return _this._processIncludesAsync(vertexCode);
  302. })
  303. .then(function (vertexCodeWithIncludes) {
  304. finalVertexCode = _this._processShaderConversion(vertexCodeWithIncludes, false);
  305. return _this._loadFragmentShaderAsync(fragmentSource);
  306. })
  307. .then(function (fragmentCode) {
  308. return _this._processIncludesAsync(fragmentCode);
  309. })
  310. .then(function (fragmentCodeWithIncludes) {
  311. var migratedFragmentCode = _this._processShaderConversion(fragmentCodeWithIncludes, true);
  312. if (baseName) {
  313. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  314. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  315. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + finalVertexCode;
  316. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  317. }
  318. else {
  319. _this._vertexSourceCode = finalVertexCode;
  320. _this._fragmentSourceCode = migratedFragmentCode;
  321. }
  322. _this._prepareEffect();
  323. });
  324. }
  325. Object.defineProperty(Effect.prototype, "key", {
  326. /**
  327. * Unique key for this effect
  328. */
  329. get: function () {
  330. return this._key;
  331. },
  332. enumerable: true,
  333. configurable: true
  334. });
  335. /**
  336. * If the effect has been compiled and prepared.
  337. * @returns if the effect is compiled and prepared.
  338. */
  339. Effect.prototype.isReady = function () {
  340. return this._isReady;
  341. };
  342. /**
  343. * The engine the effect was initialized with.
  344. * @returns the engine.
  345. */
  346. Effect.prototype.getEngine = function () {
  347. return this._engine;
  348. };
  349. /**
  350. * The compiled webGL program for the effect
  351. * @returns the webGL program.
  352. */
  353. Effect.prototype.getProgram = function () {
  354. return this._program;
  355. };
  356. /**
  357. * The set of names of attribute variables for the shader.
  358. * @returns An array of attribute names.
  359. */
  360. Effect.prototype.getAttributesNames = function () {
  361. return this._attributesNames;
  362. };
  363. /**
  364. * Returns the attribute at the given index.
  365. * @param index The index of the attribute.
  366. * @returns The location of the attribute.
  367. */
  368. Effect.prototype.getAttributeLocation = function (index) {
  369. return this._attributes[index];
  370. };
  371. /**
  372. * Returns the attribute based on the name of the variable.
  373. * @param name of the attribute to look up.
  374. * @returns the attribute location.
  375. */
  376. Effect.prototype.getAttributeLocationByName = function (name) {
  377. var index = this._attributesNames.indexOf(name);
  378. return this._attributes[index];
  379. };
  380. /**
  381. * The number of attributes.
  382. * @returns the numnber of attributes.
  383. */
  384. Effect.prototype.getAttributesCount = function () {
  385. return this._attributes.length;
  386. };
  387. /**
  388. * Gets the index of a uniform variable.
  389. * @param uniformName of the uniform to look up.
  390. * @returns the index.
  391. */
  392. Effect.prototype.getUniformIndex = function (uniformName) {
  393. return this._uniformsNames.indexOf(uniformName);
  394. };
  395. /**
  396. * Returns the attribute based on the name of the variable.
  397. * @param uniformName of the uniform to look up.
  398. * @returns the location of the uniform.
  399. */
  400. Effect.prototype.getUniform = function (uniformName) {
  401. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  402. };
  403. /**
  404. * Returns an array of sampler variable names
  405. * @returns The array of sampler variable neames.
  406. */
  407. Effect.prototype.getSamplers = function () {
  408. return this._samplers;
  409. };
  410. /**
  411. * The error from the last compilation.
  412. * @returns the error string.
  413. */
  414. Effect.prototype.getCompilationError = function () {
  415. return this._compilationError;
  416. };
  417. /**
  418. * Adds a callback to the onCompiled observable and call the callback imediatly if already ready.
  419. * @param func The callback to be used.
  420. */
  421. Effect.prototype.executeWhenCompiled = function (func) {
  422. if (this.isReady()) {
  423. func(this);
  424. return;
  425. }
  426. this.onCompileObservable.add(function (effect) {
  427. func(effect);
  428. });
  429. };
  430. /** @ignore */
  431. Effect.prototype._loadVertexShaderAsync = function (vertex) {
  432. if (BABYLON.Tools.IsWindowObjectExist()) {
  433. // DOM element ?
  434. if (vertex instanceof HTMLElement) {
  435. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  436. return Promise.resolve(vertexCode);
  437. }
  438. }
  439. // Base64 encoded ?
  440. if (vertex.substr(0, 7) === "base64:") {
  441. var vertexBinary = window.atob(vertex.substr(7));
  442. return Promise.resolve(vertexBinary);
  443. }
  444. // Is in local store ?
  445. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  446. return Promise.resolve(Effect.ShadersStore[vertex + "VertexShader"]);
  447. }
  448. var vertexShaderUrl;
  449. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  450. vertexShaderUrl = vertex;
  451. }
  452. else {
  453. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  454. }
  455. // Vertex shader
  456. return this._engine._loadFileAsync(vertexShaderUrl + ".vertex.fx");
  457. };
  458. /** @ignore */
  459. Effect.prototype._loadFragmentShaderAsync = function (fragment) {
  460. if (BABYLON.Tools.IsWindowObjectExist()) {
  461. // DOM element ?
  462. if (fragment instanceof HTMLElement) {
  463. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  464. return Promise.resolve(fragmentCode);
  465. }
  466. }
  467. // Base64 encoded ?
  468. if (fragment.substr(0, 7) === "base64:") {
  469. var fragmentBinary = window.atob(fragment.substr(7));
  470. return Promise.resolve(fragmentBinary);
  471. }
  472. // Is in local store ?
  473. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  474. return Promise.resolve(Effect.ShadersStore[fragment + "PixelShader"]);
  475. }
  476. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  477. return Promise.resolve(Effect.ShadersStore[fragment + "FragmentShader"]);
  478. }
  479. var fragmentShaderUrl;
  480. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  481. fragmentShaderUrl = fragment;
  482. }
  483. else {
  484. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  485. }
  486. // Fragment shader
  487. return this._engine._loadFileAsync(fragmentShaderUrl + ".fragment.fx");
  488. };
  489. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  490. // Rebuild shaders source code
  491. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n" : "";
  492. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  493. vertexCode = prefix + vertexCode;
  494. fragmentCode = prefix + fragmentCode;
  495. // Number lines of shaders source code
  496. var i = 2;
  497. var regex = /\n/gm;
  498. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  499. i = 2;
  500. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  501. // Dump shaders name and formatted source code
  502. if (this.name.vertexElement) {
  503. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  504. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  505. }
  506. else if (this.name.vertex) {
  507. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  508. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  509. }
  510. else {
  511. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  512. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  513. }
  514. };
  515. ;
  516. Effect.prototype._processShaderConversion = function (sourceCode, isFragment) {
  517. var preparedSourceCode = this._processPrecision(sourceCode);
  518. if (this._engine.webGLVersion == 1) {
  519. return preparedSourceCode;
  520. }
  521. // Already converted
  522. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  523. return preparedSourceCode.replace("#version 300 es", "");
  524. }
  525. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  526. // Remove extensions
  527. // #extension GL_OES_standard_derivatives : enable
  528. // #extension GL_EXT_shader_texture_lod : enable
  529. // #extension GL_EXT_frag_depth : enable
  530. // #extension GL_EXT_draw_buffers : require
  531. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  532. var result = preparedSourceCode.replace(regex, "");
  533. // Migrate to GLSL v300
  534. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  535. result = result.replace(/attribute[ \t]/g, "in ");
  536. result = result.replace(/[ \t]attribute/g, " in");
  537. if (isFragment) {
  538. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  539. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  540. result = result.replace(/texture2D\s*\(/g, "texture(");
  541. result = result.replace(/textureCube\s*\(/g, "texture(");
  542. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  543. result = result.replace(/gl_FragColor/g, "glFragColor");
  544. result = result.replace(/gl_FragData/g, "glFragData");
  545. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  546. }
  547. return result;
  548. };
  549. Effect.prototype._processIncludesAsync = function (sourceCode) {
  550. var _this = this;
  551. return new Promise(function (resolve, reject) {
  552. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  553. var match = regex.exec(sourceCode);
  554. var returnValue = sourceCode;
  555. while (match != null) {
  556. var includeFile = match[1];
  557. // Uniform declaration
  558. if (includeFile.indexOf("__decl__") !== -1) {
  559. includeFile = includeFile.replace(/__decl__/, "");
  560. if (_this._engine.supportsUniformBuffers) {
  561. includeFile = includeFile.replace(/Vertex/, "Ubo");
  562. includeFile = includeFile.replace(/Fragment/, "Ubo");
  563. }
  564. includeFile = includeFile + "Declaration";
  565. }
  566. if (Effect.IncludesShadersStore[includeFile]) {
  567. // Substitution
  568. var includeContent = Effect.IncludesShadersStore[includeFile];
  569. if (match[2]) {
  570. var splits = match[3].split(",");
  571. for (var index = 0; index < splits.length; index += 2) {
  572. var source = new RegExp(splits[index], "g");
  573. var dest = splits[index + 1];
  574. includeContent = includeContent.replace(source, dest);
  575. }
  576. }
  577. if (match[4]) {
  578. var indexString = match[5];
  579. if (indexString.indexOf("..") !== -1) {
  580. var indexSplits = indexString.split("..");
  581. var minIndex = parseInt(indexSplits[0]);
  582. var maxIndex = parseInt(indexSplits[1]);
  583. var sourceIncludeContent = includeContent.slice(0);
  584. includeContent = "";
  585. if (isNaN(maxIndex)) {
  586. maxIndex = _this._indexParameters[indexSplits[1]];
  587. }
  588. for (var i = minIndex; i < maxIndex; i++) {
  589. if (!_this._engine.supportsUniformBuffers) {
  590. // Ubo replacement
  591. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  592. return p1 + "{X}";
  593. });
  594. }
  595. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  596. }
  597. }
  598. else {
  599. if (!_this._engine.supportsUniformBuffers) {
  600. // Ubo replacement
  601. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  602. return p1 + "{X}";
  603. });
  604. }
  605. includeContent = includeContent.replace(/\{X\}/g, indexString);
  606. }
  607. }
  608. // Replace
  609. returnValue = returnValue.replace(match[0], includeContent);
  610. }
  611. else {
  612. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  613. _this._engine._loadFileAsync(includeShaderUrl)
  614. .then(function (fileContent) {
  615. Effect.IncludesShadersStore[includeFile] = fileContent;
  616. return _this._processIncludesAsync(returnValue);
  617. })
  618. .then(function (returnValue) {
  619. resolve(returnValue);
  620. });
  621. return;
  622. }
  623. match = regex.exec(sourceCode);
  624. }
  625. resolve(returnValue);
  626. });
  627. };
  628. Effect.prototype._processPrecision = function (source) {
  629. if (source.indexOf("precision highp float") === -1) {
  630. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  631. source = "precision mediump float;\n" + source;
  632. }
  633. else {
  634. source = "precision highp float;\n" + source;
  635. }
  636. }
  637. else {
  638. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  639. source = source.replace("precision highp float", "precision mediump float");
  640. }
  641. }
  642. return source;
  643. };
  644. /**
  645. * Recompiles the webGL program
  646. * @param vertexSourceCode The source code for the vertex shader.
  647. * @param fragmentSourceCode The source code for the fragment shader.
  648. * @param onCompiled Callback called when completed.
  649. * @param onError Callback called on error.
  650. */
  651. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  652. var _this = this;
  653. this._isReady = false;
  654. this._vertexSourceCodeOverride = vertexSourceCode;
  655. this._fragmentSourceCodeOverride = fragmentSourceCode;
  656. this.onError = function (effect, error) {
  657. if (onError) {
  658. onError(error);
  659. }
  660. };
  661. this.onCompiled = function () {
  662. var scenes = _this.getEngine().scenes;
  663. for (var i = 0; i < scenes.length; i++) {
  664. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  665. }
  666. if (onCompiled) {
  667. onCompiled(_this._program);
  668. }
  669. };
  670. this._fallbacks = null;
  671. this._prepareEffect();
  672. };
  673. /**
  674. * Gets the uniform locations of the the specified variable names
  675. * @param names THe names of the variables to lookup.
  676. * @returns Array of locations in the same order as variable names.
  677. */
  678. Effect.prototype.getSpecificUniformLocations = function (names) {
  679. var engine = this._engine;
  680. return engine.getUniforms(this._program, names);
  681. };
  682. /**
  683. * Prepares the effect
  684. */
  685. Effect.prototype._prepareEffect = function () {
  686. var attributesNames = this._attributesNames;
  687. var defines = this.defines;
  688. var fallbacks = this._fallbacks;
  689. this._valueCache = {};
  690. var previousProgram = this._program;
  691. try {
  692. var engine = this._engine;
  693. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  694. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  695. }
  696. else {
  697. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  698. }
  699. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  700. if (engine.supportsUniformBuffers) {
  701. for (var name in this._uniformBuffersNames) {
  702. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  703. }
  704. }
  705. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  706. this._attributes = engine.getAttributes(this._program, attributesNames);
  707. var index;
  708. for (index = 0; index < this._samplers.length; index++) {
  709. var sampler = this.getUniform(this._samplers[index]);
  710. if (sampler == null) {
  711. this._samplers.splice(index, 1);
  712. index--;
  713. }
  714. }
  715. engine.bindSamplers(this);
  716. this._compilationError = "";
  717. this._isReady = true;
  718. if (this.onCompiled) {
  719. this.onCompiled(this);
  720. }
  721. this.onCompileObservable.notifyObservers(this);
  722. this.onCompileObservable.clear();
  723. // Unbind mesh reference in fallbacks
  724. if (this._fallbacks) {
  725. this._fallbacks.unBindMesh();
  726. }
  727. if (previousProgram) {
  728. this.getEngine()._deleteProgram(previousProgram);
  729. }
  730. }
  731. catch (e) {
  732. this._compilationError = e.message;
  733. // Let's go through fallbacks then
  734. BABYLON.Tools.Error("Unable to compile effect:");
  735. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  736. return " " + uniform;
  737. }));
  738. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  739. return " " + attribute;
  740. }));
  741. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  742. BABYLON.Tools.Error("Error: " + this._compilationError);
  743. if (previousProgram) {
  744. this._program = previousProgram;
  745. this._isReady = true;
  746. if (this.onError) {
  747. this.onError(this, this._compilationError);
  748. }
  749. this.onErrorObservable.notifyObservers(this);
  750. }
  751. if (fallbacks && fallbacks.isMoreFallbacks) {
  752. BABYLON.Tools.Error("Trying next fallback.");
  753. this.defines = fallbacks.reduce(this.defines, this);
  754. this._prepareEffect();
  755. }
  756. else {
  757. if (this.onError) {
  758. this.onError(this, this._compilationError);
  759. }
  760. this.onErrorObservable.notifyObservers(this);
  761. this.onErrorObservable.clear();
  762. // Unbind mesh reference in fallbacks
  763. if (this._fallbacks) {
  764. this._fallbacks.unBindMesh();
  765. }
  766. }
  767. }
  768. };
  769. Object.defineProperty(Effect.prototype, "isSupported", {
  770. /**
  771. * Checks if the effect is supported. (Must be called after compilation)
  772. */
  773. get: function () {
  774. return this._compilationError === "";
  775. },
  776. enumerable: true,
  777. configurable: true
  778. });
  779. /**
  780. * Binds a texture to the engine to be used as output of the shader.
  781. * @param channel Name of the output variable.
  782. * @param texture Texture to bind.
  783. */
  784. Effect.prototype._bindTexture = function (channel, texture) {
  785. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  786. };
  787. /**
  788. * Sets a texture on the engine to be used in the shader.
  789. * @param channel Name of the sampler variable.
  790. * @param texture Texture to set.
  791. */
  792. Effect.prototype.setTexture = function (channel, texture) {
  793. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  794. };
  795. /**
  796. * Sets an array of textures on the engine to be used in the shader.
  797. * @param channel Name of the variable.
  798. * @param textures Textures to set.
  799. */
  800. Effect.prototype.setTextureArray = function (channel, textures) {
  801. if (this._samplers.indexOf(channel + "Ex") === -1) {
  802. var initialPos = this._samplers.indexOf(channel);
  803. for (var index = 1; index < textures.length; index++) {
  804. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  805. }
  806. }
  807. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  808. };
  809. /**
  810. * Sets a texture to be the input of the specified post process. (To use the output, pass in the next post process in the pipeline)
  811. * @param channel Name of the sampler variable.
  812. * @param postProcess Post process to get the input texture from.
  813. */
  814. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  815. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  816. };
  817. /** @ignore */
  818. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  819. var cache = this._valueCache[uniformName];
  820. var flag = matrix.updateFlag;
  821. if (cache !== undefined && cache === flag) {
  822. return false;
  823. }
  824. this._valueCache[uniformName] = flag;
  825. return true;
  826. };
  827. /** @ignore */
  828. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  829. var cache = this._valueCache[uniformName];
  830. if (!cache) {
  831. cache = [x, y];
  832. this._valueCache[uniformName] = cache;
  833. return true;
  834. }
  835. var changed = false;
  836. if (cache[0] !== x) {
  837. cache[0] = x;
  838. changed = true;
  839. }
  840. if (cache[1] !== y) {
  841. cache[1] = y;
  842. changed = true;
  843. }
  844. return changed;
  845. };
  846. /** @ignore */
  847. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  848. var cache = this._valueCache[uniformName];
  849. if (!cache) {
  850. cache = [x, y, z];
  851. this._valueCache[uniformName] = cache;
  852. return true;
  853. }
  854. var changed = false;
  855. if (cache[0] !== x) {
  856. cache[0] = x;
  857. changed = true;
  858. }
  859. if (cache[1] !== y) {
  860. cache[1] = y;
  861. changed = true;
  862. }
  863. if (cache[2] !== z) {
  864. cache[2] = z;
  865. changed = true;
  866. }
  867. return changed;
  868. };
  869. /** @ignore */
  870. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  871. var cache = this._valueCache[uniformName];
  872. if (!cache) {
  873. cache = [x, y, z, w];
  874. this._valueCache[uniformName] = cache;
  875. return true;
  876. }
  877. var changed = false;
  878. if (cache[0] !== x) {
  879. cache[0] = x;
  880. changed = true;
  881. }
  882. if (cache[1] !== y) {
  883. cache[1] = y;
  884. changed = true;
  885. }
  886. if (cache[2] !== z) {
  887. cache[2] = z;
  888. changed = true;
  889. }
  890. if (cache[3] !== w) {
  891. cache[3] = w;
  892. changed = true;
  893. }
  894. return changed;
  895. };
  896. /**
  897. * Binds a buffer to a uniform.
  898. * @param buffer Buffer to bind.
  899. * @param name Name of the uniform variable to bind to.
  900. */
  901. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  902. var bufferName = this._uniformBuffersNames[name];
  903. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  904. return;
  905. }
  906. Effect._baseCache[bufferName] = buffer;
  907. this._engine.bindUniformBufferBase(buffer, bufferName);
  908. };
  909. /**
  910. * Binds block to a uniform.
  911. * @param blockName Name of the block to bind.
  912. * @param index Index to bind.
  913. */
  914. Effect.prototype.bindUniformBlock = function (blockName, index) {
  915. this._engine.bindUniformBlock(this._program, blockName, index);
  916. };
  917. /**
  918. * Sets an interger value on a uniform variable.
  919. * @param uniformName Name of the variable.
  920. * @param value Value to be set.
  921. * @returns this effect.
  922. */
  923. Effect.prototype.setInt = function (uniformName, value) {
  924. var cache = this._valueCache[uniformName];
  925. if (cache !== undefined && cache === value)
  926. return this;
  927. this._valueCache[uniformName] = value;
  928. this._engine.setInt(this.getUniform(uniformName), value);
  929. return this;
  930. };
  931. /**
  932. * Sets an int array on a uniform variable.
  933. * @param uniformName Name of the variable.
  934. * @param array array to be set.
  935. * @returns this effect.
  936. */
  937. Effect.prototype.setIntArray = function (uniformName, array) {
  938. this._valueCache[uniformName] = null;
  939. this._engine.setIntArray(this.getUniform(uniformName), array);
  940. return this;
  941. };
  942. /**
  943. * Sets an int array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  944. * @param uniformName Name of the variable.
  945. * @param array array to be set.
  946. * @returns this effect.
  947. */
  948. Effect.prototype.setIntArray2 = function (uniformName, array) {
  949. this._valueCache[uniformName] = null;
  950. this._engine.setIntArray2(this.getUniform(uniformName), array);
  951. return this;
  952. };
  953. /**
  954. * Sets an int array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  955. * @param uniformName Name of the variable.
  956. * @param array array to be set.
  957. * @returns this effect.
  958. */
  959. Effect.prototype.setIntArray3 = function (uniformName, array) {
  960. this._valueCache[uniformName] = null;
  961. this._engine.setIntArray3(this.getUniform(uniformName), array);
  962. return this;
  963. };
  964. /**
  965. * Sets an int array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  966. * @param uniformName Name of the variable.
  967. * @param array array to be set.
  968. * @returns this effect.
  969. */
  970. Effect.prototype.setIntArray4 = function (uniformName, array) {
  971. this._valueCache[uniformName] = null;
  972. this._engine.setIntArray4(this.getUniform(uniformName), array);
  973. return this;
  974. };
  975. /**
  976. * Sets an float array on a uniform variable.
  977. * @param uniformName Name of the variable.
  978. * @param array array to be set.
  979. * @returns this effect.
  980. */
  981. Effect.prototype.setFloatArray = function (uniformName, array) {
  982. this._valueCache[uniformName] = null;
  983. this._engine.setFloatArray(this.getUniform(uniformName), array);
  984. return this;
  985. };
  986. /**
  987. * Sets an float array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  988. * @param uniformName Name of the variable.
  989. * @param array array to be set.
  990. * @returns this effect.
  991. */
  992. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  993. this._valueCache[uniformName] = null;
  994. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  995. return this;
  996. };
  997. /**
  998. * Sets an float array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  999. * @param uniformName Name of the variable.
  1000. * @param array array to be set.
  1001. * @returns this effect.
  1002. */
  1003. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  1004. this._valueCache[uniformName] = null;
  1005. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  1006. return this;
  1007. };
  1008. /**
  1009. * Sets an float array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  1010. * @param uniformName Name of the variable.
  1011. * @param array array to be set.
  1012. * @returns this effect.
  1013. */
  1014. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  1015. this._valueCache[uniformName] = null;
  1016. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  1017. return this;
  1018. };
  1019. /**
  1020. * Sets an array on a uniform variable.
  1021. * @param uniformName Name of the variable.
  1022. * @param array array to be set.
  1023. * @returns this effect.
  1024. */
  1025. Effect.prototype.setArray = function (uniformName, array) {
  1026. this._valueCache[uniformName] = null;
  1027. this._engine.setArray(this.getUniform(uniformName), array);
  1028. return this;
  1029. };
  1030. /**
  1031. * Sets an array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  1032. * @param uniformName Name of the variable.
  1033. * @param array array to be set.
  1034. * @returns this effect.
  1035. */
  1036. Effect.prototype.setArray2 = function (uniformName, array) {
  1037. this._valueCache[uniformName] = null;
  1038. this._engine.setArray2(this.getUniform(uniformName), array);
  1039. return this;
  1040. };
  1041. /**
  1042. * Sets an array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  1043. * @param uniformName Name of the variable.
  1044. * @param array array to be set.
  1045. * @returns this effect.
  1046. */
  1047. Effect.prototype.setArray3 = function (uniformName, array) {
  1048. this._valueCache[uniformName] = null;
  1049. this._engine.setArray3(this.getUniform(uniformName), array);
  1050. return this;
  1051. };
  1052. /**
  1053. * Sets an array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  1054. * @param uniformName Name of the variable.
  1055. * @param array array to be set.
  1056. * @returns this effect.
  1057. */
  1058. Effect.prototype.setArray4 = function (uniformName, array) {
  1059. this._valueCache[uniformName] = null;
  1060. this._engine.setArray4(this.getUniform(uniformName), array);
  1061. return this;
  1062. };
  1063. /**
  1064. * Sets matrices on a uniform variable.
  1065. * @param uniformName Name of the variable.
  1066. * @param matrices matrices to be set.
  1067. * @returns this effect.
  1068. */
  1069. Effect.prototype.setMatrices = function (uniformName, matrices) {
  1070. if (!matrices) {
  1071. return this;
  1072. }
  1073. this._valueCache[uniformName] = null;
  1074. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  1075. return this;
  1076. };
  1077. /**
  1078. * Sets matrix on a uniform variable.
  1079. * @param uniformName Name of the variable.
  1080. * @param matrix matrix to be set.
  1081. * @returns this effect.
  1082. */
  1083. Effect.prototype.setMatrix = function (uniformName, matrix) {
  1084. if (this._cacheMatrix(uniformName, matrix)) {
  1085. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  1086. }
  1087. return this;
  1088. };
  1089. /**
  1090. * Sets a 3x3 matrix on a uniform variable. (Speicified as [1,2,3,4,5,6,7,8,9] will result in [1,2,3][4,5,6][7,8,9] matrix)
  1091. * @param uniformName Name of the variable.
  1092. * @param matrix matrix to be set.
  1093. * @returns this effect.
  1094. */
  1095. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  1096. this._valueCache[uniformName] = null;
  1097. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  1098. return this;
  1099. };
  1100. /**
  1101. * Sets a 2x2 matrix on a uniform variable. (Speicified as [1,2,3,4] will result in [1,2][3,4] matrix)
  1102. * @param uniformName Name of the variable.
  1103. * @param matrix matrix to be set.
  1104. * @returns this effect.
  1105. */
  1106. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  1107. this._valueCache[uniformName] = null;
  1108. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  1109. return this;
  1110. };
  1111. /**
  1112. * Sets a float on a uniform variable.
  1113. * @param uniformName Name of the variable.
  1114. * @param value value to be set.
  1115. * @returns this effect.
  1116. */
  1117. Effect.prototype.setFloat = function (uniformName, value) {
  1118. var cache = this._valueCache[uniformName];
  1119. if (cache !== undefined && cache === value)
  1120. return this;
  1121. this._valueCache[uniformName] = value;
  1122. this._engine.setFloat(this.getUniform(uniformName), value);
  1123. return this;
  1124. };
  1125. /**
  1126. * Sets a boolean on a uniform variable.
  1127. * @param uniformName Name of the variable.
  1128. * @param bool value to be set.
  1129. * @returns this effect.
  1130. */
  1131. Effect.prototype.setBool = function (uniformName, bool) {
  1132. var cache = this._valueCache[uniformName];
  1133. if (cache !== undefined && cache === bool)
  1134. return this;
  1135. this._valueCache[uniformName] = bool;
  1136. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  1137. return this;
  1138. };
  1139. /**
  1140. * Sets a Vector2 on a uniform variable.
  1141. * @param uniformName Name of the variable.
  1142. * @param vector2 vector2 to be set.
  1143. * @returns this effect.
  1144. */
  1145. Effect.prototype.setVector2 = function (uniformName, vector2) {
  1146. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  1147. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  1148. }
  1149. return this;
  1150. };
  1151. /**
  1152. * Sets a float2 on a uniform variable.
  1153. * @param uniformName Name of the variable.
  1154. * @param x First float in float2.
  1155. * @param y Second float in float2.
  1156. * @returns this effect.
  1157. */
  1158. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  1159. if (this._cacheFloat2(uniformName, x, y)) {
  1160. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  1161. }
  1162. return this;
  1163. };
  1164. /**
  1165. * Sets a Vector3 on a uniform variable.
  1166. * @param uniformName Name of the variable.
  1167. * @param vector3 Value to be set.
  1168. * @returns this effect.
  1169. */
  1170. Effect.prototype.setVector3 = function (uniformName, vector3) {
  1171. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  1172. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  1173. }
  1174. return this;
  1175. };
  1176. /**
  1177. * Sets a float3 on a uniform variable.
  1178. * @param uniformName Name of the variable.
  1179. * @param x First float in float3.
  1180. * @param y Second float in float3.
  1181. * @param z Third float in float3.
  1182. * @returns this effect.
  1183. */
  1184. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  1185. if (this._cacheFloat3(uniformName, x, y, z)) {
  1186. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  1187. }
  1188. return this;
  1189. };
  1190. /**
  1191. * Sets a Vector4 on a uniform variable.
  1192. * @param uniformName Name of the variable.
  1193. * @param vector4 Value to be set.
  1194. * @returns this effect.
  1195. */
  1196. Effect.prototype.setVector4 = function (uniformName, vector4) {
  1197. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  1198. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  1199. }
  1200. return this;
  1201. };
  1202. /**
  1203. * Sets a float4 on a uniform variable.
  1204. * @param uniformName Name of the variable.
  1205. * @param x First float in float4.
  1206. * @param y Second float in float4.
  1207. * @param z Third float in float4.
  1208. * @param w Fourth float in float4.
  1209. * @returns this effect.
  1210. */
  1211. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  1212. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  1213. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  1214. }
  1215. return this;
  1216. };
  1217. /**
  1218. * Sets a Color3 on a uniform variable.
  1219. * @param uniformName Name of the variable.
  1220. * @param color3 Value to be set.
  1221. * @returns this effect.
  1222. */
  1223. Effect.prototype.setColor3 = function (uniformName, color3) {
  1224. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  1225. this._engine.setColor3(this.getUniform(uniformName), color3);
  1226. }
  1227. return this;
  1228. };
  1229. /**
  1230. * Sets a Color4 on a uniform variable.
  1231. * @param uniformName Name of the variable.
  1232. * @param color3 Value to be set.
  1233. * @param alpha Alpha value to be set.
  1234. * @returns this effect.
  1235. */
  1236. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  1237. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  1238. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  1239. }
  1240. return this;
  1241. };
  1242. /**
  1243. * Sets a Color4 on a uniform variable
  1244. * @param uniformName defines the name of the variable
  1245. * @param color4 defines the value to be set
  1246. * @returns this effect.
  1247. */
  1248. Effect.prototype.setDirectColor4 = function (uniformName, color4) {
  1249. if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) {
  1250. this._engine.setDirectColor4(this.getUniform(uniformName), color4);
  1251. }
  1252. return this;
  1253. };
  1254. /**
  1255. * Resets the cache of effects.
  1256. */
  1257. Effect.ResetCache = function () {
  1258. Effect._baseCache = {};
  1259. };
  1260. Effect._uniqueIdSeed = 0;
  1261. Effect._baseCache = {};
  1262. // Statics
  1263. /**
  1264. * Store of each shader (The can be looked up using effect.key)
  1265. */
  1266. Effect.ShadersStore = {};
  1267. /**
  1268. * Store of each included file for a shader (The can be looked up using effect.key)
  1269. */
  1270. Effect.IncludesShadersStore = {};
  1271. return Effect;
  1272. }());
  1273. BABYLON.Effect = Effect;
  1274. })(BABYLON || (BABYLON = {}));
  1275. //# sourceMappingURL=babylon.effect.js.map
  1276. //# sourceMappingURL=babylon.types.js.map
  1277. var BABYLON;
  1278. (function (BABYLON) {
  1279. var KeyboardEventTypes = /** @class */ (function () {
  1280. function KeyboardEventTypes() {
  1281. }
  1282. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  1283. get: function () {
  1284. return KeyboardEventTypes._KEYDOWN;
  1285. },
  1286. enumerable: true,
  1287. configurable: true
  1288. });
  1289. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  1290. get: function () {
  1291. return KeyboardEventTypes._KEYUP;
  1292. },
  1293. enumerable: true,
  1294. configurable: true
  1295. });
  1296. KeyboardEventTypes._KEYDOWN = 0x01;
  1297. KeyboardEventTypes._KEYUP = 0x02;
  1298. return KeyboardEventTypes;
  1299. }());
  1300. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  1301. var KeyboardInfo = /** @class */ (function () {
  1302. function KeyboardInfo(type, event) {
  1303. this.type = type;
  1304. this.event = event;
  1305. }
  1306. return KeyboardInfo;
  1307. }());
  1308. BABYLON.KeyboardInfo = KeyboardInfo;
  1309. /**
  1310. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1311. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  1312. */
  1313. var KeyboardInfoPre = /** @class */ (function (_super) {
  1314. __extends(KeyboardInfoPre, _super);
  1315. function KeyboardInfoPre(type, event) {
  1316. var _this = _super.call(this, type, event) || this;
  1317. _this.skipOnPointerObservable = false;
  1318. return _this;
  1319. }
  1320. return KeyboardInfoPre;
  1321. }(KeyboardInfo));
  1322. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  1323. })(BABYLON || (BABYLON = {}));
  1324. //# sourceMappingURL=babylon.keyboardEvents.js.map
  1325. var BABYLON;
  1326. (function (BABYLON) {
  1327. var PointerEventTypes = /** @class */ (function () {
  1328. function PointerEventTypes() {
  1329. }
  1330. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  1331. get: function () {
  1332. return PointerEventTypes._POINTERDOWN;
  1333. },
  1334. enumerable: true,
  1335. configurable: true
  1336. });
  1337. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  1338. get: function () {
  1339. return PointerEventTypes._POINTERUP;
  1340. },
  1341. enumerable: true,
  1342. configurable: true
  1343. });
  1344. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  1345. get: function () {
  1346. return PointerEventTypes._POINTERMOVE;
  1347. },
  1348. enumerable: true,
  1349. configurable: true
  1350. });
  1351. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  1352. get: function () {
  1353. return PointerEventTypes._POINTERWHEEL;
  1354. },
  1355. enumerable: true,
  1356. configurable: true
  1357. });
  1358. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  1359. get: function () {
  1360. return PointerEventTypes._POINTERPICK;
  1361. },
  1362. enumerable: true,
  1363. configurable: true
  1364. });
  1365. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  1366. get: function () {
  1367. return PointerEventTypes._POINTERTAP;
  1368. },
  1369. enumerable: true,
  1370. configurable: true
  1371. });
  1372. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  1373. get: function () {
  1374. return PointerEventTypes._POINTERDOUBLETAP;
  1375. },
  1376. enumerable: true,
  1377. configurable: true
  1378. });
  1379. PointerEventTypes._POINTERDOWN = 0x01;
  1380. PointerEventTypes._POINTERUP = 0x02;
  1381. PointerEventTypes._POINTERMOVE = 0x04;
  1382. PointerEventTypes._POINTERWHEEL = 0x08;
  1383. PointerEventTypes._POINTERPICK = 0x10;
  1384. PointerEventTypes._POINTERTAP = 0x20;
  1385. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  1386. return PointerEventTypes;
  1387. }());
  1388. BABYLON.PointerEventTypes = PointerEventTypes;
  1389. var PointerInfoBase = /** @class */ (function () {
  1390. function PointerInfoBase(type, event) {
  1391. this.type = type;
  1392. this.event = event;
  1393. }
  1394. return PointerInfoBase;
  1395. }());
  1396. BABYLON.PointerInfoBase = PointerInfoBase;
  1397. /**
  1398. * This class is used to store pointer related info for the onPrePointerObservable event.
  1399. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1400. */
  1401. var PointerInfoPre = /** @class */ (function (_super) {
  1402. __extends(PointerInfoPre, _super);
  1403. function PointerInfoPre(type, event, localX, localY) {
  1404. var _this = _super.call(this, type, event) || this;
  1405. _this.skipOnPointerObservable = false;
  1406. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1407. return _this;
  1408. }
  1409. return PointerInfoPre;
  1410. }(PointerInfoBase));
  1411. BABYLON.PointerInfoPre = PointerInfoPre;
  1412. /**
  1413. * This type contains all the data related to a pointer event in Babylon.js.
  1414. * 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.
  1415. */
  1416. var PointerInfo = /** @class */ (function (_super) {
  1417. __extends(PointerInfo, _super);
  1418. function PointerInfo(type, event, pickInfo) {
  1419. var _this = _super.call(this, type, event) || this;
  1420. _this.pickInfo = pickInfo;
  1421. return _this;
  1422. }
  1423. return PointerInfo;
  1424. }(PointerInfoBase));
  1425. BABYLON.PointerInfo = PointerInfo;
  1426. })(BABYLON || (BABYLON = {}));
  1427. //# sourceMappingURL=babylon.pointerEvents.js.map
  1428. var BABYLON;
  1429. (function (BABYLON) {
  1430. BABYLON.ToGammaSpace = 1 / 2.2;
  1431. BABYLON.ToLinearSpace = 2.2;
  1432. BABYLON.Epsilon = 0.001;
  1433. /**
  1434. * Class used to hold a RBG color
  1435. */
  1436. var Color3 = /** @class */ (function () {
  1437. /**
  1438. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1439. * @param r defines the red component (between 0 and 1, default is 0)
  1440. * @param g defines the green component (between 0 and 1, default is 0)
  1441. * @param b defines the blue component (between 0 and 1, default is 0)
  1442. */
  1443. function Color3(
  1444. /**
  1445. * Defines the red component (between 0 and 1, default is 0)
  1446. */
  1447. r,
  1448. /**
  1449. * Defines the green component (between 0 and 1, default is 0)
  1450. */
  1451. g,
  1452. /**
  1453. * Defines the blue component (between 0 and 1, default is 0)
  1454. */
  1455. b) {
  1456. if (r === void 0) { r = 0; }
  1457. if (g === void 0) { g = 0; }
  1458. if (b === void 0) { b = 0; }
  1459. this.r = r;
  1460. this.g = g;
  1461. this.b = b;
  1462. }
  1463. /**
  1464. * Creates a string with the Color3 current values
  1465. * @returns the string representation of the Color3 object
  1466. */
  1467. Color3.prototype.toString = function () {
  1468. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1469. };
  1470. /**
  1471. * Returns the string "Color3"
  1472. * @returns "Color3"
  1473. */
  1474. Color3.prototype.getClassName = function () {
  1475. return "Color3";
  1476. };
  1477. /**
  1478. * Compute the Color3 hash code
  1479. * @returns an unique number that can be used to hash Color3 objects
  1480. */
  1481. Color3.prototype.getHashCode = function () {
  1482. var hash = this.r || 0;
  1483. hash = (hash * 397) ^ (this.g || 0);
  1484. hash = (hash * 397) ^ (this.b || 0);
  1485. return hash;
  1486. };
  1487. // Operators
  1488. /**
  1489. * Stores in the passed array from the passed starting index the red, green, blue values as successive elements
  1490. * @param array defines the array where to store the r,g,b components
  1491. * @param index defines an optional index in the target array to define where to start storing values
  1492. * @returns the current Color3 object
  1493. */
  1494. Color3.prototype.toArray = function (array, index) {
  1495. if (index === undefined) {
  1496. index = 0;
  1497. }
  1498. array[index] = this.r;
  1499. array[index + 1] = this.g;
  1500. array[index + 2] = this.b;
  1501. return this;
  1502. };
  1503. /**
  1504. * Returns a new {BABYLON.Color4} object from the current Color3 and the passed alpha
  1505. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1506. * @returns a new {BABYLON.Color4} object
  1507. */
  1508. Color3.prototype.toColor4 = function (alpha) {
  1509. if (alpha === void 0) { alpha = 1; }
  1510. return new Color4(this.r, this.g, this.b, alpha);
  1511. };
  1512. /**
  1513. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1514. * @returns the new array
  1515. */
  1516. Color3.prototype.asArray = function () {
  1517. var result = new Array();
  1518. this.toArray(result, 0);
  1519. return result;
  1520. };
  1521. /**
  1522. * Returns the luminance value
  1523. * @returns a float value
  1524. */
  1525. Color3.prototype.toLuminance = function () {
  1526. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1527. };
  1528. /**
  1529. * Multiply each Color3 rgb values by the passed Color3 rgb values in a new Color3 object
  1530. * @param otherColor defines the second operand
  1531. * @returns the new Color3 object
  1532. */
  1533. Color3.prototype.multiply = function (otherColor) {
  1534. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1535. };
  1536. /**
  1537. * Multiply the rgb values of the Color3 and the passed Color3 and stores the result in the object "result"
  1538. * @param otherColor defines the second operand
  1539. * @param result defines the Color3 object where to store the result
  1540. * @returns the current Color3
  1541. */
  1542. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1543. result.r = this.r * otherColor.r;
  1544. result.g = this.g * otherColor.g;
  1545. result.b = this.b * otherColor.b;
  1546. return this;
  1547. };
  1548. /**
  1549. * Determines equality between Color3 objects
  1550. * @param otherColor defines the second operand
  1551. * @returns true if the rgb values are equal to the passed ones
  1552. */
  1553. Color3.prototype.equals = function (otherColor) {
  1554. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1555. };
  1556. /**
  1557. * Determines equality between the current Color3 object and a set of r,b,g values
  1558. * @param r defines the red component to check
  1559. * @param g defines the green component to check
  1560. * @param b defines the blue component to check
  1561. * @returns true if the rgb values are equal to the passed ones
  1562. */
  1563. Color3.prototype.equalsFloats = function (r, g, b) {
  1564. return this.r === r && this.g === g && this.b === b;
  1565. };
  1566. /**
  1567. * Multiplies in place each rgb value by scale
  1568. * @param scale defines the scaling factor
  1569. * @returns the updated Color3.
  1570. */
  1571. Color3.prototype.scale = function (scale) {
  1572. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1573. };
  1574. /**
  1575. * Multiplies the rgb values by scale and stores the result into "result"
  1576. * @param scale defines the scaling factor
  1577. * @param result defines the Color3 object where to store the result
  1578. * @returns the unmodified current Color3.
  1579. */
  1580. Color3.prototype.scaleToRef = function (scale, result) {
  1581. result.r = this.r * scale;
  1582. result.g = this.g * scale;
  1583. result.b = this.b * scale;
  1584. return this;
  1585. };
  1586. /**
  1587. * Clamps the rgb values by the min and max values and stores the result into "result"
  1588. * @param min defines minimum clamping value (default is 0)
  1589. * @param max defines maximum clamping value (default is 1)
  1590. * @param result defines color to store the result into
  1591. * @returns the original Color3
  1592. */
  1593. Color3.prototype.clampToRef = function (min, max, result) {
  1594. if (min === void 0) { min = 0; }
  1595. if (max === void 0) { max = 1; }
  1596. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1597. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1598. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1599. return this;
  1600. };
  1601. /**
  1602. * Creates a new Color3 set with the added values of the current Color3 and of the passed one
  1603. * @param otherColor defines the second operand
  1604. * @returns the new Color3
  1605. */
  1606. Color3.prototype.add = function (otherColor) {
  1607. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1608. };
  1609. /**
  1610. * Stores the result of the addition of the current Color3 and passed one rgb values into "result"
  1611. * @param otherColor defines the second operand
  1612. * @param result defines Color3 object to store the result into
  1613. * @returns the unmodified current Color3
  1614. */
  1615. Color3.prototype.addToRef = function (otherColor, result) {
  1616. result.r = this.r + otherColor.r;
  1617. result.g = this.g + otherColor.g;
  1618. result.b = this.b + otherColor.b;
  1619. return this;
  1620. };
  1621. /**
  1622. * Returns a new Color3 set with the subtracted values of the passed one from the current Color3
  1623. * @param otherColor defines the second operand
  1624. * @returns the new Color3
  1625. */
  1626. Color3.prototype.subtract = function (otherColor) {
  1627. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1628. };
  1629. /**
  1630. * Stores the result of the subtraction of passed one from the current Color3 rgb values into "result"
  1631. * @param otherColor defines the second operand
  1632. * @param result defines Color3 object to store the result into
  1633. * @returns the unmodified current Color3
  1634. */
  1635. Color3.prototype.subtractToRef = function (otherColor, result) {
  1636. result.r = this.r - otherColor.r;
  1637. result.g = this.g - otherColor.g;
  1638. result.b = this.b - otherColor.b;
  1639. return this;
  1640. };
  1641. /**
  1642. * Copy the current object
  1643. * @returns a new Color3 copied the current one
  1644. */
  1645. Color3.prototype.clone = function () {
  1646. return new Color3(this.r, this.g, this.b);
  1647. };
  1648. /**
  1649. * Copies the rgb values from the source in the current Color3
  1650. * @param source defines the source Color3 object
  1651. * @returns the updated Color3 object
  1652. */
  1653. Color3.prototype.copyFrom = function (source) {
  1654. this.r = source.r;
  1655. this.g = source.g;
  1656. this.b = source.b;
  1657. return this;
  1658. };
  1659. /**
  1660. * Updates the Color3 rgb values from the passed floats
  1661. * @param r defines the red component to read from
  1662. * @param g defines the green component to read from
  1663. * @param b defines the blue component to read from
  1664. * @returns the current Color3 object
  1665. */
  1666. Color3.prototype.copyFromFloats = function (r, g, b) {
  1667. this.r = r;
  1668. this.g = g;
  1669. this.b = b;
  1670. return this;
  1671. };
  1672. /**
  1673. * Updates the Color3 rgb values from the passed floats
  1674. * @param r defines the red component to read from
  1675. * @param g defines the green component to read from
  1676. * @param b defines the blue component to read from
  1677. * @returns the current Color3 object
  1678. */
  1679. Color3.prototype.set = function (r, g, b) {
  1680. return this.copyFromFloats(r, g, b);
  1681. };
  1682. /**
  1683. * Compute the Color3 hexadecimal code as a string
  1684. * @returns a string containing the hexadecimal representation of the Color3 object
  1685. */
  1686. Color3.prototype.toHexString = function () {
  1687. var intR = (this.r * 255) | 0;
  1688. var intG = (this.g * 255) | 0;
  1689. var intB = (this.b * 255) | 0;
  1690. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1691. };
  1692. /**
  1693. * Computes a new Color3 converted from the current one to linear space
  1694. * @returns a new Color3 object
  1695. */
  1696. Color3.prototype.toLinearSpace = function () {
  1697. var convertedColor = new Color3();
  1698. this.toLinearSpaceToRef(convertedColor);
  1699. return convertedColor;
  1700. };
  1701. /**
  1702. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1703. * @param convertedColor defines the Color3 object where to store the linear space version
  1704. * @returns the unmodified Color3
  1705. */
  1706. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1707. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1708. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1709. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1710. return this;
  1711. };
  1712. /**
  1713. * Computes a new Color3 converted from the current one to gamma space
  1714. * @returns a new Color3 object
  1715. */
  1716. Color3.prototype.toGammaSpace = function () {
  1717. var convertedColor = new Color3();
  1718. this.toGammaSpaceToRef(convertedColor);
  1719. return convertedColor;
  1720. };
  1721. /**
  1722. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1723. * @param convertedColor defines the Color3 object where to store the gamma space version
  1724. * @returns the unmodified Color3
  1725. */
  1726. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1727. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1728. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1729. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1730. return this;
  1731. };
  1732. // Statics
  1733. /**
  1734. * Creates a new Color3 from the string containing valid hexadecimal values
  1735. * @param hex defines a string containing valid hexadecimal values
  1736. * @returns a new Color3 object
  1737. */
  1738. Color3.FromHexString = function (hex) {
  1739. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1740. return new Color3(0, 0, 0);
  1741. }
  1742. var r = parseInt(hex.substring(1, 3), 16);
  1743. var g = parseInt(hex.substring(3, 5), 16);
  1744. var b = parseInt(hex.substring(5, 7), 16);
  1745. return Color3.FromInts(r, g, b);
  1746. };
  1747. /**
  1748. * Creates a new Vector3 from the starting index of the passed array
  1749. * @param array defines the source array
  1750. * @param offset defines an offset in the source array
  1751. * @returns a new Color3 object
  1752. */
  1753. Color3.FromArray = function (array, offset) {
  1754. if (offset === void 0) { offset = 0; }
  1755. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1756. };
  1757. /**
  1758. * Creates a new Color3 from integer values (< 256)
  1759. * @param r defines the red component to read from (value between 0 and 255)
  1760. * @param g defines the green component to read from (value between 0 and 255)
  1761. * @param b defines the blue component to read from (value between 0 and 255)
  1762. * @returns a new Color3 object
  1763. */
  1764. Color3.FromInts = function (r, g, b) {
  1765. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1766. };
  1767. /**
  1768. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1769. * @param start defines the start Color3 value
  1770. * @param end defines the end Color3 value
  1771. * @param amount defines the gradient value between start and end
  1772. * @returns a new Color3 object
  1773. */
  1774. Color3.Lerp = function (start, end, amount) {
  1775. var r = start.r + ((end.r - start.r) * amount);
  1776. var g = start.g + ((end.g - start.g) * amount);
  1777. var b = start.b + ((end.b - start.b) * amount);
  1778. return new Color3(r, g, b);
  1779. };
  1780. /**
  1781. * Returns a Color3 value containing a red color
  1782. * @returns a new Color3 object
  1783. */
  1784. Color3.Red = function () { return new Color3(1, 0, 0); };
  1785. /**
  1786. * Returns a Color3 value containing a green color
  1787. * @returns a new Color3 object
  1788. */
  1789. Color3.Green = function () { return new Color3(0, 1, 0); };
  1790. /**
  1791. * Returns a Color3 value containing a blue color
  1792. * @returns a new Color3 object
  1793. */
  1794. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1795. /**
  1796. * Returns a Color3 value containing a black color
  1797. * @returns a new Color3 object
  1798. */
  1799. Color3.Black = function () { return new Color3(0, 0, 0); };
  1800. /**
  1801. * Returns a Color3 value containing a white color
  1802. * @returns a new Color3 object
  1803. */
  1804. Color3.White = function () { return new Color3(1, 1, 1); };
  1805. /**
  1806. * Returns a Color3 value containing a purple color
  1807. * @returns a new Color3 object
  1808. */
  1809. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1810. /**
  1811. * Returns a Color3 value containing a magenta color
  1812. * @returns a new Color3 object
  1813. */
  1814. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1815. /**
  1816. * Returns a Color3 value containing a yellow color
  1817. * @returns a new Color3 object
  1818. */
  1819. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1820. /**
  1821. * Returns a Color3 value containing a gray color
  1822. * @returns a new Color3 object
  1823. */
  1824. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1825. /**
  1826. * Returns a Color3 value containing a teal color
  1827. * @returns a new Color3 object
  1828. */
  1829. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1830. /**
  1831. * Returns a Color3 value containing a random color
  1832. * @returns a new Color3 object
  1833. */
  1834. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1835. return Color3;
  1836. }());
  1837. BABYLON.Color3 = Color3;
  1838. /**
  1839. * Class used to hold a RBGA color
  1840. */
  1841. var Color4 = /** @class */ (function () {
  1842. /**
  1843. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1844. * @param r defines the red component (between 0 and 1, default is 0)
  1845. * @param g defines the green component (between 0 and 1, default is 0)
  1846. * @param b defines the blue component (between 0 and 1, default is 0)
  1847. * @param a defines the alpha component (between 0 and 1, default is 1)
  1848. */
  1849. function Color4(
  1850. /**
  1851. * Defines the red component (between 0 and 1, default is 0)
  1852. */
  1853. r,
  1854. /**
  1855. * Defines the green component (between 0 and 1, default is 0)
  1856. */
  1857. g,
  1858. /**
  1859. * Defines the blue component (between 0 and 1, default is 0)
  1860. */
  1861. b,
  1862. /**
  1863. * Defines the alpha component (between 0 and 1, default is 1)
  1864. */
  1865. a) {
  1866. if (r === void 0) { r = 0; }
  1867. if (g === void 0) { g = 0; }
  1868. if (b === void 0) { b = 0; }
  1869. if (a === void 0) { a = 1; }
  1870. this.r = r;
  1871. this.g = g;
  1872. this.b = b;
  1873. this.a = a;
  1874. }
  1875. // Operators
  1876. /**
  1877. * Adds in place the passed Color4 values to the current Color4 object
  1878. * @param right defines the second operand
  1879. * @returns the current updated Color4 object
  1880. */
  1881. Color4.prototype.addInPlace = function (right) {
  1882. this.r += right.r;
  1883. this.g += right.g;
  1884. this.b += right.b;
  1885. this.a += right.a;
  1886. return this;
  1887. };
  1888. /**
  1889. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1890. * @returns the new array
  1891. */
  1892. Color4.prototype.asArray = function () {
  1893. var result = new Array();
  1894. this.toArray(result, 0);
  1895. return result;
  1896. };
  1897. /**
  1898. * Stores from the starting index in the passed array the Color4 successive values
  1899. * @param array defines the array where to store the r,g,b components
  1900. * @param index defines an optional index in the target array to define where to start storing values
  1901. * @returns the current Color4 object
  1902. */
  1903. Color4.prototype.toArray = function (array, index) {
  1904. if (index === undefined) {
  1905. index = 0;
  1906. }
  1907. array[index] = this.r;
  1908. array[index + 1] = this.g;
  1909. array[index + 2] = this.b;
  1910. array[index + 3] = this.a;
  1911. return this;
  1912. };
  1913. /**
  1914. * Creates a new Color4 set with the added values of the current Color4 and of the passed one
  1915. * @param right defines the second operand
  1916. * @returns a new Color4 object
  1917. */
  1918. Color4.prototype.add = function (right) {
  1919. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1920. };
  1921. /**
  1922. * Creates a new Color4 set with the subtracted values of the passed one from the current Color4
  1923. * @param right defines the second operand
  1924. * @returns a new Color4 object
  1925. */
  1926. Color4.prototype.subtract = function (right) {
  1927. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1928. };
  1929. /**
  1930. * Subtracts the passed ones from the current Color4 values and stores the results in "result"
  1931. * @param right defines the second operand
  1932. * @param result defines the Color4 object where to store the result
  1933. * @returns the current Color4 object
  1934. */
  1935. Color4.prototype.subtractToRef = function (right, result) {
  1936. result.r = this.r - right.r;
  1937. result.g = this.g - right.g;
  1938. result.b = this.b - right.b;
  1939. result.a = this.a - right.a;
  1940. return this;
  1941. };
  1942. /**
  1943. * Creates a new Color4 with the current Color4 values multiplied by scale
  1944. * @param scale defines the scaling factor to apply
  1945. * @returns a new Color4 object
  1946. */
  1947. Color4.prototype.scale = function (scale) {
  1948. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  1949. };
  1950. /**
  1951. * Multiplies the current Color4 values by scale and stores the result in "result"
  1952. * @param scale defines the scaling factor to apply
  1953. * @param result defines the Color4 object where to store the result
  1954. * @returns the current Color4.
  1955. */
  1956. Color4.prototype.scaleToRef = function (scale, result) {
  1957. result.r = this.r * scale;
  1958. result.g = this.g * scale;
  1959. result.b = this.b * scale;
  1960. result.a = this.a * scale;
  1961. return this;
  1962. };
  1963. /**
  1964. * Clamps the rgb values by the min and max values and stores the result into "result"
  1965. * @param min defines minimum clamping value (default is 0)
  1966. * @param max defines maximum clamping value (default is 1)
  1967. * @param result defines color to store the result into.
  1968. * @returns the cuurent Color4
  1969. */
  1970. Color4.prototype.clampToRef = function (min, max, result) {
  1971. if (min === void 0) { min = 0; }
  1972. if (max === void 0) { max = 1; }
  1973. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1974. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1975. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1976. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  1977. return this;
  1978. };
  1979. /**
  1980. * Multipy an Color4 value by another and return a new Color4 object
  1981. * @param color defines the Color4 value to multiply by
  1982. * @returns a new Color4 object
  1983. */
  1984. Color4.prototype.multiply = function (color) {
  1985. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  1986. };
  1987. /**
  1988. * Multipy a Color4 value by another and push the result in a reference value
  1989. * @param color defines the Color4 value to multiply by
  1990. * @param result defines the Color4 to fill the result in
  1991. * @returns the result Color4
  1992. */
  1993. Color4.prototype.multiplyToRef = function (color, result) {
  1994. result.r = this.r * color.r;
  1995. result.g = this.g * color.g;
  1996. result.b = this.b * color.b;
  1997. result.a = this.a * color.a;
  1998. return result;
  1999. };
  2000. /**
  2001. * Creates a string with the Color4 current values
  2002. * @returns the string representation of the Color4 object
  2003. */
  2004. Color4.prototype.toString = function () {
  2005. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  2006. };
  2007. /**
  2008. * Returns the string "Color4"
  2009. * @returns "Color4"
  2010. */
  2011. Color4.prototype.getClassName = function () {
  2012. return "Color4";
  2013. };
  2014. /**
  2015. * Compute the Color4 hash code
  2016. * @returns an unique number that can be used to hash Color4 objects
  2017. */
  2018. Color4.prototype.getHashCode = function () {
  2019. var hash = this.r || 0;
  2020. hash = (hash * 397) ^ (this.g || 0);
  2021. hash = (hash * 397) ^ (this.b || 0);
  2022. hash = (hash * 397) ^ (this.a || 0);
  2023. return hash;
  2024. };
  2025. /**
  2026. * Creates a new Color4 copied from the current one
  2027. * @returns a new Color4 object
  2028. */
  2029. Color4.prototype.clone = function () {
  2030. return new Color4(this.r, this.g, this.b, this.a);
  2031. };
  2032. /**
  2033. * Copies the passed Color4 values into the current one
  2034. * @param source defines the source Color4 object
  2035. * @returns the current updated Color4 object
  2036. */
  2037. Color4.prototype.copyFrom = function (source) {
  2038. this.r = source.r;
  2039. this.g = source.g;
  2040. this.b = source.b;
  2041. this.a = source.a;
  2042. return this;
  2043. };
  2044. /**
  2045. * Copies the passed float values into the current one
  2046. * @param r defines the red component to read from
  2047. * @param g defines the green component to read from
  2048. * @param b defines the blue component to read from
  2049. * @param a defines the alpha component to read from
  2050. * @returns the current updated Color4 object
  2051. */
  2052. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  2053. this.r = r;
  2054. this.g = g;
  2055. this.b = b;
  2056. this.a = a;
  2057. return this;
  2058. };
  2059. /**
  2060. * Copies the passed float values into the current one
  2061. * @param r defines the red component to read from
  2062. * @param g defines the green component to read from
  2063. * @param b defines the blue component to read from
  2064. * @param a defines the alpha component to read from
  2065. * @returns the current updated Color4 object
  2066. */
  2067. Color4.prototype.set = function (r, g, b, a) {
  2068. return this.copyFromFloats(r, g, b, a);
  2069. };
  2070. /**
  2071. * Compute the Color4 hexadecimal code as a string
  2072. * @returns a string containing the hexadecimal representation of the Color4 object
  2073. */
  2074. Color4.prototype.toHexString = function () {
  2075. var intR = (this.r * 255) | 0;
  2076. var intG = (this.g * 255) | 0;
  2077. var intB = (this.b * 255) | 0;
  2078. var intA = (this.a * 255) | 0;
  2079. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  2080. };
  2081. /**
  2082. * Computes a new Color4 converted from the current one to linear space
  2083. * @returns a new Color4 object
  2084. */
  2085. Color4.prototype.toLinearSpace = function () {
  2086. var convertedColor = new Color4();
  2087. this.toLinearSpaceToRef(convertedColor);
  2088. return convertedColor;
  2089. };
  2090. /**
  2091. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  2092. * @param convertedColor defines the Color4 object where to store the linear space version
  2093. * @returns the unmodified Color4
  2094. */
  2095. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  2096. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  2097. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  2098. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  2099. convertedColor.a = this.a;
  2100. return this;
  2101. };
  2102. /**
  2103. * Computes a new Color4 converted from the current one to gamma space
  2104. * @returns a new Color4 object
  2105. */
  2106. Color4.prototype.toGammaSpace = function () {
  2107. var convertedColor = new Color4();
  2108. this.toGammaSpaceToRef(convertedColor);
  2109. return convertedColor;
  2110. };
  2111. /**
  2112. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2113. * @param convertedColor defines the Color4 object where to store the gamma space version
  2114. * @returns the unmodified Color4
  2115. */
  2116. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2117. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2118. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2119. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2120. convertedColor.a = this.a;
  2121. return this;
  2122. };
  2123. // Statics
  2124. /**
  2125. * Creates a new Color4 from the string containing valid hexadecimal values
  2126. * @param hex defines a string containing valid hexadecimal values
  2127. * @returns a new Color4 object
  2128. */
  2129. Color4.FromHexString = function (hex) {
  2130. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2131. return new Color4(0.0, 0.0, 0.0, 0.0);
  2132. }
  2133. var r = parseInt(hex.substring(1, 3), 16);
  2134. var g = parseInt(hex.substring(3, 5), 16);
  2135. var b = parseInt(hex.substring(5, 7), 16);
  2136. var a = parseInt(hex.substring(7, 9), 16);
  2137. return Color4.FromInts(r, g, b, a);
  2138. };
  2139. /**
  2140. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2141. * @param left defines the start value
  2142. * @param right defines the end value
  2143. * @param amount defines the gradient factor
  2144. * @returns a new Color4 object
  2145. */
  2146. Color4.Lerp = function (left, right, amount) {
  2147. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2148. Color4.LerpToRef(left, right, amount, result);
  2149. return result;
  2150. };
  2151. /**
  2152. * Set the passed "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2153. * @param left defines the start value
  2154. * @param right defines the end value
  2155. * @param amount defines the gradient factor
  2156. * @param result defines the Color4 object where to store data
  2157. */
  2158. Color4.LerpToRef = function (left, right, amount, result) {
  2159. result.r = left.r + (right.r - left.r) * amount;
  2160. result.g = left.g + (right.g - left.g) * amount;
  2161. result.b = left.b + (right.b - left.b) * amount;
  2162. result.a = left.a + (right.a - left.a) * amount;
  2163. };
  2164. /**
  2165. * Creates a new Color4 from the starting index element of the passed array
  2166. * @param array defines the source array to read from
  2167. * @param offset defines the offset in the source array
  2168. * @returns a new Color4 object
  2169. */
  2170. Color4.FromArray = function (array, offset) {
  2171. if (offset === void 0) { offset = 0; }
  2172. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2173. };
  2174. /**
  2175. * Creates a new Color3 from integer values (< 256)
  2176. * @param r defines the red component to read from (value between 0 and 255)
  2177. * @param g defines the green component to read from (value between 0 and 255)
  2178. * @param b defines the blue component to read from (value between 0 and 255)
  2179. * @param a defines the alpha component to read from (value between 0 and 255)
  2180. * @returns a new Color3 object
  2181. */
  2182. Color4.FromInts = function (r, g, b, a) {
  2183. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2184. };
  2185. /**
  2186. * Check the content of a given array and convert it to an array containing RGBA data
  2187. * If the original array was already containing count * 4 values then it is returned directly
  2188. * @param colors defines the array to check
  2189. * @param count defines the number of RGBA data to expect
  2190. * @returns an array containing count * 4 values (RGBA)
  2191. */
  2192. Color4.CheckColors4 = function (colors, count) {
  2193. // Check if color3 was used
  2194. if (colors.length === count * 3) {
  2195. var colors4 = [];
  2196. for (var index = 0; index < colors.length; index += 3) {
  2197. var newIndex = (index / 3) * 4;
  2198. colors4[newIndex] = colors[index];
  2199. colors4[newIndex + 1] = colors[index + 1];
  2200. colors4[newIndex + 2] = colors[index + 2];
  2201. colors4[newIndex + 3] = 1.0;
  2202. }
  2203. return colors4;
  2204. }
  2205. return colors;
  2206. };
  2207. return Color4;
  2208. }());
  2209. BABYLON.Color4 = Color4;
  2210. var Vector2 = /** @class */ (function () {
  2211. /**
  2212. * Creates a new Vector2 from the passed x and y coordinates.
  2213. */
  2214. function Vector2(x, y) {
  2215. this.x = x;
  2216. this.y = y;
  2217. }
  2218. /**
  2219. * Returns a string with the Vector2 coordinates.
  2220. */
  2221. Vector2.prototype.toString = function () {
  2222. return "{X: " + this.x + " Y:" + this.y + "}";
  2223. };
  2224. /**
  2225. * Returns the string "Vector2"
  2226. */
  2227. Vector2.prototype.getClassName = function () {
  2228. return "Vector2";
  2229. };
  2230. /**
  2231. * Returns the Vector2 hash code as a number.
  2232. */
  2233. Vector2.prototype.getHashCode = function () {
  2234. var hash = this.x || 0;
  2235. hash = (hash * 397) ^ (this.y || 0);
  2236. return hash;
  2237. };
  2238. // Operators
  2239. /**
  2240. * Sets the Vector2 coordinates in the passed array or Float32Array from the passed index.
  2241. * Returns the Vector2.
  2242. */
  2243. Vector2.prototype.toArray = function (array, index) {
  2244. if (index === void 0) { index = 0; }
  2245. array[index] = this.x;
  2246. array[index + 1] = this.y;
  2247. return this;
  2248. };
  2249. /**
  2250. * Returns a new array with 2 elements : the Vector2 coordinates.
  2251. */
  2252. Vector2.prototype.asArray = function () {
  2253. var result = new Array();
  2254. this.toArray(result, 0);
  2255. return result;
  2256. };
  2257. /**
  2258. * Sets the Vector2 coordinates with the passed Vector2 coordinates.
  2259. * Returns the updated Vector2.
  2260. */
  2261. Vector2.prototype.copyFrom = function (source) {
  2262. this.x = source.x;
  2263. this.y = source.y;
  2264. return this;
  2265. };
  2266. /**
  2267. * Sets the Vector2 coordinates with the passed floats.
  2268. * Returns the updated Vector2.
  2269. */
  2270. Vector2.prototype.copyFromFloats = function (x, y) {
  2271. this.x = x;
  2272. this.y = y;
  2273. return this;
  2274. };
  2275. /**
  2276. * Sets the Vector2 coordinates with the passed floats.
  2277. * Returns the updated Vector2.
  2278. */
  2279. Vector2.prototype.set = function (x, y) {
  2280. return this.copyFromFloats(x, y);
  2281. };
  2282. /**
  2283. * Returns a new Vector2 set with the addition of the current Vector2 and the passed one coordinates.
  2284. */
  2285. Vector2.prototype.add = function (otherVector) {
  2286. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2287. };
  2288. /**
  2289. * Sets the "result" coordinates with the addition of the current Vector2 and the passed one coordinates.
  2290. * Returns the Vector2.
  2291. */
  2292. Vector2.prototype.addToRef = function (otherVector, result) {
  2293. result.x = this.x + otherVector.x;
  2294. result.y = this.y + otherVector.y;
  2295. return this;
  2296. };
  2297. /**
  2298. * Set the Vector2 coordinates by adding the passed Vector2 coordinates.
  2299. * Returns the updated Vector2.
  2300. */
  2301. Vector2.prototype.addInPlace = function (otherVector) {
  2302. this.x += otherVector.x;
  2303. this.y += otherVector.y;
  2304. return this;
  2305. };
  2306. /**
  2307. * Returns a new Vector2 by adding the current Vector2 coordinates to the passed Vector3 x, y coordinates.
  2308. */
  2309. Vector2.prototype.addVector3 = function (otherVector) {
  2310. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2311. };
  2312. /**
  2313. * Returns a new Vector2 set with the subtracted coordinates of the passed one from the current Vector2.
  2314. */
  2315. Vector2.prototype.subtract = function (otherVector) {
  2316. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2317. };
  2318. /**
  2319. * Sets the "result" coordinates with the subtraction of the passed one from the current Vector2 coordinates.
  2320. * Returns the Vector2.
  2321. */
  2322. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2323. result.x = this.x - otherVector.x;
  2324. result.y = this.y - otherVector.y;
  2325. return this;
  2326. };
  2327. /**
  2328. * Sets the current Vector2 coordinates by subtracting from it the passed one coordinates.
  2329. * Returns the updated Vector2.
  2330. */
  2331. Vector2.prototype.subtractInPlace = function (otherVector) {
  2332. this.x -= otherVector.x;
  2333. this.y -= otherVector.y;
  2334. return this;
  2335. };
  2336. /**
  2337. * Multiplies in place the current Vector2 coordinates by the passed ones.
  2338. * Returns the updated Vector2.
  2339. */
  2340. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2341. this.x *= otherVector.x;
  2342. this.y *= otherVector.y;
  2343. return this;
  2344. };
  2345. /**
  2346. * Returns a new Vector2 set with the multiplication of the current Vector2 and the passed one coordinates.
  2347. */
  2348. Vector2.prototype.multiply = function (otherVector) {
  2349. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2350. };
  2351. /**
  2352. * Sets "result" coordinates with the multiplication of the current Vector2 and the passed one coordinates.
  2353. * Returns the Vector2.
  2354. */
  2355. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2356. result.x = this.x * otherVector.x;
  2357. result.y = this.y * otherVector.y;
  2358. return this;
  2359. };
  2360. /**
  2361. * Returns a new Vector2 set with the Vector2 coordinates multiplied by the passed floats.
  2362. */
  2363. Vector2.prototype.multiplyByFloats = function (x, y) {
  2364. return new Vector2(this.x * x, this.y * y);
  2365. };
  2366. /**
  2367. * Returns a new Vector2 set with the Vector2 coordinates divided by the passed one coordinates.
  2368. */
  2369. Vector2.prototype.divide = function (otherVector) {
  2370. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2371. };
  2372. /**
  2373. * Sets the "result" coordinates with the Vector2 divided by the passed one coordinates.
  2374. * Returns the Vector2.
  2375. */
  2376. Vector2.prototype.divideToRef = function (otherVector, result) {
  2377. result.x = this.x / otherVector.x;
  2378. result.y = this.y / otherVector.y;
  2379. return this;
  2380. };
  2381. /**
  2382. * Divides the current Vector3 coordinates by the passed ones.
  2383. * Returns the updated Vector3.
  2384. */
  2385. Vector2.prototype.divideInPlace = function (otherVector) {
  2386. return this.divideToRef(otherVector, this);
  2387. };
  2388. /**
  2389. * Returns a new Vector2 with current Vector2 negated coordinates.
  2390. */
  2391. Vector2.prototype.negate = function () {
  2392. return new Vector2(-this.x, -this.y);
  2393. };
  2394. /**
  2395. * Multiply the Vector2 coordinates by scale.
  2396. * Returns the updated Vector2.
  2397. */
  2398. Vector2.prototype.scaleInPlace = function (scale) {
  2399. this.x *= scale;
  2400. this.y *= scale;
  2401. return this;
  2402. };
  2403. /**
  2404. * Returns a new Vector2 scaled by "scale" from the current Vector2.
  2405. */
  2406. Vector2.prototype.scale = function (scale) {
  2407. return new Vector2(this.x * scale, this.y * scale);
  2408. };
  2409. /**
  2410. * Boolean : True if the passed vector coordinates strictly equal the current Vector2 ones.
  2411. */
  2412. Vector2.prototype.equals = function (otherVector) {
  2413. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2414. };
  2415. /**
  2416. * Boolean : True if the passed vector coordinates are close to the current ones by a distance of epsilon.
  2417. */
  2418. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2419. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2420. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2421. };
  2422. // Properties
  2423. /**
  2424. * Returns the vector length (float).
  2425. */
  2426. Vector2.prototype.length = function () {
  2427. return Math.sqrt(this.x * this.x + this.y * this.y);
  2428. };
  2429. /**
  2430. * Returns the vector squared length (float);
  2431. */
  2432. Vector2.prototype.lengthSquared = function () {
  2433. return (this.x * this.x + this.y * this.y);
  2434. };
  2435. // Methods
  2436. /**
  2437. * Normalize the vector.
  2438. * Returns the updated Vector2.
  2439. */
  2440. Vector2.prototype.normalize = function () {
  2441. var len = this.length();
  2442. if (len === 0)
  2443. return this;
  2444. var num = 1.0 / len;
  2445. this.x *= num;
  2446. this.y *= num;
  2447. return this;
  2448. };
  2449. /**
  2450. * Returns a new Vector2 copied from the Vector2.
  2451. */
  2452. Vector2.prototype.clone = function () {
  2453. return new Vector2(this.x, this.y);
  2454. };
  2455. // Statics
  2456. /**
  2457. * Returns a new Vector2(0, 0)
  2458. */
  2459. Vector2.Zero = function () {
  2460. return new Vector2(0, 0);
  2461. };
  2462. /**
  2463. * Returns a new Vector2(1, 1)
  2464. */
  2465. Vector2.One = function () {
  2466. return new Vector2(1, 1);
  2467. };
  2468. /**
  2469. * Returns a new Vector2 set from the passed index element of the passed array.
  2470. */
  2471. Vector2.FromArray = function (array, offset) {
  2472. if (offset === void 0) { offset = 0; }
  2473. return new Vector2(array[offset], array[offset + 1]);
  2474. };
  2475. /**
  2476. * Sets "result" from the passed index element of the passed array.
  2477. */
  2478. Vector2.FromArrayToRef = function (array, offset, result) {
  2479. result.x = array[offset];
  2480. result.y = array[offset + 1];
  2481. };
  2482. /**
  2483. * Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the passed four Vector2.
  2484. */
  2485. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2486. var squared = amount * amount;
  2487. var cubed = amount * squared;
  2488. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2489. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2490. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2491. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2492. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2493. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2494. return new Vector2(x, y);
  2495. };
  2496. /**
  2497. * 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".
  2498. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2499. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
  2500. */
  2501. Vector2.Clamp = function (value, min, max) {
  2502. var x = value.x;
  2503. x = (x > max.x) ? max.x : x;
  2504. x = (x < min.x) ? min.x : x;
  2505. var y = value.y;
  2506. y = (y > max.y) ? max.y : y;
  2507. y = (y < min.y) ? min.y : y;
  2508. return new Vector2(x, y);
  2509. };
  2510. /**
  2511. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
  2512. */
  2513. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2514. var squared = amount * amount;
  2515. var cubed = amount * squared;
  2516. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2517. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2518. var part3 = (cubed - (2.0 * squared)) + amount;
  2519. var part4 = cubed - squared;
  2520. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2521. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2522. return new Vector2(x, y);
  2523. };
  2524. /**
  2525. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2526. */
  2527. Vector2.Lerp = function (start, end, amount) {
  2528. var x = start.x + ((end.x - start.x) * amount);
  2529. var y = start.y + ((end.y - start.y) * amount);
  2530. return new Vector2(x, y);
  2531. };
  2532. /**
  2533. * Returns the dot product (float) of the vector "left" and the vector "right".
  2534. */
  2535. Vector2.Dot = function (left, right) {
  2536. return left.x * right.x + left.y * right.y;
  2537. };
  2538. /**
  2539. * Returns a new Vector2 equal to the normalized passed vector.
  2540. */
  2541. Vector2.Normalize = function (vector) {
  2542. var newVector = vector.clone();
  2543. newVector.normalize();
  2544. return newVector;
  2545. };
  2546. /**
  2547. * Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
  2548. */
  2549. Vector2.Minimize = function (left, right) {
  2550. var x = (left.x < right.x) ? left.x : right.x;
  2551. var y = (left.y < right.y) ? left.y : right.y;
  2552. return new Vector2(x, y);
  2553. };
  2554. /**
  2555. * Returns a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors.
  2556. */
  2557. Vector2.Maximize = function (left, right) {
  2558. var x = (left.x > right.x) ? left.x : right.x;
  2559. var y = (left.y > right.y) ? left.y : right.y;
  2560. return new Vector2(x, y);
  2561. };
  2562. /**
  2563. * Returns a new Vecto2 set with the transformed coordinates of the passed vector by the passed transformation matrix.
  2564. */
  2565. Vector2.Transform = function (vector, transformation) {
  2566. var r = Vector2.Zero();
  2567. Vector2.TransformToRef(vector, transformation, r);
  2568. return r;
  2569. };
  2570. /**
  2571. * Transforms the passed vector coordinates by the passed transformation matrix and stores the result in the vector "result" coordinates.
  2572. */
  2573. Vector2.TransformToRef = function (vector, transformation, result) {
  2574. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2575. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2576. result.x = x;
  2577. result.y = y;
  2578. };
  2579. /**
  2580. * Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2581. */
  2582. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2583. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2584. var sign = a < 0 ? -1 : 1;
  2585. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2586. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2587. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2588. };
  2589. /**
  2590. * Returns the distance (float) between the vectors "value1" and "value2".
  2591. */
  2592. Vector2.Distance = function (value1, value2) {
  2593. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2594. };
  2595. /**
  2596. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2597. */
  2598. Vector2.DistanceSquared = function (value1, value2) {
  2599. var x = value1.x - value2.x;
  2600. var y = value1.y - value2.y;
  2601. return (x * x) + (y * y);
  2602. };
  2603. /**
  2604. * Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
  2605. */
  2606. Vector2.Center = function (value1, value2) {
  2607. var center = value1.add(value2);
  2608. center.scaleInPlace(0.5);
  2609. return center;
  2610. };
  2611. /**
  2612. * Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2613. */
  2614. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2615. var l2 = Vector2.DistanceSquared(segA, segB);
  2616. if (l2 === 0.0) {
  2617. return Vector2.Distance(p, segA);
  2618. }
  2619. var v = segB.subtract(segA);
  2620. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2621. var proj = segA.add(v.multiplyByFloats(t, t));
  2622. return Vector2.Distance(p, proj);
  2623. };
  2624. return Vector2;
  2625. }());
  2626. BABYLON.Vector2 = Vector2;
  2627. /**
  2628. * Classed used to store (x,y,z) vector representation
  2629. * A Vector3 is the main object used in 3D geometry
  2630. * It can represent etiher the coordinates of a point the space, either a direction
  2631. * Reminder: Babylon.js uses a left handed forward facing system
  2632. */
  2633. var Vector3 = /** @class */ (function () {
  2634. /**
  2635. * Creates a new Vector3 object from the passed x, y, z (floats) coordinates.
  2636. * @param x defines the first coordinates (on X axis)
  2637. * @param y defines the second coordinates (on Y axis)
  2638. * @param z defines the third coordinates (on Z axis)
  2639. */
  2640. function Vector3(
  2641. /**
  2642. * Defines the first coordinates (on X axis)
  2643. */
  2644. x,
  2645. /**
  2646. * Defines the second coordinates (on Y axis)
  2647. */
  2648. y,
  2649. /**
  2650. * Defines the third coordinates (on Z axis)
  2651. */
  2652. z) {
  2653. this.x = x;
  2654. this.y = y;
  2655. this.z = z;
  2656. }
  2657. /**
  2658. * Creates a string representation of the Vector3
  2659. * @returns a string with the Vector3 coordinates.
  2660. */
  2661. Vector3.prototype.toString = function () {
  2662. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2663. };
  2664. /**
  2665. * Gets the class name
  2666. * @returns the string "Vector3"
  2667. */
  2668. Vector3.prototype.getClassName = function () {
  2669. return "Vector3";
  2670. };
  2671. /**
  2672. * Creates the Vector3 hash code
  2673. * @returns a number which tends to be unique between Vector3 instances
  2674. */
  2675. Vector3.prototype.getHashCode = function () {
  2676. var hash = this.x || 0;
  2677. hash = (hash * 397) ^ (this.y || 0);
  2678. hash = (hash * 397) ^ (this.z || 0);
  2679. return hash;
  2680. };
  2681. // Operators
  2682. /**
  2683. * Creates an array containing three elements : the coordinates of the Vector3
  2684. * @returns a new array of numbers
  2685. */
  2686. Vector3.prototype.asArray = function () {
  2687. var result = [];
  2688. this.toArray(result, 0);
  2689. return result;
  2690. };
  2691. /**
  2692. * Populates the passed array or Float32Array from the passed index with the successive coordinates of the Vector3
  2693. * @param array defines the destination array
  2694. * @param index defines the offset in the destination array
  2695. * @returns the current Vector3
  2696. */
  2697. Vector3.prototype.toArray = function (array, index) {
  2698. if (index === void 0) { index = 0; }
  2699. array[index] = this.x;
  2700. array[index + 1] = this.y;
  2701. array[index + 2] = this.z;
  2702. return this;
  2703. };
  2704. /**
  2705. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2706. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2707. */
  2708. Vector3.prototype.toQuaternion = function () {
  2709. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  2710. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  2711. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  2712. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  2713. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  2714. var cosy = Math.cos(this.y * 0.5);
  2715. var siny = Math.sin(this.y * 0.5);
  2716. result.x = coszMinusx * siny;
  2717. result.y = -sinzMinusx * siny;
  2718. result.z = sinxPlusz * cosy;
  2719. result.w = cosxPlusz * cosy;
  2720. return result;
  2721. };
  2722. /**
  2723. * Adds the passed vector to the current Vector3
  2724. * @param otherVector defines the second operand
  2725. * @returns the current updated Vector3
  2726. */
  2727. Vector3.prototype.addInPlace = function (otherVector) {
  2728. this.x += otherVector.x;
  2729. this.y += otherVector.y;
  2730. this.z += otherVector.z;
  2731. return this;
  2732. };
  2733. /**
  2734. * Gets a new Vector3, result of the addition the current Vector3 and the passed vector
  2735. * @param otherVector defines the second operand
  2736. * @returns the resulting Vector3
  2737. */
  2738. Vector3.prototype.add = function (otherVector) {
  2739. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2740. };
  2741. /**
  2742. * Adds the current Vector3 to the passed one and stores the result in the vector "result"
  2743. * @param otherVector defines the second operand
  2744. * @param result defines the Vector3 object where to store the result
  2745. * @returns the current Vector3
  2746. */
  2747. Vector3.prototype.addToRef = function (otherVector, result) {
  2748. result.x = this.x + otherVector.x;
  2749. result.y = this.y + otherVector.y;
  2750. result.z = this.z + otherVector.z;
  2751. return this;
  2752. };
  2753. /**
  2754. * Subtract the passed vector from the current Vector3
  2755. * @param otherVector defines the second operand
  2756. * @returns the current updated Vector3
  2757. */
  2758. Vector3.prototype.subtractInPlace = function (otherVector) {
  2759. this.x -= otherVector.x;
  2760. this.y -= otherVector.y;
  2761. this.z -= otherVector.z;
  2762. return this;
  2763. };
  2764. /**
  2765. * Returns a new Vector3, result of the subtraction of the passed vector from the current Vector3
  2766. * @param otherVector defines the second operand
  2767. * @returns the resulting Vector3
  2768. */
  2769. Vector3.prototype.subtract = function (otherVector) {
  2770. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2771. };
  2772. /**
  2773. * Subtracts the passed vector from the current Vector3 and stores the result in the vector "result".
  2774. * @param otherVector defines the second operand
  2775. * @param result defines the Vector3 object where to store the result
  2776. * @returns the current Vector3
  2777. */
  2778. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2779. result.x = this.x - otherVector.x;
  2780. result.y = this.y - otherVector.y;
  2781. result.z = this.z - otherVector.z;
  2782. return this;
  2783. };
  2784. /**
  2785. * Returns a new Vector3 set with the subtraction of the passed floats from the current Vector3 coordinates
  2786. * @param x defines the x coordinate of the operand
  2787. * @param y defines the y coordinate of the operand
  2788. * @param z defines the z coordinate of the operand
  2789. * @returns the resulting Vector3
  2790. */
  2791. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2792. return new Vector3(this.x - x, this.y - y, this.z - z);
  2793. };
  2794. /**
  2795. * Subtracts the passed floats from the current Vector3 coordinates and set the passed vector "result" with this result
  2796. * @param x defines the x coordinate of the operand
  2797. * @param y defines the y coordinate of the operand
  2798. * @param z defines the z coordinate of the operand
  2799. * @param result defines the Vector3 object where to store the result
  2800. * @returns the current Vector3
  2801. */
  2802. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2803. result.x = this.x - x;
  2804. result.y = this.y - y;
  2805. result.z = this.z - z;
  2806. return this;
  2807. };
  2808. /**
  2809. * Gets a new Vector3 set with the current Vector3 negated coordinates
  2810. * @returns a new Vector3
  2811. */
  2812. Vector3.prototype.negate = function () {
  2813. return new Vector3(-this.x, -this.y, -this.z);
  2814. };
  2815. /**
  2816. * Multiplies the Vector3 coordinates by the float "scale"
  2817. * @param scale defines the multiplier factor
  2818. * @returns the current updated Vector3
  2819. */
  2820. Vector3.prototype.scaleInPlace = function (scale) {
  2821. this.x *= scale;
  2822. this.y *= scale;
  2823. this.z *= scale;
  2824. return this;
  2825. };
  2826. /**
  2827. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  2828. * @param scale defines the multiplier factor
  2829. * @returns a new Vector3
  2830. */
  2831. Vector3.prototype.scale = function (scale) {
  2832. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  2833. };
  2834. /**
  2835. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the passed vector "result" coordinates
  2836. * @param scale defines the multiplier factor
  2837. * @param result defines the Vector3 object where to store the result
  2838. * @returns the current Vector3
  2839. */
  2840. Vector3.prototype.scaleToRef = function (scale, result) {
  2841. result.x = this.x * scale;
  2842. result.y = this.y * scale;
  2843. result.z = this.z * scale;
  2844. return this;
  2845. };
  2846. /**
  2847. * Returns true if the current Vector3 and the passed vector coordinates are strictly equal
  2848. * @param otherVector defines the second operand
  2849. * @returns true if both vectors are equals
  2850. */
  2851. Vector3.prototype.equals = function (otherVector) {
  2852. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  2853. };
  2854. /**
  2855. * Returns true if the current Vector3 and the passed vector coordinates are distant less than epsilon
  2856. * @param otherVector defines the second operand
  2857. * @param epsilon defines the minimal distance to define values as equals
  2858. * @returns true if both vectors are distant less than epsilon
  2859. */
  2860. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2861. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2862. 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);
  2863. };
  2864. /**
  2865. * Returns true if the current Vector3 coordinates equals the passed floats
  2866. * @param x defines the x coordinate of the operand
  2867. * @param y defines the y coordinate of the operand
  2868. * @param z defines the z coordinate of the operand
  2869. * @returns true if both vectors are equals
  2870. */
  2871. Vector3.prototype.equalsToFloats = function (x, y, z) {
  2872. return this.x === x && this.y === y && this.z === z;
  2873. };
  2874. /**
  2875. * Multiplies the current Vector3 coordinates by the passed ones
  2876. * @param otherVector defines the second operand
  2877. * @returns the current updated Vector3
  2878. */
  2879. Vector3.prototype.multiplyInPlace = function (otherVector) {
  2880. this.x *= otherVector.x;
  2881. this.y *= otherVector.y;
  2882. this.z *= otherVector.z;
  2883. return this;
  2884. };
  2885. /**
  2886. * Returns a new Vector3, result of the multiplication of the current Vector3 by the passed vector
  2887. * @param otherVector defines the second operand
  2888. * @returns the new Vector3
  2889. */
  2890. Vector3.prototype.multiply = function (otherVector) {
  2891. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  2892. };
  2893. /**
  2894. * Multiplies the current Vector3 by the passed one and stores the result in the passed vector "result"
  2895. * @param otherVector defines the second operand
  2896. * @param result defines the Vector3 object where to store the result
  2897. * @returns the current Vector3
  2898. */
  2899. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  2900. result.x = this.x * otherVector.x;
  2901. result.y = this.y * otherVector.y;
  2902. result.z = this.z * otherVector.z;
  2903. return this;
  2904. };
  2905. /**
  2906. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the passed floats
  2907. * @param x defines the x coordinate of the operand
  2908. * @param y defines the y coordinate of the operand
  2909. * @param z defines the z coordinate of the operand
  2910. * @returns the new Vector3
  2911. */
  2912. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  2913. return new Vector3(this.x * x, this.y * y, this.z * z);
  2914. };
  2915. /**
  2916. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the passed ones
  2917. * @param otherVector defines the second operand
  2918. * @returns the new Vector3
  2919. */
  2920. Vector3.prototype.divide = function (otherVector) {
  2921. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  2922. };
  2923. /**
  2924. * Divides the current Vector3 coordinates by the passed ones and stores the result in the passed vector "result"
  2925. * @param otherVector defines the second operand
  2926. * @param result defines the Vector3 object where to store the result
  2927. * @returns the current Vector3
  2928. */
  2929. Vector3.prototype.divideToRef = function (otherVector, result) {
  2930. result.x = this.x / otherVector.x;
  2931. result.y = this.y / otherVector.y;
  2932. result.z = this.z / otherVector.z;
  2933. return this;
  2934. };
  2935. /**
  2936. * Divides the current Vector3 coordinates by the passed ones.
  2937. * @param otherVector defines the second operand
  2938. * @returns the current updated Vector3
  2939. */
  2940. Vector3.prototype.divideInPlace = function (otherVector) {
  2941. return this.divideToRef(otherVector, this);
  2942. };
  2943. /**
  2944. * Updates the current Vector3 with the minimal coordinate values between its and the passed vector ones
  2945. * @param other defines the second operand
  2946. * @returns the current updated Vector3
  2947. */
  2948. Vector3.prototype.minimizeInPlace = function (other) {
  2949. if (other.x < this.x)
  2950. this.x = other.x;
  2951. if (other.y < this.y)
  2952. this.y = other.y;
  2953. if (other.z < this.z)
  2954. this.z = other.z;
  2955. return this;
  2956. };
  2957. /**
  2958. * Updates the current Vector3 with the maximal coordinate values between its and the passed vector ones.
  2959. * @param other defines the second operand
  2960. * @returns the current updated Vector3
  2961. */
  2962. Vector3.prototype.maximizeInPlace = function (other) {
  2963. if (other.x > this.x)
  2964. this.x = other.x;
  2965. if (other.y > this.y)
  2966. this.y = other.y;
  2967. if (other.z > this.z)
  2968. this.z = other.z;
  2969. return this;
  2970. };
  2971. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  2972. /**
  2973. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  2974. */
  2975. get: function () {
  2976. var absX = Math.abs(this.x);
  2977. var absY = Math.abs(this.y);
  2978. if (absX !== absY) {
  2979. return true;
  2980. }
  2981. var absZ = Math.abs(this.z);
  2982. if (absX !== absZ) {
  2983. return true;
  2984. }
  2985. if (absY !== absZ) {
  2986. return true;
  2987. }
  2988. return false;
  2989. },
  2990. enumerable: true,
  2991. configurable: true
  2992. });
  2993. // Properties
  2994. /**
  2995. * Gets the length of the Vector3
  2996. * @returns the length of the Vecto3
  2997. */
  2998. Vector3.prototype.length = function () {
  2999. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  3000. };
  3001. /**
  3002. * Gets the squared length of the Vector3
  3003. * @returns squared length of the Vector3
  3004. */
  3005. Vector3.prototype.lengthSquared = function () {
  3006. return (this.x * this.x + this.y * this.y + this.z * this.z);
  3007. };
  3008. /**
  3009. * Normalize the current Vector3.
  3010. * Please note that this is an in place operation.
  3011. * @returns the current updated Vector3
  3012. */
  3013. Vector3.prototype.normalize = function () {
  3014. var len = this.length();
  3015. if (len === 0 || len === 1.0)
  3016. return this;
  3017. var num = 1.0 / len;
  3018. this.x *= num;
  3019. this.y *= num;
  3020. this.z *= num;
  3021. return this;
  3022. };
  3023. /**
  3024. * Normalize the current Vector3 to a new vector
  3025. * @returns the new Vector3
  3026. */
  3027. Vector3.prototype.normalizeToNew = function () {
  3028. var normalized = new Vector3(0, 0, 0);
  3029. this.normalizeToRef(normalized);
  3030. return normalized;
  3031. };
  3032. /**
  3033. * Normalize the current Vector3 to the reference
  3034. * @param reference define the Vector3 to update
  3035. * @returns the updated Vector3
  3036. */
  3037. Vector3.prototype.normalizeToRef = function (reference) {
  3038. var len = this.length();
  3039. if (len === 0 || len === 1.0) {
  3040. reference.set(this.x, this.y, this.z);
  3041. return reference;
  3042. }
  3043. var scale = 1.0 / len;
  3044. this.scaleToRef(scale, reference);
  3045. return reference;
  3046. };
  3047. /**
  3048. * Creates a new Vector3 copied from the current Vector3
  3049. * @returns the new Vector3
  3050. */
  3051. Vector3.prototype.clone = function () {
  3052. return new Vector3(this.x, this.y, this.z);
  3053. };
  3054. /**
  3055. * Copies the passed vector coordinates to the current Vector3 ones
  3056. * @param source defines the source Vector3
  3057. * @returns the current updated Vector3
  3058. */
  3059. Vector3.prototype.copyFrom = function (source) {
  3060. this.x = source.x;
  3061. this.y = source.y;
  3062. this.z = source.z;
  3063. return this;
  3064. };
  3065. /**
  3066. * Copies the passed floats to the current Vector3 coordinates
  3067. * @param x defines the x coordinate of the operand
  3068. * @param y defines the y coordinate of the operand
  3069. * @param z defines the z coordinate of the operand
  3070. * @returns the current updated Vector3
  3071. */
  3072. Vector3.prototype.copyFromFloats = function (x, y, z) {
  3073. this.x = x;
  3074. this.y = y;
  3075. this.z = z;
  3076. return this;
  3077. };
  3078. /**
  3079. * Copies the passed floats to the current Vector3 coordinates
  3080. * @param x defines the x coordinate of the operand
  3081. * @param y defines the y coordinate of the operand
  3082. * @param z defines the z coordinate of the operand
  3083. * @returns the current updated Vector3
  3084. */
  3085. Vector3.prototype.set = function (x, y, z) {
  3086. return this.copyFromFloats(x, y, z);
  3087. };
  3088. // Statics
  3089. /**
  3090. * Get the clip factor between two vectors
  3091. * @param vector0 defines the first operand
  3092. * @param vector1 defines the second operand
  3093. * @param axis defines the axis to use
  3094. * @param size defines the size along the axis
  3095. * @returns the clip factor
  3096. */
  3097. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3098. var d0 = Vector3.Dot(vector0, axis) - size;
  3099. var d1 = Vector3.Dot(vector1, axis) - size;
  3100. var s = d0 / (d0 - d1);
  3101. return s;
  3102. };
  3103. /**
  3104. * Get angle between two vectors
  3105. * @param vector0 angle between vector0 and vector1
  3106. * @param vector1 angle between vector0 and vector1
  3107. * @param normal direction of the normal
  3108. * @return the angle between vector0 and vector1
  3109. */
  3110. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3111. var v0 = vector0.clone().normalize();
  3112. var v1 = vector1.clone().normalize();
  3113. var dot = Vector3.Dot(v0, v1);
  3114. var n = Vector3.Cross(v0, v1);
  3115. if (Vector3.Dot(n, normal) > 0) {
  3116. return Math.acos(dot);
  3117. }
  3118. return -Math.acos(dot);
  3119. };
  3120. /**
  3121. * Returns a new Vector3 set from the index "offset" of the passed array
  3122. * @param array defines the source array
  3123. * @param offset defines the offset in the source array
  3124. * @returns the new Vector3
  3125. */
  3126. Vector3.FromArray = function (array, offset) {
  3127. if (!offset) {
  3128. offset = 0;
  3129. }
  3130. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3131. };
  3132. /**
  3133. * Returns a new Vector3 set from the index "offset" of the passed Float32Array
  3134. * This function is deprecated. Use FromArray instead
  3135. * @param array defines the source array
  3136. * @param offset defines the offset in the source array
  3137. * @returns the new Vector3
  3138. */
  3139. Vector3.FromFloatArray = function (array, offset) {
  3140. return Vector3.FromArray(array, offset);
  3141. };
  3142. /**
  3143. * Sets the passed vector "result" with the element values from the index "offset" of the passed array
  3144. * @param array defines the source array
  3145. * @param offset defines the offset in the source array
  3146. * @param result defines the Vector3 where to store the result
  3147. */
  3148. Vector3.FromArrayToRef = function (array, offset, result) {
  3149. result.x = array[offset];
  3150. result.y = array[offset + 1];
  3151. result.z = array[offset + 2];
  3152. };
  3153. /**
  3154. * Sets the passed vector "result" with the element values from the index "offset" of the passed Float32Array
  3155. * This function is deprecated. Use FromArrayToRef instead.
  3156. * @param array defines the source array
  3157. * @param offset defines the offset in the source array
  3158. * @param result defines the Vector3 where to store the result
  3159. */
  3160. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3161. return Vector3.FromArrayToRef(array, offset, result);
  3162. };
  3163. /**
  3164. * Sets the passed vector "result" with the passed floats.
  3165. * @param x defines the x coordinate of the source
  3166. * @param y defines the y coordinate of the source
  3167. * @param z defines the z coordinate of the source
  3168. * @param result defines the Vector3 where to store the result
  3169. */
  3170. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3171. result.x = x;
  3172. result.y = y;
  3173. result.z = z;
  3174. };
  3175. /**
  3176. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3177. * @returns a new empty Vector3
  3178. */
  3179. Vector3.Zero = function () {
  3180. return new Vector3(0.0, 0.0, 0.0);
  3181. };
  3182. /**
  3183. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3184. * @returns a new unit Vector3
  3185. */
  3186. Vector3.One = function () {
  3187. return new Vector3(1.0, 1.0, 1.0);
  3188. };
  3189. /**
  3190. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3191. * @returns a new up Vector3
  3192. */
  3193. Vector3.Up = function () {
  3194. return new Vector3(0.0, 1.0, 0.0);
  3195. };
  3196. /**
  3197. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3198. * @returns a new forward Vector3
  3199. */
  3200. Vector3.Forward = function () {
  3201. return new Vector3(0.0, 0.0, 1.0);
  3202. };
  3203. /**
  3204. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3205. * @returns a new right Vector3
  3206. */
  3207. Vector3.Right = function () {
  3208. return new Vector3(1.0, 0.0, 0.0);
  3209. };
  3210. /**
  3211. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3212. * @returns a new left Vector3
  3213. */
  3214. Vector3.Left = function () {
  3215. return new Vector3(-1.0, 0.0, 0.0);
  3216. };
  3217. /**
  3218. * Returns a new Vector3 set with the result of the transformation by the passed matrix of the passed vector.
  3219. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3220. * @param vector defines the Vector3 to transform
  3221. * @param transformation defines the transformation matrix
  3222. * @returns the transformed Vector3
  3223. */
  3224. Vector3.TransformCoordinates = function (vector, transformation) {
  3225. var result = Vector3.Zero();
  3226. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3227. return result;
  3228. };
  3229. /**
  3230. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed vector
  3231. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3232. * @param vector defines the Vector3 to transform
  3233. * @param transformation defines the transformation matrix
  3234. * @param result defines the Vector3 where to store the result
  3235. */
  3236. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3237. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3238. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3239. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3240. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3241. result.x = x / w;
  3242. result.y = y / w;
  3243. result.z = z / w;
  3244. };
  3245. /**
  3246. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed floats (x, y, z)
  3247. * This method computes tranformed coordinates only, not transformed direction vectors
  3248. * @param x define the x coordinate of the source vector
  3249. * @param y define the y coordinate of the source vector
  3250. * @param z define the z coordinate of the source vector
  3251. * @param transformation defines the transformation matrix
  3252. * @param result defines the Vector3 where to store the result
  3253. */
  3254. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3255. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3256. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3257. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3258. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3259. result.x = rx / rw;
  3260. result.y = ry / rw;
  3261. result.z = rz / rw;
  3262. };
  3263. /**
  3264. * Returns a new Vector3 set with the result of the normal transformation by the passed matrix of the passed vector
  3265. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3266. * @param vector defines the Vector3 to transform
  3267. * @param transformation defines the transformation matrix
  3268. * @returns the new Vector3
  3269. */
  3270. Vector3.TransformNormal = function (vector, transformation) {
  3271. var result = Vector3.Zero();
  3272. Vector3.TransformNormalToRef(vector, transformation, result);
  3273. return result;
  3274. };
  3275. /**
  3276. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector
  3277. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3278. * @param vector defines the Vector3 to transform
  3279. * @param transformation defines the transformation matrix
  3280. * @param result defines the Vector3 where to store the result
  3281. */
  3282. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3283. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3284. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3285. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3286. result.x = x;
  3287. result.y = y;
  3288. result.z = z;
  3289. };
  3290. /**
  3291. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z)
  3292. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3293. * @param x define the x coordinate of the source vector
  3294. * @param y define the y coordinate of the source vector
  3295. * @param z define the z coordinate of the source vector
  3296. * @param transformation defines the transformation matrix
  3297. * @param result defines the Vector3 where to store the result
  3298. */
  3299. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3300. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3301. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3302. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3303. };
  3304. /**
  3305. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3306. * @param value1 defines the first control point
  3307. * @param value2 defines the second control point
  3308. * @param value3 defines the third control point
  3309. * @param value4 defines the fourth control point
  3310. * @param amount defines the amount on the spline to use
  3311. * @returns the new Vector3
  3312. */
  3313. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3314. var squared = amount * amount;
  3315. var cubed = amount * squared;
  3316. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3317. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3318. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3319. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3320. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3321. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3322. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3323. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3324. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3325. return new Vector3(x, y, z);
  3326. };
  3327. /**
  3328. * 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"
  3329. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3330. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3331. * @param value defines the current value
  3332. * @param min defines the lower range value
  3333. * @param max defines the upper range value
  3334. * @returns the new Vector3
  3335. */
  3336. Vector3.Clamp = function (value, min, max) {
  3337. var x = value.x;
  3338. x = (x > max.x) ? max.x : x;
  3339. x = (x < min.x) ? min.x : x;
  3340. var y = value.y;
  3341. y = (y > max.y) ? max.y : y;
  3342. y = (y < min.y) ? min.y : y;
  3343. var z = value.z;
  3344. z = (z > max.z) ? max.z : z;
  3345. z = (z < min.z) ? min.z : z;
  3346. return new Vector3(x, y, z);
  3347. };
  3348. /**
  3349. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3350. * @param value1 defines the first control point
  3351. * @param tangent1 defines the first tangent vector
  3352. * @param value2 defines the second control point
  3353. * @param tangent2 defines the second tangent vector
  3354. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3355. * @returns the new Vector3
  3356. */
  3357. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3358. var squared = amount * amount;
  3359. var cubed = amount * squared;
  3360. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3361. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3362. var part3 = (cubed - (2.0 * squared)) + amount;
  3363. var part4 = cubed - squared;
  3364. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3365. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3366. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3367. return new Vector3(x, y, z);
  3368. };
  3369. /**
  3370. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3371. * @param start defines the start value
  3372. * @param end defines the end value
  3373. * @param amount max defines amount between both (between 0 and 1)
  3374. * @returns the new Vector3
  3375. */
  3376. Vector3.Lerp = function (start, end, amount) {
  3377. var result = new Vector3(0, 0, 0);
  3378. Vector3.LerpToRef(start, end, amount, result);
  3379. return result;
  3380. };
  3381. /**
  3382. * Sets the passed vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3383. * @param start defines the start value
  3384. * @param end defines the end value
  3385. * @param amount max defines amount between both (between 0 and 1)
  3386. * @param result defines the Vector3 where to store the result
  3387. */
  3388. Vector3.LerpToRef = function (start, end, amount, result) {
  3389. result.x = start.x + ((end.x - start.x) * amount);
  3390. result.y = start.y + ((end.y - start.y) * amount);
  3391. result.z = start.z + ((end.z - start.z) * amount);
  3392. };
  3393. /**
  3394. * Returns the dot product (float) between the vectors "left" and "right"
  3395. * @param left defines the left operand
  3396. * @param right defines the right operand
  3397. * @returns the dot product
  3398. */
  3399. Vector3.Dot = function (left, right) {
  3400. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3401. };
  3402. /**
  3403. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3404. * The cross product is then orthogonal to both "left" and "right"
  3405. * @param left defines the left operand
  3406. * @param right defines the right operand
  3407. * @returns the cross product
  3408. */
  3409. Vector3.Cross = function (left, right) {
  3410. var result = Vector3.Zero();
  3411. Vector3.CrossToRef(left, right, result);
  3412. return result;
  3413. };
  3414. /**
  3415. * Sets the passed vector "result" with the cross product of "left" and "right"
  3416. * The cross product is then orthogonal to both "left" and "right"
  3417. * @param left defines the left operand
  3418. * @param right defines the right operand
  3419. * @param result defines the Vector3 where to store the result
  3420. */
  3421. Vector3.CrossToRef = function (left, right, result) {
  3422. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3423. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3424. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3425. result.copyFrom(MathTmp.Vector3[0]);
  3426. };
  3427. /**
  3428. * Returns a new Vector3 as the normalization of the passed vector
  3429. * @param vector defines the Vector3 to normalize
  3430. * @returns the new Vector3
  3431. */
  3432. Vector3.Normalize = function (vector) {
  3433. var result = Vector3.Zero();
  3434. Vector3.NormalizeToRef(vector, result);
  3435. return result;
  3436. };
  3437. /**
  3438. * Sets the passed vector "result" with the normalization of the passed first vector
  3439. * @param vector defines the Vector3 to normalize
  3440. * @param result defines the Vector3 where to store the result
  3441. */
  3442. Vector3.NormalizeToRef = function (vector, result) {
  3443. result.copyFrom(vector);
  3444. result.normalize();
  3445. };
  3446. /**
  3447. * Project a Vector3 onto screen space
  3448. * @param vector defines the Vector3 to project
  3449. * @param world defines the world matrix to use
  3450. * @param transform defines the transform (view x projection) matrix to use
  3451. * @param viewport defines the screen viewport to use
  3452. * @returns the new Vector3
  3453. */
  3454. Vector3.Project = function (vector, world, transform, viewport) {
  3455. var cw = viewport.width;
  3456. var ch = viewport.height;
  3457. var cx = viewport.x;
  3458. var cy = viewport.y;
  3459. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3460. 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);
  3461. var matrix = MathTmp.Matrix[0];
  3462. world.multiplyToRef(transform, matrix);
  3463. matrix.multiplyToRef(viewportMatrix, matrix);
  3464. return Vector3.TransformCoordinates(vector, matrix);
  3465. };
  3466. /**
  3467. * Unproject from screen space to object space
  3468. * @param source defines the screen space Vector3 to use
  3469. * @param viewportWidth defines the current width of the viewport
  3470. * @param viewportHeight defines the current height of the viewport
  3471. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3472. * @param transform defines the transform (view x projection) matrix to use
  3473. * @returns the new Vector3
  3474. */
  3475. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3476. var matrix = MathTmp.Matrix[0];
  3477. world.multiplyToRef(transform, matrix);
  3478. matrix.invert();
  3479. source.x = source.x / viewportWidth * 2 - 1;
  3480. source.y = -(source.y / viewportHeight * 2 - 1);
  3481. var vector = Vector3.TransformCoordinates(source, matrix);
  3482. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3483. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3484. vector = vector.scale(1.0 / num);
  3485. }
  3486. return vector;
  3487. };
  3488. /**
  3489. * Unproject from screen space to object space
  3490. * @param source defines the screen space Vector3 to use
  3491. * @param viewportWidth defines the current width of the viewport
  3492. * @param viewportHeight defines the current height of the viewport
  3493. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3494. * @param view defines the view matrix to use
  3495. * @param projection defines the projection matrix to use
  3496. * @returns the new Vector3
  3497. */
  3498. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3499. var result = Vector3.Zero();
  3500. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3501. return result;
  3502. };
  3503. /**
  3504. * Unproject from screen space to object space
  3505. * @param source defines the screen space Vector3 to use
  3506. * @param viewportWidth defines the current width of the viewport
  3507. * @param viewportHeight defines the current height of the viewport
  3508. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3509. * @param view defines the view matrix to use
  3510. * @param projection defines the projection matrix to use
  3511. * @param result defines the Vector3 where to store the result
  3512. */
  3513. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3514. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3515. };
  3516. /**
  3517. * Unproject from screen space to object space
  3518. * @param sourceX defines the screen space x coordinate to use
  3519. * @param sourceY defines the screen space y coordinate to use
  3520. * @param sourceZ defines the screen space z coordinate to use
  3521. * @param viewportWidth defines the current width of the viewport
  3522. * @param viewportHeight defines the current height of the viewport
  3523. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3524. * @param view defines the view matrix to use
  3525. * @param projection defines the projection matrix to use
  3526. * @param result defines the Vector3 where to store the result
  3527. */
  3528. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3529. var matrix = MathTmp.Matrix[0];
  3530. world.multiplyToRef(view, matrix);
  3531. matrix.multiplyToRef(projection, matrix);
  3532. matrix.invert();
  3533. var screenSource = MathTmp.Vector3[0];
  3534. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3535. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3536. screenSource.z = 2 * sourceZ - 1.0;
  3537. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3538. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3539. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3540. result.scaleInPlace(1.0 / num);
  3541. }
  3542. };
  3543. /**
  3544. * Gets the minimal coordinate values between two Vector3
  3545. * @param left defines the first operand
  3546. * @param right defines the second operand
  3547. * @returns the new Vector3
  3548. */
  3549. Vector3.Minimize = function (left, right) {
  3550. var min = left.clone();
  3551. min.minimizeInPlace(right);
  3552. return min;
  3553. };
  3554. /**
  3555. * Gets the maximal coordinate values between two Vector3
  3556. * @param left defines the first operand
  3557. * @param right defines the second operand
  3558. * @returns the new Vector3
  3559. */
  3560. Vector3.Maximize = function (left, right) {
  3561. var max = left.clone();
  3562. max.maximizeInPlace(right);
  3563. return max;
  3564. };
  3565. /**
  3566. * Returns the distance between the vectors "value1" and "value2"
  3567. * @param value1 defines the first operand
  3568. * @param value2 defines the second operand
  3569. * @returns the distance
  3570. */
  3571. Vector3.Distance = function (value1, value2) {
  3572. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3573. };
  3574. /**
  3575. * Returns the squared distance between the vectors "value1" and "value2"
  3576. * @param value1 defines the first operand
  3577. * @param value2 defines the second operand
  3578. * @returns the squared distance
  3579. */
  3580. Vector3.DistanceSquared = function (value1, value2) {
  3581. var x = value1.x - value2.x;
  3582. var y = value1.y - value2.y;
  3583. var z = value1.z - value2.z;
  3584. return (x * x) + (y * y) + (z * z);
  3585. };
  3586. /**
  3587. * Returns a new Vector3 located at the center between "value1" and "value2"
  3588. * @param value1 defines the first operand
  3589. * @param value2 defines the second operand
  3590. * @returns the new Vector3
  3591. */
  3592. Vector3.Center = function (value1, value2) {
  3593. var center = value1.add(value2);
  3594. center.scaleInPlace(0.5);
  3595. return center;
  3596. };
  3597. /**
  3598. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3599. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3600. * to something in order to rotate it from its local system to the given target system
  3601. * Note: axis1, axis2 and axis3 are normalized during this operation
  3602. * @param axis1 defines the first axis
  3603. * @param axis2 defines the second axis
  3604. * @param axis3 defines the third axis
  3605. * @returns a new Vector3
  3606. */
  3607. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3608. var rotation = Vector3.Zero();
  3609. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3610. return rotation;
  3611. };
  3612. /**
  3613. * The same than RotationFromAxis but updates the passed ref Vector3 parameter instead of returning a new Vector3
  3614. * @param axis1 defines the first axis
  3615. * @param axis2 defines the second axis
  3616. * @param axis3 defines the third axis
  3617. * @param ref defines the Vector3 where to store the result
  3618. */
  3619. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3620. var quat = MathTmp.Quaternion[0];
  3621. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3622. quat.toEulerAnglesToRef(ref);
  3623. };
  3624. return Vector3;
  3625. }());
  3626. BABYLON.Vector3 = Vector3;
  3627. //Vector4 class created for EulerAngle class conversion to Quaternion
  3628. var Vector4 = /** @class */ (function () {
  3629. /**
  3630. * Creates a Vector4 object from the passed floats.
  3631. */
  3632. function Vector4(x, y, z, w) {
  3633. this.x = x;
  3634. this.y = y;
  3635. this.z = z;
  3636. this.w = w;
  3637. }
  3638. /**
  3639. * Returns the string with the Vector4 coordinates.
  3640. */
  3641. Vector4.prototype.toString = function () {
  3642. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3643. };
  3644. /**
  3645. * Returns the string "Vector4".
  3646. */
  3647. Vector4.prototype.getClassName = function () {
  3648. return "Vector4";
  3649. };
  3650. /**
  3651. * Returns the Vector4 hash code.
  3652. */
  3653. Vector4.prototype.getHashCode = function () {
  3654. var hash = this.x || 0;
  3655. hash = (hash * 397) ^ (this.y || 0);
  3656. hash = (hash * 397) ^ (this.z || 0);
  3657. hash = (hash * 397) ^ (this.w || 0);
  3658. return hash;
  3659. };
  3660. // Operators
  3661. /**
  3662. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3663. */
  3664. Vector4.prototype.asArray = function () {
  3665. var result = new Array();
  3666. this.toArray(result, 0);
  3667. return result;
  3668. };
  3669. /**
  3670. * Populates the passed array from the passed index with the Vector4 coordinates.
  3671. * Returns the Vector4.
  3672. */
  3673. Vector4.prototype.toArray = function (array, index) {
  3674. if (index === undefined) {
  3675. index = 0;
  3676. }
  3677. array[index] = this.x;
  3678. array[index + 1] = this.y;
  3679. array[index + 2] = this.z;
  3680. array[index + 3] = this.w;
  3681. return this;
  3682. };
  3683. /**
  3684. * Adds the passed vector to the current Vector4.
  3685. * Returns the updated Vector4.
  3686. */
  3687. Vector4.prototype.addInPlace = function (otherVector) {
  3688. this.x += otherVector.x;
  3689. this.y += otherVector.y;
  3690. this.z += otherVector.z;
  3691. this.w += otherVector.w;
  3692. return this;
  3693. };
  3694. /**
  3695. * Returns a new Vector4 as the result of the addition of the current Vector4 and the passed one.
  3696. */
  3697. Vector4.prototype.add = function (otherVector) {
  3698. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3699. };
  3700. /**
  3701. * Updates the passed vector "result" with the result of the addition of the current Vector4 and the passed one.
  3702. * Returns the current Vector4.
  3703. */
  3704. Vector4.prototype.addToRef = function (otherVector, result) {
  3705. result.x = this.x + otherVector.x;
  3706. result.y = this.y + otherVector.y;
  3707. result.z = this.z + otherVector.z;
  3708. result.w = this.w + otherVector.w;
  3709. return this;
  3710. };
  3711. /**
  3712. * Subtract in place the passed vector from the current Vector4.
  3713. * Returns the updated Vector4.
  3714. */
  3715. Vector4.prototype.subtractInPlace = function (otherVector) {
  3716. this.x -= otherVector.x;
  3717. this.y -= otherVector.y;
  3718. this.z -= otherVector.z;
  3719. this.w -= otherVector.w;
  3720. return this;
  3721. };
  3722. /**
  3723. * Returns a new Vector4 with the result of the subtraction of the passed vector from the current Vector4.
  3724. */
  3725. Vector4.prototype.subtract = function (otherVector) {
  3726. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3727. };
  3728. /**
  3729. * Sets the passed vector "result" with the result of the subtraction of the passed vector from the current Vector4.
  3730. * Returns the current Vector4.
  3731. */
  3732. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3733. result.x = this.x - otherVector.x;
  3734. result.y = this.y - otherVector.y;
  3735. result.z = this.z - otherVector.z;
  3736. result.w = this.w - otherVector.w;
  3737. return this;
  3738. };
  3739. /**
  3740. * Returns a new Vector4 set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  3741. */
  3742. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3743. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3744. };
  3745. /**
  3746. * Sets the passed vector "result" set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  3747. * Returns the current Vector4.
  3748. */
  3749. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3750. result.x = this.x - x;
  3751. result.y = this.y - y;
  3752. result.z = this.z - z;
  3753. result.w = this.w - w;
  3754. return this;
  3755. };
  3756. /**
  3757. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3758. */
  3759. Vector4.prototype.negate = function () {
  3760. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3761. };
  3762. /**
  3763. * Multiplies the current Vector4 coordinates by scale (float).
  3764. * Returns the updated Vector4.
  3765. */
  3766. Vector4.prototype.scaleInPlace = function (scale) {
  3767. this.x *= scale;
  3768. this.y *= scale;
  3769. this.z *= scale;
  3770. this.w *= scale;
  3771. return this;
  3772. };
  3773. /**
  3774. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  3775. */
  3776. Vector4.prototype.scale = function (scale) {
  3777. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  3778. };
  3779. /**
  3780. * Sets the passed vector "result" with the current Vector4 coordinates multiplied by scale (float).
  3781. * Returns the current Vector4.
  3782. */
  3783. Vector4.prototype.scaleToRef = function (scale, result) {
  3784. result.x = this.x * scale;
  3785. result.y = this.y * scale;
  3786. result.z = this.z * scale;
  3787. result.w = this.w * scale;
  3788. return this;
  3789. };
  3790. /**
  3791. * Boolean : True if the current Vector4 coordinates are stricly equal to the passed ones.
  3792. */
  3793. Vector4.prototype.equals = function (otherVector) {
  3794. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  3795. };
  3796. /**
  3797. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the passed vector ones.
  3798. */
  3799. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3800. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3801. return otherVector
  3802. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  3803. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  3804. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  3805. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  3806. };
  3807. /**
  3808. * Boolean : True if the passed floats are strictly equal to the current Vector4 coordinates.
  3809. */
  3810. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  3811. return this.x === x && this.y === y && this.z === z && this.w === w;
  3812. };
  3813. /**
  3814. * Multiplies in place the current Vector4 by the passed one.
  3815. * Returns the updated Vector4.
  3816. */
  3817. Vector4.prototype.multiplyInPlace = function (otherVector) {
  3818. this.x *= otherVector.x;
  3819. this.y *= otherVector.y;
  3820. this.z *= otherVector.z;
  3821. this.w *= otherVector.w;
  3822. return this;
  3823. };
  3824. /**
  3825. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the passed one.
  3826. */
  3827. Vector4.prototype.multiply = function (otherVector) {
  3828. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  3829. };
  3830. /**
  3831. * Updates the passed vector "result" with the multiplication result of the current Vector4 and the passed one.
  3832. * Returns the current Vector4.
  3833. */
  3834. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  3835. result.x = this.x * otherVector.x;
  3836. result.y = this.y * otherVector.y;
  3837. result.z = this.z * otherVector.z;
  3838. result.w = this.w * otherVector.w;
  3839. return this;
  3840. };
  3841. /**
  3842. * Returns a new Vector4 set with the multiplication result of the passed floats and the current Vector4 coordinates.
  3843. */
  3844. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  3845. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  3846. };
  3847. /**
  3848. * Returns a new Vector4 set with the division result of the current Vector4 by the passed one.
  3849. */
  3850. Vector4.prototype.divide = function (otherVector) {
  3851. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  3852. };
  3853. /**
  3854. * Updates the passed vector "result" with the division result of the current Vector4 by the passed one.
  3855. * Returns the current Vector4.
  3856. */
  3857. Vector4.prototype.divideToRef = function (otherVector, result) {
  3858. result.x = this.x / otherVector.x;
  3859. result.y = this.y / otherVector.y;
  3860. result.z = this.z / otherVector.z;
  3861. result.w = this.w / otherVector.w;
  3862. return this;
  3863. };
  3864. /**
  3865. * Divides the current Vector3 coordinates by the passed ones.
  3866. * @returns the updated Vector3.
  3867. */
  3868. Vector4.prototype.divideInPlace = function (otherVector) {
  3869. return this.divideToRef(otherVector, this);
  3870. };
  3871. /**
  3872. * Updates the Vector4 coordinates with the minimum values between its own and the passed vector ones
  3873. * @param other defines the second operand
  3874. * @returns the current updated Vector4
  3875. */
  3876. Vector4.prototype.minimizeInPlace = function (other) {
  3877. if (other.x < this.x)
  3878. this.x = other.x;
  3879. if (other.y < this.y)
  3880. this.y = other.y;
  3881. if (other.z < this.z)
  3882. this.z = other.z;
  3883. if (other.w < this.w)
  3884. this.w = other.w;
  3885. return this;
  3886. };
  3887. /**
  3888. * Updates the Vector4 coordinates with the maximum values between its own and the passed vector ones
  3889. * @param other defines the second operand
  3890. * @returns the current updated Vector4
  3891. */
  3892. Vector4.prototype.maximizeInPlace = function (other) {
  3893. if (other.x > this.x)
  3894. this.x = other.x;
  3895. if (other.y > this.y)
  3896. this.y = other.y;
  3897. if (other.z > this.z)
  3898. this.z = other.z;
  3899. if (other.w > this.w)
  3900. this.w = other.w;
  3901. return this;
  3902. };
  3903. // Properties
  3904. /**
  3905. * Returns the Vector4 length (float).
  3906. */
  3907. Vector4.prototype.length = function () {
  3908. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  3909. };
  3910. /**
  3911. * Returns the Vector4 squared length (float).
  3912. */
  3913. Vector4.prototype.lengthSquared = function () {
  3914. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  3915. };
  3916. // Methods
  3917. /**
  3918. * Normalizes in place the Vector4.
  3919. * Returns the updated Vector4.
  3920. */
  3921. Vector4.prototype.normalize = function () {
  3922. var len = this.length();
  3923. if (len === 0)
  3924. return this;
  3925. var num = 1.0 / len;
  3926. this.x *= num;
  3927. this.y *= num;
  3928. this.z *= num;
  3929. this.w *= num;
  3930. return this;
  3931. };
  3932. /**
  3933. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  3934. */
  3935. Vector4.prototype.toVector3 = function () {
  3936. return new Vector3(this.x, this.y, this.z);
  3937. };
  3938. /**
  3939. * Returns a new Vector4 copied from the current one.
  3940. */
  3941. Vector4.prototype.clone = function () {
  3942. return new Vector4(this.x, this.y, this.z, this.w);
  3943. };
  3944. /**
  3945. * Updates the current Vector4 with the passed one coordinates.
  3946. * Returns the updated Vector4.
  3947. */
  3948. Vector4.prototype.copyFrom = function (source) {
  3949. this.x = source.x;
  3950. this.y = source.y;
  3951. this.z = source.z;
  3952. this.w = source.w;
  3953. return this;
  3954. };
  3955. /**
  3956. * Updates the current Vector4 coordinates with the passed floats.
  3957. * Returns the updated Vector4.
  3958. */
  3959. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  3960. this.x = x;
  3961. this.y = y;
  3962. this.z = z;
  3963. this.w = w;
  3964. return this;
  3965. };
  3966. /**
  3967. * Updates the current Vector4 coordinates with the passed floats.
  3968. * Returns the updated Vector4.
  3969. */
  3970. Vector4.prototype.set = function (x, y, z, w) {
  3971. return this.copyFromFloats(x, y, z, w);
  3972. };
  3973. // Statics
  3974. /**
  3975. * Returns a new Vector4 set from the starting index of the passed array.
  3976. */
  3977. Vector4.FromArray = function (array, offset) {
  3978. if (!offset) {
  3979. offset = 0;
  3980. }
  3981. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  3982. };
  3983. /**
  3984. * Updates the passed vector "result" from the starting index of the passed array.
  3985. */
  3986. Vector4.FromArrayToRef = function (array, offset, result) {
  3987. result.x = array[offset];
  3988. result.y = array[offset + 1];
  3989. result.z = array[offset + 2];
  3990. result.w = array[offset + 3];
  3991. };
  3992. /**
  3993. * Updates the passed vector "result" from the starting index of the passed Float32Array.
  3994. */
  3995. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  3996. Vector4.FromArrayToRef(array, offset, result);
  3997. };
  3998. /**
  3999. * Updates the passed vector "result" coordinates from the passed floats.
  4000. */
  4001. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  4002. result.x = x;
  4003. result.y = y;
  4004. result.z = z;
  4005. result.w = w;
  4006. };
  4007. /**
  4008. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  4009. */
  4010. Vector4.Zero = function () {
  4011. return new Vector4(0.0, 0.0, 0.0, 0.0);
  4012. };
  4013. /**
  4014. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  4015. */
  4016. Vector4.One = function () {
  4017. return new Vector4(1.0, 1.0, 1.0, 1.0);
  4018. };
  4019. /**
  4020. * Returns a new normalized Vector4 from the passed one.
  4021. */
  4022. Vector4.Normalize = function (vector) {
  4023. var result = Vector4.Zero();
  4024. Vector4.NormalizeToRef(vector, result);
  4025. return result;
  4026. };
  4027. /**
  4028. * Updates the passed vector "result" from the normalization of the passed one.
  4029. */
  4030. Vector4.NormalizeToRef = function (vector, result) {
  4031. result.copyFrom(vector);
  4032. result.normalize();
  4033. };
  4034. Vector4.Minimize = function (left, right) {
  4035. var min = left.clone();
  4036. min.minimizeInPlace(right);
  4037. return min;
  4038. };
  4039. Vector4.Maximize = function (left, right) {
  4040. var max = left.clone();
  4041. max.maximizeInPlace(right);
  4042. return max;
  4043. };
  4044. /**
  4045. * Returns the distance (float) between the vectors "value1" and "value2".
  4046. */
  4047. Vector4.Distance = function (value1, value2) {
  4048. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  4049. };
  4050. /**
  4051. * Returns the squared distance (float) between the vectors "value1" and "value2".
  4052. */
  4053. Vector4.DistanceSquared = function (value1, value2) {
  4054. var x = value1.x - value2.x;
  4055. var y = value1.y - value2.y;
  4056. var z = value1.z - value2.z;
  4057. var w = value1.w - value2.w;
  4058. return (x * x) + (y * y) + (z * z) + (w * w);
  4059. };
  4060. /**
  4061. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  4062. */
  4063. Vector4.Center = function (value1, value2) {
  4064. var center = value1.add(value2);
  4065. center.scaleInPlace(0.5);
  4066. return center;
  4067. };
  4068. /**
  4069. * Returns a new Vector4 set with the result of the normal transformation by the passed matrix of the passed vector.
  4070. * This methods computes transformed normalized direction vectors only.
  4071. */
  4072. Vector4.TransformNormal = function (vector, transformation) {
  4073. var result = Vector4.Zero();
  4074. Vector4.TransformNormalToRef(vector, transformation, result);
  4075. return result;
  4076. };
  4077. /**
  4078. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  4079. * This methods computes transformed normalized direction vectors only.
  4080. */
  4081. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  4082. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4083. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4084. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4085. result.x = x;
  4086. result.y = y;
  4087. result.z = z;
  4088. result.w = vector.w;
  4089. };
  4090. /**
  4091. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z, w).
  4092. * This methods computes transformed normalized direction vectors only.
  4093. */
  4094. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4095. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4096. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4097. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4098. result.w = w;
  4099. };
  4100. return Vector4;
  4101. }());
  4102. BABYLON.Vector4 = Vector4;
  4103. var Size = /** @class */ (function () {
  4104. /**
  4105. * Creates a Size object from the passed width and height (floats).
  4106. */
  4107. function Size(width, height) {
  4108. this.width = width;
  4109. this.height = height;
  4110. }
  4111. // Returns a string with the Size width and height.
  4112. Size.prototype.toString = function () {
  4113. return "{W: " + this.width + ", H: " + this.height + "}";
  4114. };
  4115. /**
  4116. * Returns the string "Size"
  4117. */
  4118. Size.prototype.getClassName = function () {
  4119. return "Size";
  4120. };
  4121. /**
  4122. * Returns the Size hash code.
  4123. */
  4124. Size.prototype.getHashCode = function () {
  4125. var hash = this.width || 0;
  4126. hash = (hash * 397) ^ (this.height || 0);
  4127. return hash;
  4128. };
  4129. /**
  4130. * Updates the current size from the passed one.
  4131. * Returns the updated Size.
  4132. */
  4133. Size.prototype.copyFrom = function (src) {
  4134. this.width = src.width;
  4135. this.height = src.height;
  4136. };
  4137. /**
  4138. * Updates in place the current Size from the passed floats.
  4139. * Returns the updated Size.
  4140. */
  4141. Size.prototype.copyFromFloats = function (width, height) {
  4142. this.width = width;
  4143. this.height = height;
  4144. return this;
  4145. };
  4146. /**
  4147. * Updates in place the current Size from the passed floats.
  4148. * Returns the updated Size.
  4149. */
  4150. Size.prototype.set = function (width, height) {
  4151. return this.copyFromFloats(width, height);
  4152. };
  4153. /**
  4154. * Returns a new Size set with the multiplication result of the current Size and the passed floats.
  4155. */
  4156. Size.prototype.multiplyByFloats = function (w, h) {
  4157. return new Size(this.width * w, this.height * h);
  4158. };
  4159. /**
  4160. * Returns a new Size copied from the passed one.
  4161. */
  4162. Size.prototype.clone = function () {
  4163. return new Size(this.width, this.height);
  4164. };
  4165. /**
  4166. * Boolean : True if the current Size and the passed one width and height are strictly equal.
  4167. */
  4168. Size.prototype.equals = function (other) {
  4169. if (!other) {
  4170. return false;
  4171. }
  4172. return (this.width === other.width) && (this.height === other.height);
  4173. };
  4174. Object.defineProperty(Size.prototype, "surface", {
  4175. /**
  4176. * Returns the surface of the Size : width * height (float).
  4177. */
  4178. get: function () {
  4179. return this.width * this.height;
  4180. },
  4181. enumerable: true,
  4182. configurable: true
  4183. });
  4184. /**
  4185. * Returns a new Size set to (0.0, 0.0)
  4186. */
  4187. Size.Zero = function () {
  4188. return new Size(0.0, 0.0);
  4189. };
  4190. /**
  4191. * Returns a new Size set as the addition result of the current Size and the passed one.
  4192. */
  4193. Size.prototype.add = function (otherSize) {
  4194. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4195. return r;
  4196. };
  4197. /**
  4198. * Returns a new Size set as the subtraction result of the passed one from the current Size.
  4199. */
  4200. Size.prototype.subtract = function (otherSize) {
  4201. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4202. return r;
  4203. };
  4204. /**
  4205. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  4206. */
  4207. Size.Lerp = function (start, end, amount) {
  4208. var w = start.width + ((end.width - start.width) * amount);
  4209. var h = start.height + ((end.height - start.height) * amount);
  4210. return new Size(w, h);
  4211. };
  4212. return Size;
  4213. }());
  4214. BABYLON.Size = Size;
  4215. var Quaternion = /** @class */ (function () {
  4216. /**
  4217. * Creates a new Quaternion from the passed floats.
  4218. */
  4219. function Quaternion(x, y, z, w) {
  4220. if (x === void 0) { x = 0.0; }
  4221. if (y === void 0) { y = 0.0; }
  4222. if (z === void 0) { z = 0.0; }
  4223. if (w === void 0) { w = 1.0; }
  4224. this.x = x;
  4225. this.y = y;
  4226. this.z = z;
  4227. this.w = w;
  4228. }
  4229. /**
  4230. * Returns a string with the Quaternion coordinates.
  4231. */
  4232. Quaternion.prototype.toString = function () {
  4233. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4234. };
  4235. /**
  4236. * Returns the string "Quaternion".
  4237. */
  4238. Quaternion.prototype.getClassName = function () {
  4239. return "Quaternion";
  4240. };
  4241. /**
  4242. * Returns the Quaternion hash code.
  4243. */
  4244. Quaternion.prototype.getHashCode = function () {
  4245. var hash = this.x || 0;
  4246. hash = (hash * 397) ^ (this.y || 0);
  4247. hash = (hash * 397) ^ (this.z || 0);
  4248. hash = (hash * 397) ^ (this.w || 0);
  4249. return hash;
  4250. };
  4251. /**
  4252. * Returns a new array populated with 4 elements : the Quaternion coordinates.
  4253. */
  4254. Quaternion.prototype.asArray = function () {
  4255. return [this.x, this.y, this.z, this.w];
  4256. };
  4257. /**
  4258. * Boolean : True if the current Quaterion and the passed one coordinates are strictly equal.
  4259. */
  4260. Quaternion.prototype.equals = function (otherQuaternion) {
  4261. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4262. };
  4263. /**
  4264. * Returns a new Quaternion copied from the current one.
  4265. */
  4266. Quaternion.prototype.clone = function () {
  4267. return new Quaternion(this.x, this.y, this.z, this.w);
  4268. };
  4269. /**
  4270. * Updates the current Quaternion from the passed one coordinates.
  4271. * Returns the updated Quaterion.
  4272. */
  4273. Quaternion.prototype.copyFrom = function (other) {
  4274. this.x = other.x;
  4275. this.y = other.y;
  4276. this.z = other.z;
  4277. this.w = other.w;
  4278. return this;
  4279. };
  4280. /**
  4281. * Updates the current Quaternion from the passed float coordinates.
  4282. * Returns the updated Quaterion.
  4283. */
  4284. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4285. this.x = x;
  4286. this.y = y;
  4287. this.z = z;
  4288. this.w = w;
  4289. return this;
  4290. };
  4291. /**
  4292. * Updates the current Quaternion from the passed float coordinates.
  4293. * Returns the updated Quaterion.
  4294. */
  4295. Quaternion.prototype.set = function (x, y, z, w) {
  4296. return this.copyFromFloats(x, y, z, w);
  4297. };
  4298. /**
  4299. * Returns a new Quaternion as the addition result of the passed one and the current Quaternion.
  4300. */
  4301. Quaternion.prototype.add = function (other) {
  4302. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4303. };
  4304. /**
  4305. * Returns a new Quaternion as the subtraction result of the passed one from the current Quaternion.
  4306. */
  4307. Quaternion.prototype.subtract = function (other) {
  4308. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4309. };
  4310. /**
  4311. * Returns a new Quaternion set by multiplying the current Quaterion coordinates by the float "scale".
  4312. */
  4313. Quaternion.prototype.scale = function (value) {
  4314. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4315. };
  4316. /**
  4317. * Returns a new Quaternion set as the quaternion mulplication result of the current one with the passed one "q1".
  4318. */
  4319. Quaternion.prototype.multiply = function (q1) {
  4320. var result = new Quaternion(0, 0, 0, 1.0);
  4321. this.multiplyToRef(q1, result);
  4322. return result;
  4323. };
  4324. /**
  4325. * Sets the passed "result" as the quaternion mulplication result of the current one with the passed one "q1".
  4326. * Returns the current Quaternion.
  4327. */
  4328. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4329. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4330. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4331. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4332. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4333. result.copyFromFloats(x, y, z, w);
  4334. return this;
  4335. };
  4336. /**
  4337. * Updates the current Quaternion with the quaternion mulplication result of itself with the passed one "q1".
  4338. * Returns the updated Quaternion.
  4339. */
  4340. Quaternion.prototype.multiplyInPlace = function (q1) {
  4341. this.multiplyToRef(q1, this);
  4342. return this;
  4343. };
  4344. /**
  4345. * Sets the passed "ref" with the conjugation of the current Quaternion.
  4346. * Returns the current Quaternion.
  4347. */
  4348. Quaternion.prototype.conjugateToRef = function (ref) {
  4349. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4350. return this;
  4351. };
  4352. /**
  4353. * Conjugates in place the current Quaternion.
  4354. * Returns the updated Quaternion.
  4355. */
  4356. Quaternion.prototype.conjugateInPlace = function () {
  4357. this.x *= -1;
  4358. this.y *= -1;
  4359. this.z *= -1;
  4360. return this;
  4361. };
  4362. /**
  4363. * Returns a new Quaternion as the conjugate of the current Quaternion.
  4364. */
  4365. Quaternion.prototype.conjugate = function () {
  4366. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4367. return result;
  4368. };
  4369. /**
  4370. * Returns the Quaternion length (float).
  4371. */
  4372. Quaternion.prototype.length = function () {
  4373. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4374. };
  4375. /**
  4376. * Normalize in place the current Quaternion.
  4377. * Returns the updated Quaternion.
  4378. */
  4379. Quaternion.prototype.normalize = function () {
  4380. var length = 1.0 / this.length();
  4381. this.x *= length;
  4382. this.y *= length;
  4383. this.z *= length;
  4384. this.w *= length;
  4385. return this;
  4386. };
  4387. /**
  4388. * Returns a new Vector3 set with the Euler angles translated from the current Quaternion.
  4389. */
  4390. Quaternion.prototype.toEulerAngles = function (order) {
  4391. if (order === void 0) { order = "YZX"; }
  4392. var result = Vector3.Zero();
  4393. this.toEulerAnglesToRef(result, order);
  4394. return result;
  4395. };
  4396. /**
  4397. * Sets the passed vector3 "result" with the Euler angles translated from the current Quaternion.
  4398. * Returns the current Quaternion.
  4399. */
  4400. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4401. if (order === void 0) { order = "YZX"; }
  4402. var qz = this.z;
  4403. var qx = this.x;
  4404. var qy = this.y;
  4405. var qw = this.w;
  4406. var sqw = qw * qw;
  4407. var sqz = qz * qz;
  4408. var sqx = qx * qx;
  4409. var sqy = qy * qy;
  4410. var zAxisY = qy * qz - qx * qw;
  4411. var limit = .4999999;
  4412. if (zAxisY < -limit) {
  4413. result.y = 2 * Math.atan2(qy, qw);
  4414. result.x = Math.PI / 2;
  4415. result.z = 0;
  4416. }
  4417. else if (zAxisY > limit) {
  4418. result.y = 2 * Math.atan2(qy, qw);
  4419. result.x = -Math.PI / 2;
  4420. result.z = 0;
  4421. }
  4422. else {
  4423. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4424. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4425. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4426. }
  4427. return this;
  4428. };
  4429. /**
  4430. * Updates the passed rotation matrix with the current Quaternion values.
  4431. * Returns the current Quaternion.
  4432. */
  4433. Quaternion.prototype.toRotationMatrix = function (result) {
  4434. var xx = this.x * this.x;
  4435. var yy = this.y * this.y;
  4436. var zz = this.z * this.z;
  4437. var xy = this.x * this.y;
  4438. var zw = this.z * this.w;
  4439. var zx = this.z * this.x;
  4440. var yw = this.y * this.w;
  4441. var yz = this.y * this.z;
  4442. var xw = this.x * this.w;
  4443. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4444. result.m[1] = 2.0 * (xy + zw);
  4445. result.m[2] = 2.0 * (zx - yw);
  4446. result.m[3] = 0;
  4447. result.m[4] = 2.0 * (xy - zw);
  4448. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4449. result.m[6] = 2.0 * (yz + xw);
  4450. result.m[7] = 0;
  4451. result.m[8] = 2.0 * (zx + yw);
  4452. result.m[9] = 2.0 * (yz - xw);
  4453. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4454. result.m[11] = 0;
  4455. result.m[12] = 0;
  4456. result.m[13] = 0;
  4457. result.m[14] = 0;
  4458. result.m[15] = 1.0;
  4459. result._markAsUpdated();
  4460. return this;
  4461. };
  4462. /**
  4463. * Updates the current Quaternion from the passed rotation matrix values.
  4464. * Returns the updated Quaternion.
  4465. */
  4466. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  4467. Quaternion.FromRotationMatrixToRef(matrix, this);
  4468. return this;
  4469. };
  4470. // Statics
  4471. /**
  4472. * Returns a new Quaternion set from the passed rotation matrix values.
  4473. */
  4474. Quaternion.FromRotationMatrix = function (matrix) {
  4475. var result = new Quaternion();
  4476. Quaternion.FromRotationMatrixToRef(matrix, result);
  4477. return result;
  4478. };
  4479. /**
  4480. * Updates the passed quaternion "result" with the passed rotation matrix values.
  4481. */
  4482. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  4483. var data = matrix.m;
  4484. var m11 = data[0], m12 = data[4], m13 = data[8];
  4485. var m21 = data[1], m22 = data[5], m23 = data[9];
  4486. var m31 = data[2], m32 = data[6], m33 = data[10];
  4487. var trace = m11 + m22 + m33;
  4488. var s;
  4489. if (trace > 0) {
  4490. s = 0.5 / Math.sqrt(trace + 1.0);
  4491. result.w = 0.25 / s;
  4492. result.x = (m32 - m23) * s;
  4493. result.y = (m13 - m31) * s;
  4494. result.z = (m21 - m12) * s;
  4495. }
  4496. else if (m11 > m22 && m11 > m33) {
  4497. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  4498. result.w = (m32 - m23) / s;
  4499. result.x = 0.25 * s;
  4500. result.y = (m12 + m21) / s;
  4501. result.z = (m13 + m31) / s;
  4502. }
  4503. else if (m22 > m33) {
  4504. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  4505. result.w = (m13 - m31) / s;
  4506. result.x = (m12 + m21) / s;
  4507. result.y = 0.25 * s;
  4508. result.z = (m23 + m32) / s;
  4509. }
  4510. else {
  4511. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  4512. result.w = (m21 - m12) / s;
  4513. result.x = (m13 + m31) / s;
  4514. result.y = (m23 + m32) / s;
  4515. result.z = 0.25 * s;
  4516. }
  4517. };
  4518. /**
  4519. * Returns a new Quaternion set to (0.0, 0.0, 0.0).
  4520. */
  4521. Quaternion.Zero = function () {
  4522. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  4523. };
  4524. /**
  4525. * Returns a new Quaternion as the inverted current Quaternion.
  4526. */
  4527. Quaternion.Inverse = function (q) {
  4528. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  4529. };
  4530. /**
  4531. * Returns the identity Quaternion.
  4532. */
  4533. Quaternion.Identity = function () {
  4534. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  4535. };
  4536. Quaternion.IsIdentity = function (quaternion) {
  4537. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  4538. };
  4539. /**
  4540. * Returns a new Quaternion set from the passed axis (Vector3) and angle in radians (float).
  4541. */
  4542. Quaternion.RotationAxis = function (axis, angle) {
  4543. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  4544. };
  4545. /**
  4546. * Sets the passed quaternion "result" from the passed axis (Vector3) and angle in radians (float).
  4547. */
  4548. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  4549. var sin = Math.sin(angle / 2);
  4550. axis.normalize();
  4551. result.w = Math.cos(angle / 2);
  4552. result.x = axis.x * sin;
  4553. result.y = axis.y * sin;
  4554. result.z = axis.z * sin;
  4555. return result;
  4556. };
  4557. /**
  4558. * Retuns a new Quaternion set from the starting index of the passed array.
  4559. */
  4560. Quaternion.FromArray = function (array, offset) {
  4561. if (!offset) {
  4562. offset = 0;
  4563. }
  4564. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4565. };
  4566. /**
  4567. * Returns a new Quaternion set from the passed Euler float angles (y, x, z).
  4568. */
  4569. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4570. var q = new Quaternion();
  4571. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  4572. return q;
  4573. };
  4574. /**
  4575. * Sets the passed quaternion "result" from the passed float Euler angles (y, x, z).
  4576. */
  4577. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4578. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  4579. var halfRoll = roll * 0.5;
  4580. var halfPitch = pitch * 0.5;
  4581. var halfYaw = yaw * 0.5;
  4582. var sinRoll = Math.sin(halfRoll);
  4583. var cosRoll = Math.cos(halfRoll);
  4584. var sinPitch = Math.sin(halfPitch);
  4585. var cosPitch = Math.cos(halfPitch);
  4586. var sinYaw = Math.sin(halfYaw);
  4587. var cosYaw = Math.cos(halfYaw);
  4588. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  4589. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  4590. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  4591. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  4592. };
  4593. /**
  4594. * Returns a new Quaternion from the passed float Euler angles expressed in z-x-z orientation
  4595. */
  4596. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  4597. var result = new Quaternion();
  4598. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  4599. return result;
  4600. };
  4601. /**
  4602. * Sets the passed quaternion "result" from the passed float Euler angles expressed in z-x-z orientation
  4603. */
  4604. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  4605. // Produces a quaternion from Euler angles in the z-x-z orientation
  4606. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  4607. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  4608. var halfBeta = beta * 0.5;
  4609. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4610. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4611. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4612. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4613. };
  4614. /**
  4615. * Returns a new Quaternion as the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  4616. * cf to Vector3.RotationFromAxis() documentation.
  4617. * Note : axis1, axis2 and axis3 are normalized during this operation.
  4618. */
  4619. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3, ref) {
  4620. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  4621. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  4622. return quat;
  4623. };
  4624. /**
  4625. * Sets the passed quaternion "ref" with the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  4626. * cf to Vector3.RotationFromAxis() documentation.
  4627. * Note : axis1, axis2 and axis3 are normalized during this operation.
  4628. */
  4629. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  4630. var rotMat = MathTmp.Matrix[0];
  4631. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  4632. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  4633. };
  4634. Quaternion.Slerp = function (left, right, amount) {
  4635. var result = Quaternion.Identity();
  4636. Quaternion.SlerpToRef(left, right, amount, result);
  4637. return result;
  4638. };
  4639. Quaternion.SlerpToRef = function (left, right, amount, result) {
  4640. var num2;
  4641. var num3;
  4642. var num = amount;
  4643. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  4644. var flag = false;
  4645. if (num4 < 0) {
  4646. flag = true;
  4647. num4 = -num4;
  4648. }
  4649. if (num4 > 0.999999) {
  4650. num3 = 1 - num;
  4651. num2 = flag ? -num : num;
  4652. }
  4653. else {
  4654. var num5 = Math.acos(num4);
  4655. var num6 = (1.0 / Math.sin(num5));
  4656. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  4657. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  4658. }
  4659. result.x = (num3 * left.x) + (num2 * right.x);
  4660. result.y = (num3 * left.y) + (num2 * right.y);
  4661. result.z = (num3 * left.z) + (num2 * right.z);
  4662. result.w = (num3 * left.w) + (num2 * right.w);
  4663. };
  4664. /**
  4665. * Returns a new Quaternion located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  4666. */
  4667. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  4668. var squared = amount * amount;
  4669. var cubed = amount * squared;
  4670. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  4671. var part2 = (-2.0 * cubed) + (3.0 * squared);
  4672. var part3 = (cubed - (2.0 * squared)) + amount;
  4673. var part4 = cubed - squared;
  4674. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  4675. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  4676. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  4677. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  4678. return new Quaternion(x, y, z, w);
  4679. };
  4680. return Quaternion;
  4681. }());
  4682. BABYLON.Quaternion = Quaternion;
  4683. var Matrix = /** @class */ (function () {
  4684. function Matrix() {
  4685. this._isIdentity = false;
  4686. this._isIdentityDirty = true;
  4687. this.m = new Float32Array(16);
  4688. this._markAsUpdated();
  4689. }
  4690. Matrix.prototype._markAsUpdated = function () {
  4691. this.updateFlag = Matrix._updateFlagSeed++;
  4692. this._isIdentityDirty = true;
  4693. };
  4694. // Properties
  4695. /**
  4696. * Boolean : True is the matrix is the identity matrix
  4697. */
  4698. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  4699. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  4700. if (this._isIdentityDirty) {
  4701. this._isIdentityDirty = false;
  4702. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  4703. this._isIdentity = false;
  4704. }
  4705. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  4706. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  4707. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  4708. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  4709. this._isIdentity = false;
  4710. }
  4711. else {
  4712. this._isIdentity = true;
  4713. }
  4714. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  4715. this._isIdentity = false;
  4716. }
  4717. }
  4718. return this._isIdentity;
  4719. };
  4720. /**
  4721. * Returns the matrix determinant (float).
  4722. */
  4723. Matrix.prototype.determinant = function () {
  4724. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  4725. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  4726. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  4727. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  4728. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  4729. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  4730. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  4731. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  4732. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  4733. };
  4734. // Methods
  4735. /**
  4736. * Returns the matrix underlying array.
  4737. */
  4738. Matrix.prototype.toArray = function () {
  4739. return this.m;
  4740. };
  4741. /**
  4742. * Returns the matrix underlying array.
  4743. */
  4744. Matrix.prototype.asArray = function () {
  4745. return this.toArray();
  4746. };
  4747. /**
  4748. * Inverts in place the Matrix.
  4749. * Returns the Matrix inverted.
  4750. */
  4751. Matrix.prototype.invert = function () {
  4752. this.invertToRef(this);
  4753. return this;
  4754. };
  4755. /**
  4756. * Sets all the matrix elements to zero.
  4757. * Returns the Matrix.
  4758. */
  4759. Matrix.prototype.reset = function () {
  4760. for (var index = 0; index < 16; index++) {
  4761. this.m[index] = 0.0;
  4762. }
  4763. this._markAsUpdated();
  4764. return this;
  4765. };
  4766. /**
  4767. * Returns a new Matrix as the addition result of the current Matrix and the passed one.
  4768. */
  4769. Matrix.prototype.add = function (other) {
  4770. var result = new Matrix();
  4771. this.addToRef(other, result);
  4772. return result;
  4773. };
  4774. /**
  4775. * Sets the passed matrix "result" with the ddition result of the current Matrix and the passed one.
  4776. * Returns the Matrix.
  4777. */
  4778. Matrix.prototype.addToRef = function (other, result) {
  4779. for (var index = 0; index < 16; index++) {
  4780. result.m[index] = this.m[index] + other.m[index];
  4781. }
  4782. result._markAsUpdated();
  4783. return this;
  4784. };
  4785. /**
  4786. * Adds in place the passed matrix to the current Matrix.
  4787. * Returns the updated Matrix.
  4788. */
  4789. Matrix.prototype.addToSelf = function (other) {
  4790. for (var index = 0; index < 16; index++) {
  4791. this.m[index] += other.m[index];
  4792. }
  4793. this._markAsUpdated();
  4794. return this;
  4795. };
  4796. /**
  4797. * Sets the passed matrix with the current inverted Matrix.
  4798. * Returns the unmodified current Matrix.
  4799. */
  4800. Matrix.prototype.invertToRef = function (other) {
  4801. var l1 = this.m[0];
  4802. var l2 = this.m[1];
  4803. var l3 = this.m[2];
  4804. var l4 = this.m[3];
  4805. var l5 = this.m[4];
  4806. var l6 = this.m[5];
  4807. var l7 = this.m[6];
  4808. var l8 = this.m[7];
  4809. var l9 = this.m[8];
  4810. var l10 = this.m[9];
  4811. var l11 = this.m[10];
  4812. var l12 = this.m[11];
  4813. var l13 = this.m[12];
  4814. var l14 = this.m[13];
  4815. var l15 = this.m[14];
  4816. var l16 = this.m[15];
  4817. var l17 = (l11 * l16) - (l12 * l15);
  4818. var l18 = (l10 * l16) - (l12 * l14);
  4819. var l19 = (l10 * l15) - (l11 * l14);
  4820. var l20 = (l9 * l16) - (l12 * l13);
  4821. var l21 = (l9 * l15) - (l11 * l13);
  4822. var l22 = (l9 * l14) - (l10 * l13);
  4823. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  4824. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  4825. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  4826. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  4827. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  4828. var l28 = (l7 * l16) - (l8 * l15);
  4829. var l29 = (l6 * l16) - (l8 * l14);
  4830. var l30 = (l6 * l15) - (l7 * l14);
  4831. var l31 = (l5 * l16) - (l8 * l13);
  4832. var l32 = (l5 * l15) - (l7 * l13);
  4833. var l33 = (l5 * l14) - (l6 * l13);
  4834. var l34 = (l7 * l12) - (l8 * l11);
  4835. var l35 = (l6 * l12) - (l8 * l10);
  4836. var l36 = (l6 * l11) - (l7 * l10);
  4837. var l37 = (l5 * l12) - (l8 * l9);
  4838. var l38 = (l5 * l11) - (l7 * l9);
  4839. var l39 = (l5 * l10) - (l6 * l9);
  4840. other.m[0] = l23 * l27;
  4841. other.m[4] = l24 * l27;
  4842. other.m[8] = l25 * l27;
  4843. other.m[12] = l26 * l27;
  4844. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  4845. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  4846. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  4847. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  4848. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  4849. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  4850. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  4851. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  4852. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  4853. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  4854. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  4855. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  4856. other._markAsUpdated();
  4857. return this;
  4858. };
  4859. /**
  4860. * Inserts the translation vector (using 3 x floats) in the current Matrix.
  4861. * Returns the updated Matrix.
  4862. */
  4863. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  4864. this.m[12] = x;
  4865. this.m[13] = y;
  4866. this.m[14] = z;
  4867. this._markAsUpdated();
  4868. return this;
  4869. };
  4870. /**
  4871. * Inserts the translation vector in the current Matrix.
  4872. * Returns the updated Matrix.
  4873. */
  4874. Matrix.prototype.setTranslation = function (vector3) {
  4875. this.m[12] = vector3.x;
  4876. this.m[13] = vector3.y;
  4877. this.m[14] = vector3.z;
  4878. this._markAsUpdated();
  4879. return this;
  4880. };
  4881. /**
  4882. * Returns a new Vector3 as the extracted translation from the Matrix.
  4883. */
  4884. Matrix.prototype.getTranslation = function () {
  4885. return new Vector3(this.m[12], this.m[13], this.m[14]);
  4886. };
  4887. /**
  4888. * Fill a Vector3 with the extracted translation from the Matrix.
  4889. */
  4890. Matrix.prototype.getTranslationToRef = function (result) {
  4891. result.x = this.m[12];
  4892. result.y = this.m[13];
  4893. result.z = this.m[14];
  4894. return this;
  4895. };
  4896. /**
  4897. * Remove rotation and scaling part from the Matrix.
  4898. * Returns the updated Matrix.
  4899. */
  4900. Matrix.prototype.removeRotationAndScaling = function () {
  4901. this.setRowFromFloats(0, 1, 0, 0, 0);
  4902. this.setRowFromFloats(1, 0, 1, 0, 0);
  4903. this.setRowFromFloats(2, 0, 0, 1, 0);
  4904. return this;
  4905. };
  4906. /**
  4907. * Returns a new Matrix set with the multiplication result of the current Matrix and the passed one.
  4908. */
  4909. Matrix.prototype.multiply = function (other) {
  4910. var result = new Matrix();
  4911. this.multiplyToRef(other, result);
  4912. return result;
  4913. };
  4914. /**
  4915. * Updates the current Matrix from the passed one values.
  4916. * Returns the updated Matrix.
  4917. */
  4918. Matrix.prototype.copyFrom = function (other) {
  4919. for (var index = 0; index < 16; index++) {
  4920. this.m[index] = other.m[index];
  4921. }
  4922. this._markAsUpdated();
  4923. return this;
  4924. };
  4925. /**
  4926. * Populates the passed array from the starting index with the Matrix values.
  4927. * Returns the Matrix.
  4928. */
  4929. Matrix.prototype.copyToArray = function (array, offset) {
  4930. if (offset === void 0) { offset = 0; }
  4931. for (var index = 0; index < 16; index++) {
  4932. array[offset + index] = this.m[index];
  4933. }
  4934. return this;
  4935. };
  4936. /**
  4937. * Sets the passed matrix "result" with the multiplication result of the current Matrix and the passed one.
  4938. */
  4939. Matrix.prototype.multiplyToRef = function (other, result) {
  4940. this.multiplyToArray(other, result.m, 0);
  4941. result._markAsUpdated();
  4942. return this;
  4943. };
  4944. /**
  4945. * Sets the Float32Array "result" from the passed index "offset" with the multiplication result of the current Matrix and the passed one.
  4946. */
  4947. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  4948. var tm0 = this.m[0];
  4949. var tm1 = this.m[1];
  4950. var tm2 = this.m[2];
  4951. var tm3 = this.m[3];
  4952. var tm4 = this.m[4];
  4953. var tm5 = this.m[5];
  4954. var tm6 = this.m[6];
  4955. var tm7 = this.m[7];
  4956. var tm8 = this.m[8];
  4957. var tm9 = this.m[9];
  4958. var tm10 = this.m[10];
  4959. var tm11 = this.m[11];
  4960. var tm12 = this.m[12];
  4961. var tm13 = this.m[13];
  4962. var tm14 = this.m[14];
  4963. var tm15 = this.m[15];
  4964. var om0 = other.m[0];
  4965. var om1 = other.m[1];
  4966. var om2 = other.m[2];
  4967. var om3 = other.m[3];
  4968. var om4 = other.m[4];
  4969. var om5 = other.m[5];
  4970. var om6 = other.m[6];
  4971. var om7 = other.m[7];
  4972. var om8 = other.m[8];
  4973. var om9 = other.m[9];
  4974. var om10 = other.m[10];
  4975. var om11 = other.m[11];
  4976. var om12 = other.m[12];
  4977. var om13 = other.m[13];
  4978. var om14 = other.m[14];
  4979. var om15 = other.m[15];
  4980. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  4981. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  4982. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  4983. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  4984. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  4985. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  4986. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  4987. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  4988. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  4989. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  4990. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  4991. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  4992. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  4993. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  4994. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  4995. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  4996. return this;
  4997. };
  4998. /**
  4999. * Boolean : True is the current Matrix and the passed one values are strictly equal.
  5000. */
  5001. Matrix.prototype.equals = function (value) {
  5002. return value &&
  5003. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  5004. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  5005. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  5006. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  5007. };
  5008. /**
  5009. * Returns a new Matrix from the current Matrix.
  5010. */
  5011. Matrix.prototype.clone = function () {
  5012. 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]);
  5013. };
  5014. /**
  5015. * Returns the string "Matrix"
  5016. */
  5017. Matrix.prototype.getClassName = function () {
  5018. return "Matrix";
  5019. };
  5020. /**
  5021. * Returns the Matrix hash code.
  5022. */
  5023. Matrix.prototype.getHashCode = function () {
  5024. var hash = this.m[0] || 0;
  5025. for (var i = 1; i < 16; i++) {
  5026. hash = (hash * 397) ^ (this.m[i] || 0);
  5027. }
  5028. return hash;
  5029. };
  5030. /**
  5031. * Decomposes the current Matrix into :
  5032. * - a scale vector3 passed as a reference to update,
  5033. * - a rotation quaternion passed as a reference to update,
  5034. * - a translation vector3 passed as a reference to update.
  5035. * Returns the true if operation was successful.
  5036. */
  5037. Matrix.prototype.decompose = function (scale, rotation, translation) {
  5038. translation.x = this.m[12];
  5039. translation.y = this.m[13];
  5040. translation.z = this.m[14];
  5041. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  5042. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  5043. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  5044. if (this.determinant() <= 0) {
  5045. scale.y *= -1;
  5046. }
  5047. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  5048. rotation.x = 0;
  5049. rotation.y = 0;
  5050. rotation.z = 0;
  5051. rotation.w = 1;
  5052. return false;
  5053. }
  5054. 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]);
  5055. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  5056. return true;
  5057. };
  5058. /**
  5059. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  5060. * @param ref matrix to store the result
  5061. */
  5062. Matrix.prototype.toNormalMatrix = function (ref) {
  5063. this.invertToRef(ref);
  5064. ref.transpose();
  5065. var m = ref.m;
  5066. Matrix.FromValuesToRef(m[0], m[1], m[2], 0, m[4], m[5], m[6], 0, m[8], m[9], m[10], 0, 0, 0, 0, 1, ref);
  5067. };
  5068. /**
  5069. * Returns a new Matrix as the extracted rotation matrix from the current one.
  5070. */
  5071. Matrix.prototype.getRotationMatrix = function () {
  5072. var result = Matrix.Identity();
  5073. this.getRotationMatrixToRef(result);
  5074. return result;
  5075. };
  5076. /**
  5077. * Extracts the rotation matrix from the current one and sets it as the passed "result".
  5078. * Returns the current Matrix.
  5079. */
  5080. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5081. var m = this.m;
  5082. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  5083. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  5084. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  5085. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5086. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5087. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5088. 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);
  5089. return this;
  5090. };
  5091. // Statics
  5092. /**
  5093. * Returns a new Matrix set from the starting index of the passed array.
  5094. */
  5095. Matrix.FromArray = function (array, offset) {
  5096. var result = new Matrix();
  5097. if (!offset) {
  5098. offset = 0;
  5099. }
  5100. Matrix.FromArrayToRef(array, offset, result);
  5101. return result;
  5102. };
  5103. /**
  5104. * Sets the passed "result" matrix from the starting index of the passed array.
  5105. */
  5106. Matrix.FromArrayToRef = function (array, offset, result) {
  5107. for (var index = 0; index < 16; index++) {
  5108. result.m[index] = array[index + offset];
  5109. }
  5110. result._markAsUpdated();
  5111. };
  5112. /**
  5113. * Sets the passed "result" matrix from the starting index of the passed Float32Array by multiplying each element by the float "scale".
  5114. */
  5115. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5116. for (var index = 0; index < 16; index++) {
  5117. result.m[index] = array[index + offset] * scale;
  5118. }
  5119. result._markAsUpdated();
  5120. };
  5121. /**
  5122. * Sets the passed matrix "result" with the 16 passed floats.
  5123. */
  5124. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5125. result.m[0] = initialM11;
  5126. result.m[1] = initialM12;
  5127. result.m[2] = initialM13;
  5128. result.m[3] = initialM14;
  5129. result.m[4] = initialM21;
  5130. result.m[5] = initialM22;
  5131. result.m[6] = initialM23;
  5132. result.m[7] = initialM24;
  5133. result.m[8] = initialM31;
  5134. result.m[9] = initialM32;
  5135. result.m[10] = initialM33;
  5136. result.m[11] = initialM34;
  5137. result.m[12] = initialM41;
  5138. result.m[13] = initialM42;
  5139. result.m[14] = initialM43;
  5140. result.m[15] = initialM44;
  5141. result._markAsUpdated();
  5142. };
  5143. /**
  5144. * Returns the index-th row of the current matrix as a new Vector4.
  5145. */
  5146. Matrix.prototype.getRow = function (index) {
  5147. if (index < 0 || index > 3) {
  5148. return null;
  5149. }
  5150. var i = index * 4;
  5151. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5152. };
  5153. /**
  5154. * Sets the index-th row of the current matrix with the passed Vector4 values.
  5155. * Returns the updated Matrix.
  5156. */
  5157. Matrix.prototype.setRow = function (index, row) {
  5158. if (index < 0 || index > 3) {
  5159. return this;
  5160. }
  5161. var i = index * 4;
  5162. this.m[i + 0] = row.x;
  5163. this.m[i + 1] = row.y;
  5164. this.m[i + 2] = row.z;
  5165. this.m[i + 3] = row.w;
  5166. this._markAsUpdated();
  5167. return this;
  5168. };
  5169. /**
  5170. * Compute the transpose of the matrix.
  5171. * Returns a new Matrix.
  5172. */
  5173. Matrix.prototype.transpose = function () {
  5174. return Matrix.Transpose(this);
  5175. };
  5176. /**
  5177. * Compute the transpose of the matrix.
  5178. * Returns the current matrix.
  5179. */
  5180. Matrix.prototype.transposeToRef = function (result) {
  5181. Matrix.TransposeToRef(this, result);
  5182. return this;
  5183. };
  5184. /**
  5185. * Sets the index-th row of the current matrix with the passed 4 x float values.
  5186. * Returns the updated Matrix.
  5187. */
  5188. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5189. if (index < 0 || index > 3) {
  5190. return this;
  5191. }
  5192. var i = index * 4;
  5193. this.m[i + 0] = x;
  5194. this.m[i + 1] = y;
  5195. this.m[i + 2] = z;
  5196. this.m[i + 3] = w;
  5197. this._markAsUpdated();
  5198. return this;
  5199. };
  5200. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5201. /**
  5202. * Static identity matrix to be used as readonly matrix
  5203. * Must not be updated.
  5204. */
  5205. get: function () {
  5206. return Matrix._identityReadOnly;
  5207. },
  5208. enumerable: true,
  5209. configurable: true
  5210. });
  5211. /**
  5212. * Returns a new Matrix set from the 16 passed floats.
  5213. */
  5214. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5215. var result = new Matrix();
  5216. result.m[0] = initialM11;
  5217. result.m[1] = initialM12;
  5218. result.m[2] = initialM13;
  5219. result.m[3] = initialM14;
  5220. result.m[4] = initialM21;
  5221. result.m[5] = initialM22;
  5222. result.m[6] = initialM23;
  5223. result.m[7] = initialM24;
  5224. result.m[8] = initialM31;
  5225. result.m[9] = initialM32;
  5226. result.m[10] = initialM33;
  5227. result.m[11] = initialM34;
  5228. result.m[12] = initialM41;
  5229. result.m[13] = initialM42;
  5230. result.m[14] = initialM43;
  5231. result.m[15] = initialM44;
  5232. return result;
  5233. };
  5234. /**
  5235. * Returns a new Matrix composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  5236. */
  5237. Matrix.Compose = function (scale, rotation, translation) {
  5238. var result = Matrix.Identity();
  5239. Matrix.ComposeToRef(scale, rotation, translation, result);
  5240. return result;
  5241. };
  5242. /**
  5243. * Update a Matrix with values composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  5244. */
  5245. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  5246. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  5247. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  5248. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  5249. result.setTranslation(translation);
  5250. };
  5251. /**
  5252. * Returns a new indentity Matrix.
  5253. */
  5254. Matrix.Identity = function () {
  5255. 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);
  5256. };
  5257. /**
  5258. * Sets the passed "result" as an identity matrix.
  5259. */
  5260. Matrix.IdentityToRef = function (result) {
  5261. 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);
  5262. };
  5263. /**
  5264. * Returns a new zero Matrix.
  5265. */
  5266. Matrix.Zero = function () {
  5267. 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);
  5268. };
  5269. /**
  5270. * Returns a new rotation matrix for "angle" radians around the X axis.
  5271. */
  5272. Matrix.RotationX = function (angle) {
  5273. var result = new Matrix();
  5274. Matrix.RotationXToRef(angle, result);
  5275. return result;
  5276. };
  5277. /**
  5278. * Returns a new Matrix as the passed inverted one.
  5279. */
  5280. Matrix.Invert = function (source) {
  5281. var result = new Matrix();
  5282. source.invertToRef(result);
  5283. return result;
  5284. };
  5285. /**
  5286. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the X axis.
  5287. */
  5288. Matrix.RotationXToRef = function (angle, result) {
  5289. var s = Math.sin(angle);
  5290. var c = Math.cos(angle);
  5291. result.m[0] = 1.0;
  5292. result.m[15] = 1.0;
  5293. result.m[5] = c;
  5294. result.m[10] = c;
  5295. result.m[9] = -s;
  5296. result.m[6] = s;
  5297. result.m[1] = 0.0;
  5298. result.m[2] = 0.0;
  5299. result.m[3] = 0.0;
  5300. result.m[4] = 0.0;
  5301. result.m[7] = 0.0;
  5302. result.m[8] = 0.0;
  5303. result.m[11] = 0.0;
  5304. result.m[12] = 0.0;
  5305. result.m[13] = 0.0;
  5306. result.m[14] = 0.0;
  5307. result._markAsUpdated();
  5308. };
  5309. /**
  5310. * Returns a new rotation matrix for "angle" radians around the Y axis.
  5311. */
  5312. Matrix.RotationY = function (angle) {
  5313. var result = new Matrix();
  5314. Matrix.RotationYToRef(angle, result);
  5315. return result;
  5316. };
  5317. /**
  5318. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Y axis.
  5319. */
  5320. Matrix.RotationYToRef = function (angle, result) {
  5321. var s = Math.sin(angle);
  5322. var c = Math.cos(angle);
  5323. result.m[5] = 1.0;
  5324. result.m[15] = 1.0;
  5325. result.m[0] = c;
  5326. result.m[2] = -s;
  5327. result.m[8] = s;
  5328. result.m[10] = c;
  5329. result.m[1] = 0.0;
  5330. result.m[3] = 0.0;
  5331. result.m[4] = 0.0;
  5332. result.m[6] = 0.0;
  5333. result.m[7] = 0.0;
  5334. result.m[9] = 0.0;
  5335. result.m[11] = 0.0;
  5336. result.m[12] = 0.0;
  5337. result.m[13] = 0.0;
  5338. result.m[14] = 0.0;
  5339. result._markAsUpdated();
  5340. };
  5341. /**
  5342. * Returns a new rotation matrix for "angle" radians around the Z axis.
  5343. */
  5344. Matrix.RotationZ = function (angle) {
  5345. var result = new Matrix();
  5346. Matrix.RotationZToRef(angle, result);
  5347. return result;
  5348. };
  5349. /**
  5350. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Z axis.
  5351. */
  5352. Matrix.RotationZToRef = function (angle, result) {
  5353. var s = Math.sin(angle);
  5354. var c = Math.cos(angle);
  5355. result.m[10] = 1.0;
  5356. result.m[15] = 1.0;
  5357. result.m[0] = c;
  5358. result.m[1] = s;
  5359. result.m[4] = -s;
  5360. result.m[5] = c;
  5361. result.m[2] = 0.0;
  5362. result.m[3] = 0.0;
  5363. result.m[6] = 0.0;
  5364. result.m[7] = 0.0;
  5365. result.m[8] = 0.0;
  5366. result.m[9] = 0.0;
  5367. result.m[11] = 0.0;
  5368. result.m[12] = 0.0;
  5369. result.m[13] = 0.0;
  5370. result.m[14] = 0.0;
  5371. result._markAsUpdated();
  5372. };
  5373. /**
  5374. * Returns a new rotation matrix for "angle" radians around the passed axis.
  5375. */
  5376. Matrix.RotationAxis = function (axis, angle) {
  5377. var result = Matrix.Zero();
  5378. Matrix.RotationAxisToRef(axis, angle, result);
  5379. return result;
  5380. };
  5381. /**
  5382. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the passed axis.
  5383. */
  5384. Matrix.RotationAxisToRef = function (axis, angle, result) {
  5385. var s = Math.sin(-angle);
  5386. var c = Math.cos(-angle);
  5387. var c1 = 1 - c;
  5388. axis.normalize();
  5389. result.m[0] = (axis.x * axis.x) * c1 + c;
  5390. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  5391. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  5392. result.m[3] = 0.0;
  5393. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  5394. result.m[5] = (axis.y * axis.y) * c1 + c;
  5395. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  5396. result.m[7] = 0.0;
  5397. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  5398. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  5399. result.m[10] = (axis.z * axis.z) * c1 + c;
  5400. result.m[11] = 0.0;
  5401. result.m[15] = 1.0;
  5402. result._markAsUpdated();
  5403. };
  5404. /**
  5405. * Returns a new Matrix as a rotation matrix from the Euler angles (y, x, z).
  5406. */
  5407. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  5408. var result = new Matrix();
  5409. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  5410. return result;
  5411. };
  5412. /**
  5413. * Sets the passed matrix "result" as a rotation matrix from the Euler angles (y, x, z).
  5414. */
  5415. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  5416. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  5417. this._tempQuaternion.toRotationMatrix(result);
  5418. };
  5419. /**
  5420. * Returns a new Matrix as a scaling matrix from the passed floats (x, y, z).
  5421. */
  5422. Matrix.Scaling = function (x, y, z) {
  5423. var result = Matrix.Zero();
  5424. Matrix.ScalingToRef(x, y, z, result);
  5425. return result;
  5426. };
  5427. /**
  5428. * Sets the passed matrix "result" as a scaling matrix from the passed floats (x, y, z).
  5429. */
  5430. Matrix.ScalingToRef = function (x, y, z, result) {
  5431. result.m[0] = x;
  5432. result.m[1] = 0.0;
  5433. result.m[2] = 0.0;
  5434. result.m[3] = 0.0;
  5435. result.m[4] = 0.0;
  5436. result.m[5] = y;
  5437. result.m[6] = 0.0;
  5438. result.m[7] = 0.0;
  5439. result.m[8] = 0.0;
  5440. result.m[9] = 0.0;
  5441. result.m[10] = z;
  5442. result.m[11] = 0.0;
  5443. result.m[12] = 0.0;
  5444. result.m[13] = 0.0;
  5445. result.m[14] = 0.0;
  5446. result.m[15] = 1.0;
  5447. result._markAsUpdated();
  5448. };
  5449. /**
  5450. * Returns a new Matrix as a translation matrix from the passed floats (x, y, z).
  5451. */
  5452. Matrix.Translation = function (x, y, z) {
  5453. var result = Matrix.Identity();
  5454. Matrix.TranslationToRef(x, y, z, result);
  5455. return result;
  5456. };
  5457. /**
  5458. * Sets the passed matrix "result" as a translation matrix from the passed floats (x, y, z).
  5459. */
  5460. Matrix.TranslationToRef = function (x, y, z, result) {
  5461. 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);
  5462. };
  5463. /**
  5464. * Returns a new Matrix whose values are the interpolated values for "gradien" (float) between the ones of the matrices "startValue" and "endValue".
  5465. */
  5466. Matrix.Lerp = function (startValue, endValue, gradient) {
  5467. var result = Matrix.Zero();
  5468. for (var index = 0; index < 16; index++) {
  5469. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  5470. }
  5471. result._markAsUpdated();
  5472. return result;
  5473. };
  5474. /**
  5475. * Returns a new Matrix whose values are computed by :
  5476. * - decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices,
  5477. * - interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end,
  5478. * - recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices.
  5479. */
  5480. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  5481. var startScale = new Vector3(0, 0, 0);
  5482. var startRotation = new Quaternion();
  5483. var startTranslation = new Vector3(0, 0, 0);
  5484. startValue.decompose(startScale, startRotation, startTranslation);
  5485. var endScale = new Vector3(0, 0, 0);
  5486. var endRotation = new Quaternion();
  5487. var endTranslation = new Vector3(0, 0, 0);
  5488. endValue.decompose(endScale, endRotation, endTranslation);
  5489. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  5490. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  5491. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  5492. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  5493. };
  5494. /**
  5495. * 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".
  5496. * This methods works for a Left-Handed system.
  5497. */
  5498. Matrix.LookAtLH = function (eye, target, up) {
  5499. var result = Matrix.Zero();
  5500. Matrix.LookAtLHToRef(eye, target, up, result);
  5501. return result;
  5502. };
  5503. /**
  5504. * 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".
  5505. * This methods works for a Left-Handed system.
  5506. */
  5507. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  5508. // Z axis
  5509. target.subtractToRef(eye, this._zAxis);
  5510. this._zAxis.normalize();
  5511. // X axis
  5512. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  5513. if (this._xAxis.lengthSquared() === 0) {
  5514. this._xAxis.x = 1.0;
  5515. }
  5516. else {
  5517. this._xAxis.normalize();
  5518. }
  5519. // Y axis
  5520. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  5521. this._yAxis.normalize();
  5522. // Eye angles
  5523. var ex = -Vector3.Dot(this._xAxis, eye);
  5524. var ey = -Vector3.Dot(this._yAxis, eye);
  5525. var ez = -Vector3.Dot(this._zAxis, eye);
  5526. 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);
  5527. };
  5528. /**
  5529. * 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".
  5530. * This methods works for a Right-Handed system.
  5531. */
  5532. Matrix.LookAtRH = function (eye, target, up) {
  5533. var result = Matrix.Zero();
  5534. Matrix.LookAtRHToRef(eye, target, up, result);
  5535. return result;
  5536. };
  5537. /**
  5538. * 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".
  5539. * This methods works for a Left-Handed system.
  5540. */
  5541. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  5542. // Z axis
  5543. eye.subtractToRef(target, this._zAxis);
  5544. this._zAxis.normalize();
  5545. // X axis
  5546. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  5547. if (this._xAxis.lengthSquared() === 0) {
  5548. this._xAxis.x = 1.0;
  5549. }
  5550. else {
  5551. this._xAxis.normalize();
  5552. }
  5553. // Y axis
  5554. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  5555. this._yAxis.normalize();
  5556. // Eye angles
  5557. var ex = -Vector3.Dot(this._xAxis, eye);
  5558. var ey = -Vector3.Dot(this._yAxis, eye);
  5559. var ez = -Vector3.Dot(this._zAxis, eye);
  5560. 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);
  5561. };
  5562. /**
  5563. * 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.
  5564. */
  5565. Matrix.OrthoLH = function (width, height, znear, zfar) {
  5566. var matrix = Matrix.Zero();
  5567. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  5568. return matrix;
  5569. };
  5570. /**
  5571. * 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.
  5572. */
  5573. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  5574. var n = znear;
  5575. var f = zfar;
  5576. var a = 2.0 / width;
  5577. var b = 2.0 / height;
  5578. var c = 2.0 / (f - n);
  5579. var d = -(f + n) / (f - n);
  5580. 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);
  5581. };
  5582. /**
  5583. * 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.
  5584. */
  5585. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  5586. var matrix = Matrix.Zero();
  5587. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  5588. return matrix;
  5589. };
  5590. /**
  5591. * 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.
  5592. */
  5593. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  5594. var n = znear;
  5595. var f = zfar;
  5596. var a = 2.0 / (right - left);
  5597. var b = 2.0 / (top - bottom);
  5598. var c = 2.0 / (f - n);
  5599. var d = -(f + n) / (f - n);
  5600. var i0 = (left + right) / (left - right);
  5601. var i1 = (top + bottom) / (bottom - top);
  5602. 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);
  5603. };
  5604. /**
  5605. * 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.
  5606. */
  5607. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  5608. var matrix = Matrix.Zero();
  5609. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  5610. return matrix;
  5611. };
  5612. /**
  5613. * 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.
  5614. */
  5615. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  5616. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  5617. result.m[10] *= -1.0;
  5618. };
  5619. /**
  5620. * 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.
  5621. */
  5622. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  5623. var matrix = Matrix.Zero();
  5624. var n = znear;
  5625. var f = zfar;
  5626. var a = 2.0 * n / width;
  5627. var b = 2.0 * n / height;
  5628. var c = (f + n) / (f - n);
  5629. var d = -2.0 * f * n / (f - n);
  5630. 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);
  5631. return matrix;
  5632. };
  5633. /**
  5634. * 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.
  5635. */
  5636. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  5637. var matrix = Matrix.Zero();
  5638. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  5639. return matrix;
  5640. };
  5641. /**
  5642. * 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.
  5643. */
  5644. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  5645. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  5646. var n = znear;
  5647. var f = zfar;
  5648. var t = 1.0 / (Math.tan(fov * 0.5));
  5649. var a = isVerticalFovFixed ? (t / aspect) : t;
  5650. var b = isVerticalFovFixed ? t : (t * aspect);
  5651. var c = (f + n) / (f - n);
  5652. var d = -2.0 * f * n / (f - n);
  5653. 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);
  5654. };
  5655. /**
  5656. * 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.
  5657. */
  5658. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  5659. var matrix = Matrix.Zero();
  5660. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  5661. return matrix;
  5662. };
  5663. /**
  5664. * 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.
  5665. */
  5666. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  5667. //alternatively this could be expressed as:
  5668. // m = PerspectiveFovLHToRef
  5669. // m[10] *= -1.0;
  5670. // m[11] *= -1.0;
  5671. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  5672. var n = znear;
  5673. var f = zfar;
  5674. var t = 1.0 / (Math.tan(fov * 0.5));
  5675. var a = isVerticalFovFixed ? (t / aspect) : t;
  5676. var b = isVerticalFovFixed ? t : (t * aspect);
  5677. var c = -(f + n) / (f - n);
  5678. var d = -2 * f * n / (f - n);
  5679. 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);
  5680. };
  5681. /**
  5682. * 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.
  5683. */
  5684. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  5685. if (rightHanded === void 0) { rightHanded = false; }
  5686. var rightHandedFactor = rightHanded ? -1 : 1;
  5687. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  5688. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  5689. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  5690. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  5691. var xScale = 2.0 / (leftTan + rightTan);
  5692. var yScale = 2.0 / (upTan + downTan);
  5693. result.m[0] = xScale;
  5694. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  5695. result.m[5] = yScale;
  5696. result.m[6] = result.m[7] = 0.0;
  5697. result.m[8] = ((leftTan - rightTan) * xScale * 0.5); // * rightHandedFactor;
  5698. result.m[9] = -((upTan - downTan) * yScale * 0.5); // * rightHandedFactor;
  5699. //result.m[10] = -(znear + zfar) / (zfar - znear) * rightHandedFactor;
  5700. result.m[10] = -zfar / (znear - zfar);
  5701. result.m[11] = 1.0 * rightHandedFactor;
  5702. result.m[12] = result.m[13] = result.m[15] = 0.0;
  5703. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  5704. // result.m[14] = (znear * zfar) / (znear - zfar);
  5705. result._markAsUpdated();
  5706. };
  5707. /**
  5708. * Returns the final transformation matrix : world * view * projection * viewport
  5709. */
  5710. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  5711. var cw = viewport.width;
  5712. var ch = viewport.height;
  5713. var cx = viewport.x;
  5714. var cy = viewport.y;
  5715. 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);
  5716. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  5717. };
  5718. /**
  5719. * Returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the passed Matrix.
  5720. */
  5721. Matrix.GetAsMatrix2x2 = function (matrix) {
  5722. return new Float32Array([
  5723. matrix.m[0], matrix.m[1],
  5724. matrix.m[4], matrix.m[5]
  5725. ]);
  5726. };
  5727. /**
  5728. * Returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the passed Matrix.
  5729. */
  5730. Matrix.GetAsMatrix3x3 = function (matrix) {
  5731. return new Float32Array([
  5732. matrix.m[0], matrix.m[1], matrix.m[2],
  5733. matrix.m[4], matrix.m[5], matrix.m[6],
  5734. matrix.m[8], matrix.m[9], matrix.m[10]
  5735. ]);
  5736. };
  5737. /**
  5738. * Compute the transpose of the passed Matrix.
  5739. * Returns a new Matrix.
  5740. */
  5741. Matrix.Transpose = function (matrix) {
  5742. var result = new Matrix();
  5743. Matrix.TransposeToRef(matrix, result);
  5744. return result;
  5745. };
  5746. /**
  5747. * Compute the transpose of the passed Matrix and store it in the result matrix.
  5748. */
  5749. Matrix.TransposeToRef = function (matrix, result) {
  5750. result.m[0] = matrix.m[0];
  5751. result.m[1] = matrix.m[4];
  5752. result.m[2] = matrix.m[8];
  5753. result.m[3] = matrix.m[12];
  5754. result.m[4] = matrix.m[1];
  5755. result.m[5] = matrix.m[5];
  5756. result.m[6] = matrix.m[9];
  5757. result.m[7] = matrix.m[13];
  5758. result.m[8] = matrix.m[2];
  5759. result.m[9] = matrix.m[6];
  5760. result.m[10] = matrix.m[10];
  5761. result.m[11] = matrix.m[14];
  5762. result.m[12] = matrix.m[3];
  5763. result.m[13] = matrix.m[7];
  5764. result.m[14] = matrix.m[11];
  5765. result.m[15] = matrix.m[15];
  5766. };
  5767. /**
  5768. * Returns a new Matrix as the reflection matrix across the passed plane.
  5769. */
  5770. Matrix.Reflection = function (plane) {
  5771. var matrix = new Matrix();
  5772. Matrix.ReflectionToRef(plane, matrix);
  5773. return matrix;
  5774. };
  5775. /**
  5776. * Sets the passed matrix "result" as the reflection matrix across the passed plane.
  5777. */
  5778. Matrix.ReflectionToRef = function (plane, result) {
  5779. plane.normalize();
  5780. var x = plane.normal.x;
  5781. var y = plane.normal.y;
  5782. var z = plane.normal.z;
  5783. var temp = -2 * x;
  5784. var temp2 = -2 * y;
  5785. var temp3 = -2 * z;
  5786. result.m[0] = (temp * x) + 1;
  5787. result.m[1] = temp2 * x;
  5788. result.m[2] = temp3 * x;
  5789. result.m[3] = 0.0;
  5790. result.m[4] = temp * y;
  5791. result.m[5] = (temp2 * y) + 1;
  5792. result.m[6] = temp3 * y;
  5793. result.m[7] = 0.0;
  5794. result.m[8] = temp * z;
  5795. result.m[9] = temp2 * z;
  5796. result.m[10] = (temp3 * z) + 1;
  5797. result.m[11] = 0.0;
  5798. result.m[12] = temp * plane.d;
  5799. result.m[13] = temp2 * plane.d;
  5800. result.m[14] = temp3 * plane.d;
  5801. result.m[15] = 1.0;
  5802. result._markAsUpdated();
  5803. };
  5804. /**
  5805. * Sets the passed matrix "mat" as a rotation matrix composed from the 3 passed left handed axis.
  5806. */
  5807. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  5808. result.m[0] = xaxis.x;
  5809. result.m[1] = xaxis.y;
  5810. result.m[2] = xaxis.z;
  5811. result.m[3] = 0.0;
  5812. result.m[4] = yaxis.x;
  5813. result.m[5] = yaxis.y;
  5814. result.m[6] = yaxis.z;
  5815. result.m[7] = 0.0;
  5816. result.m[8] = zaxis.x;
  5817. result.m[9] = zaxis.y;
  5818. result.m[10] = zaxis.z;
  5819. result.m[11] = 0.0;
  5820. result.m[12] = 0.0;
  5821. result.m[13] = 0.0;
  5822. result.m[14] = 0.0;
  5823. result.m[15] = 1.0;
  5824. result._markAsUpdated();
  5825. };
  5826. /**
  5827. * Sets the passed matrix "result" as a rotation matrix according to the passed quaternion.
  5828. */
  5829. Matrix.FromQuaternionToRef = function (quat, result) {
  5830. var xx = quat.x * quat.x;
  5831. var yy = quat.y * quat.y;
  5832. var zz = quat.z * quat.z;
  5833. var xy = quat.x * quat.y;
  5834. var zw = quat.z * quat.w;
  5835. var zx = quat.z * quat.x;
  5836. var yw = quat.y * quat.w;
  5837. var yz = quat.y * quat.z;
  5838. var xw = quat.x * quat.w;
  5839. result.m[0] = 1.0 - (2.0 * (yy + zz));
  5840. result.m[1] = 2.0 * (xy + zw);
  5841. result.m[2] = 2.0 * (zx - yw);
  5842. result.m[3] = 0.0;
  5843. result.m[4] = 2.0 * (xy - zw);
  5844. result.m[5] = 1.0 - (2.0 * (zz + xx));
  5845. result.m[6] = 2.0 * (yz + xw);
  5846. result.m[7] = 0.0;
  5847. result.m[8] = 2.0 * (zx + yw);
  5848. result.m[9] = 2.0 * (yz - xw);
  5849. result.m[10] = 1.0 - (2.0 * (yy + xx));
  5850. result.m[11] = 0.0;
  5851. result.m[12] = 0.0;
  5852. result.m[13] = 0.0;
  5853. result.m[14] = 0.0;
  5854. result.m[15] = 1.0;
  5855. result._markAsUpdated();
  5856. };
  5857. Matrix._tempQuaternion = new Quaternion();
  5858. Matrix._xAxis = Vector3.Zero();
  5859. Matrix._yAxis = Vector3.Zero();
  5860. Matrix._zAxis = Vector3.Zero();
  5861. Matrix._updateFlagSeed = 0;
  5862. Matrix._identityReadOnly = Matrix.Identity();
  5863. return Matrix;
  5864. }());
  5865. BABYLON.Matrix = Matrix;
  5866. var Plane = /** @class */ (function () {
  5867. /**
  5868. * Creates a Plane object according to the passed floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  5869. */
  5870. function Plane(a, b, c, d) {
  5871. this.normal = new Vector3(a, b, c);
  5872. this.d = d;
  5873. }
  5874. /**
  5875. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  5876. */
  5877. Plane.prototype.asArray = function () {
  5878. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  5879. };
  5880. // Methods
  5881. /**
  5882. * Returns a new plane copied from the current Plane.
  5883. */
  5884. Plane.prototype.clone = function () {
  5885. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  5886. };
  5887. /**
  5888. * Returns the string "Plane".
  5889. */
  5890. Plane.prototype.getClassName = function () {
  5891. return "Plane";
  5892. };
  5893. /**
  5894. * Returns the Plane hash code.
  5895. */
  5896. Plane.prototype.getHashCode = function () {
  5897. var hash = this.normal.getHashCode();
  5898. hash = (hash * 397) ^ (this.d || 0);
  5899. return hash;
  5900. };
  5901. /**
  5902. * Normalize the current Plane in place.
  5903. * Returns the updated Plane.
  5904. */
  5905. Plane.prototype.normalize = function () {
  5906. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  5907. var magnitude = 0.0;
  5908. if (norm !== 0) {
  5909. magnitude = 1.0 / norm;
  5910. }
  5911. this.normal.x *= magnitude;
  5912. this.normal.y *= magnitude;
  5913. this.normal.z *= magnitude;
  5914. this.d *= magnitude;
  5915. return this;
  5916. };
  5917. /**
  5918. * Returns a new Plane as the result of the transformation of the current Plane by the passed matrix.
  5919. */
  5920. Plane.prototype.transform = function (transformation) {
  5921. var transposedMatrix = Matrix.Transpose(transformation);
  5922. var x = this.normal.x;
  5923. var y = this.normal.y;
  5924. var z = this.normal.z;
  5925. var d = this.d;
  5926. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  5927. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  5928. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  5929. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  5930. return new Plane(normalX, normalY, normalZ, finalD);
  5931. };
  5932. /**
  5933. * Returns the dot product (float) of the point coordinates and the plane normal.
  5934. */
  5935. Plane.prototype.dotCoordinate = function (point) {
  5936. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  5937. };
  5938. /**
  5939. * Updates the current Plane from the plane defined by the three passed points.
  5940. * Returns the updated Plane.
  5941. */
  5942. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  5943. var x1 = point2.x - point1.x;
  5944. var y1 = point2.y - point1.y;
  5945. var z1 = point2.z - point1.z;
  5946. var x2 = point3.x - point1.x;
  5947. var y2 = point3.y - point1.y;
  5948. var z2 = point3.z - point1.z;
  5949. var yz = (y1 * z2) - (z1 * y2);
  5950. var xz = (z1 * x2) - (x1 * z2);
  5951. var xy = (x1 * y2) - (y1 * x2);
  5952. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  5953. var invPyth;
  5954. if (pyth !== 0) {
  5955. invPyth = 1.0 / pyth;
  5956. }
  5957. else {
  5958. invPyth = 0.0;
  5959. }
  5960. this.normal.x = yz * invPyth;
  5961. this.normal.y = xz * invPyth;
  5962. this.normal.z = xy * invPyth;
  5963. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  5964. return this;
  5965. };
  5966. /**
  5967. * Boolean : True is the vector "direction" is the same side than the plane normal.
  5968. */
  5969. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  5970. var dot = Vector3.Dot(this.normal, direction);
  5971. return (dot <= epsilon);
  5972. };
  5973. /**
  5974. * Returns the signed distance (float) from the passed point to the Plane.
  5975. */
  5976. Plane.prototype.signedDistanceTo = function (point) {
  5977. return Vector3.Dot(point, this.normal) + this.d;
  5978. };
  5979. // Statics
  5980. /**
  5981. * Returns a new Plane from the passed array.
  5982. */
  5983. Plane.FromArray = function (array) {
  5984. return new Plane(array[0], array[1], array[2], array[3]);
  5985. };
  5986. /**
  5987. * Returns a new Plane defined by the three passed points.
  5988. */
  5989. Plane.FromPoints = function (point1, point2, point3) {
  5990. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  5991. result.copyFromPoints(point1, point2, point3);
  5992. return result;
  5993. };
  5994. /**
  5995. * Returns a new Plane the normal vector to this plane at the passed origin point.
  5996. * Note : the vector "normal" is updated because normalized.
  5997. */
  5998. Plane.FromPositionAndNormal = function (origin, normal) {
  5999. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6000. normal.normalize();
  6001. result.normal = normal;
  6002. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6003. return result;
  6004. };
  6005. /**
  6006. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the passed other point.
  6007. */
  6008. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  6009. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6010. return Vector3.Dot(point, normal) + d;
  6011. };
  6012. return Plane;
  6013. }());
  6014. BABYLON.Plane = Plane;
  6015. var Viewport = /** @class */ (function () {
  6016. /**
  6017. * Creates a Viewport object located at (x, y) and sized (width, height).
  6018. */
  6019. function Viewport(x, y, width, height) {
  6020. this.x = x;
  6021. this.y = y;
  6022. this.width = width;
  6023. this.height = height;
  6024. }
  6025. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  6026. if (renderWidthOrEngine.getRenderWidth) {
  6027. var engine = renderWidthOrEngine;
  6028. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  6029. }
  6030. var renderWidth = renderWidthOrEngine;
  6031. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  6032. };
  6033. /**
  6034. * Returns a new Viewport copied from the current one.
  6035. */
  6036. Viewport.prototype.clone = function () {
  6037. return new Viewport(this.x, this.y, this.width, this.height);
  6038. };
  6039. return Viewport;
  6040. }());
  6041. BABYLON.Viewport = Viewport;
  6042. var Frustum = /** @class */ (function () {
  6043. function Frustum() {
  6044. }
  6045. /**
  6046. * Returns a new array of 6 Frustum planes computed by the passed transformation matrix.
  6047. */
  6048. Frustum.GetPlanes = function (transform) {
  6049. var frustumPlanes = [];
  6050. for (var index = 0; index < 6; index++) {
  6051. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  6052. }
  6053. Frustum.GetPlanesToRef(transform, frustumPlanes);
  6054. return frustumPlanes;
  6055. };
  6056. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  6057. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  6058. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  6059. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  6060. frustumPlane.d = transform.m[15] + transform.m[14];
  6061. frustumPlane.normalize();
  6062. };
  6063. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  6064. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  6065. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  6066. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  6067. frustumPlane.d = transform.m[15] - transform.m[14];
  6068. frustumPlane.normalize();
  6069. };
  6070. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  6071. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  6072. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  6073. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  6074. frustumPlane.d = transform.m[15] + transform.m[12];
  6075. frustumPlane.normalize();
  6076. };
  6077. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  6078. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  6079. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  6080. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  6081. frustumPlane.d = transform.m[15] - transform.m[12];
  6082. frustumPlane.normalize();
  6083. };
  6084. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  6085. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  6086. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  6087. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  6088. frustumPlane.d = transform.m[15] - transform.m[13];
  6089. frustumPlane.normalize();
  6090. };
  6091. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  6092. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  6093. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  6094. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  6095. frustumPlane.d = transform.m[15] + transform.m[13];
  6096. frustumPlane.normalize();
  6097. };
  6098. /**
  6099. * Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
  6100. */
  6101. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  6102. // Near
  6103. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  6104. // Far
  6105. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  6106. // Left
  6107. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  6108. // Right
  6109. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  6110. // Top
  6111. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  6112. // Bottom
  6113. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  6114. };
  6115. return Frustum;
  6116. }());
  6117. BABYLON.Frustum = Frustum;
  6118. var Space;
  6119. (function (Space) {
  6120. Space[Space["LOCAL"] = 0] = "LOCAL";
  6121. Space[Space["WORLD"] = 1] = "WORLD";
  6122. Space[Space["BONE"] = 2] = "BONE";
  6123. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6124. var Axis = /** @class */ (function () {
  6125. function Axis() {
  6126. }
  6127. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6128. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6129. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6130. return Axis;
  6131. }());
  6132. BABYLON.Axis = Axis;
  6133. ;
  6134. var BezierCurve = /** @class */ (function () {
  6135. function BezierCurve() {
  6136. }
  6137. /**
  6138. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
  6139. */
  6140. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  6141. // Extract X (which is equal to time here)
  6142. var f0 = 1 - 3 * x2 + 3 * x1;
  6143. var f1 = 3 * x2 - 6 * x1;
  6144. var f2 = 3 * x1;
  6145. var refinedT = t;
  6146. for (var i = 0; i < 5; i++) {
  6147. var refinedT2 = refinedT * refinedT;
  6148. var refinedT3 = refinedT2 * refinedT;
  6149. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  6150. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  6151. refinedT -= (x - t) * slope;
  6152. refinedT = Math.min(1, Math.max(0, refinedT));
  6153. }
  6154. // Resolve cubic bezier for the given x
  6155. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  6156. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  6157. Math.pow(refinedT, 3);
  6158. };
  6159. return BezierCurve;
  6160. }());
  6161. BABYLON.BezierCurve = BezierCurve;
  6162. var Orientation;
  6163. (function (Orientation) {
  6164. Orientation[Orientation["CW"] = 0] = "CW";
  6165. Orientation[Orientation["CCW"] = 1] = "CCW";
  6166. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  6167. var Angle = /** @class */ (function () {
  6168. /**
  6169. * Creates an Angle object of "radians" radians (float).
  6170. */
  6171. function Angle(radians) {
  6172. var _this = this;
  6173. /**
  6174. * Returns the Angle value in degrees (float).
  6175. */
  6176. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  6177. /**
  6178. * Returns the Angle value in radians (float).
  6179. */
  6180. this.radians = function () { return _this._radians; };
  6181. this._radians = radians;
  6182. if (this._radians < 0.0)
  6183. this._radians += (2.0 * Math.PI);
  6184. }
  6185. /**
  6186. * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
  6187. */
  6188. Angle.BetweenTwoPoints = function (a, b) {
  6189. var delta = b.subtract(a);
  6190. var theta = Math.atan2(delta.y, delta.x);
  6191. return new Angle(theta);
  6192. };
  6193. /**
  6194. * Returns a new Angle object from the passed float in radians.
  6195. */
  6196. Angle.FromRadians = function (radians) {
  6197. return new Angle(radians);
  6198. };
  6199. /**
  6200. * Returns a new Angle object from the passed float in degrees.
  6201. */
  6202. Angle.FromDegrees = function (degrees) {
  6203. return new Angle(degrees * Math.PI / 180.0);
  6204. };
  6205. return Angle;
  6206. }());
  6207. BABYLON.Angle = Angle;
  6208. var Arc2 = /** @class */ (function () {
  6209. /**
  6210. * Creates an Arc object from the three passed points : start, middle and end.
  6211. */
  6212. function Arc2(startPoint, midPoint, endPoint) {
  6213. this.startPoint = startPoint;
  6214. this.midPoint = midPoint;
  6215. this.endPoint = endPoint;
  6216. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  6217. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  6218. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  6219. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  6220. 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);
  6221. this.radius = this.centerPoint.subtract(this.startPoint).length();
  6222. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  6223. var a1 = this.startAngle.degrees();
  6224. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  6225. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  6226. // angles correction
  6227. if (a2 - a1 > +180.0)
  6228. a2 -= 360.0;
  6229. if (a2 - a1 < -180.0)
  6230. a2 += 360.0;
  6231. if (a3 - a2 > +180.0)
  6232. a3 -= 360.0;
  6233. if (a3 - a2 < -180.0)
  6234. a3 += 360.0;
  6235. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  6236. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  6237. }
  6238. return Arc2;
  6239. }());
  6240. BABYLON.Arc2 = Arc2;
  6241. var Path2 = /** @class */ (function () {
  6242. /**
  6243. * Creates a Path2 object from the starting 2D coordinates x and y.
  6244. */
  6245. function Path2(x, y) {
  6246. this._points = new Array();
  6247. this._length = 0.0;
  6248. this.closed = false;
  6249. this._points.push(new Vector2(x, y));
  6250. }
  6251. /**
  6252. * Adds a new segment until the passed coordinates (x, y) to the current Path2.
  6253. * Returns the updated Path2.
  6254. */
  6255. Path2.prototype.addLineTo = function (x, y) {
  6256. if (this.closed) {
  6257. return this;
  6258. }
  6259. var newPoint = new Vector2(x, y);
  6260. var previousPoint = this._points[this._points.length - 1];
  6261. this._points.push(newPoint);
  6262. this._length += newPoint.subtract(previousPoint).length();
  6263. return this;
  6264. };
  6265. /**
  6266. * 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.
  6267. * Returns the updated Path2.
  6268. */
  6269. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  6270. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  6271. if (this.closed) {
  6272. return this;
  6273. }
  6274. var startPoint = this._points[this._points.length - 1];
  6275. var midPoint = new Vector2(midX, midY);
  6276. var endPoint = new Vector2(endX, endY);
  6277. var arc = new Arc2(startPoint, midPoint, endPoint);
  6278. var increment = arc.angle.radians() / numberOfSegments;
  6279. if (arc.orientation === Orientation.CW)
  6280. increment *= -1;
  6281. var currentAngle = arc.startAngle.radians() + increment;
  6282. for (var i = 0; i < numberOfSegments; i++) {
  6283. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  6284. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  6285. this.addLineTo(x, y);
  6286. currentAngle += increment;
  6287. }
  6288. return this;
  6289. };
  6290. /**
  6291. * Closes the Path2.
  6292. * Returns the Path2.
  6293. */
  6294. Path2.prototype.close = function () {
  6295. this.closed = true;
  6296. return this;
  6297. };
  6298. /**
  6299. * Returns the Path2 total length (float).
  6300. */
  6301. Path2.prototype.length = function () {
  6302. var result = this._length;
  6303. if (!this.closed) {
  6304. var lastPoint = this._points[this._points.length - 1];
  6305. var firstPoint = this._points[0];
  6306. result += (firstPoint.subtract(lastPoint).length());
  6307. }
  6308. return result;
  6309. };
  6310. /**
  6311. * Returns the Path2 internal array of points.
  6312. */
  6313. Path2.prototype.getPoints = function () {
  6314. return this._points;
  6315. };
  6316. /**
  6317. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  6318. */
  6319. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  6320. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  6321. return Vector2.Zero();
  6322. }
  6323. var lengthPosition = normalizedLengthPosition * this.length();
  6324. var previousOffset = 0;
  6325. for (var i = 0; i < this._points.length; i++) {
  6326. var j = (i + 1) % this._points.length;
  6327. var a = this._points[i];
  6328. var b = this._points[j];
  6329. var bToA = b.subtract(a);
  6330. var nextOffset = (bToA.length() + previousOffset);
  6331. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  6332. var dir = bToA.normalize();
  6333. var localOffset = lengthPosition - previousOffset;
  6334. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  6335. }
  6336. previousOffset = nextOffset;
  6337. }
  6338. return Vector2.Zero();
  6339. };
  6340. /**
  6341. * Returns a new Path2 starting at the coordinates (x, y).
  6342. */
  6343. Path2.StartingAt = function (x, y) {
  6344. return new Path2(x, y);
  6345. };
  6346. return Path2;
  6347. }());
  6348. BABYLON.Path2 = Path2;
  6349. var Path3D = /** @class */ (function () {
  6350. /**
  6351. * new Path3D(path, normal, raw)
  6352. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  6353. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  6354. * path : an array of Vector3, the curve axis of the Path3D
  6355. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  6356. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  6357. */
  6358. function Path3D(path, firstNormal, raw) {
  6359. if (firstNormal === void 0) { firstNormal = null; }
  6360. this.path = path;
  6361. this._curve = new Array();
  6362. this._distances = new Array();
  6363. this._tangents = new Array();
  6364. this._normals = new Array();
  6365. this._binormals = new Array();
  6366. for (var p = 0; p < path.length; p++) {
  6367. this._curve[p] = path[p].clone(); // hard copy
  6368. }
  6369. this._raw = raw || false;
  6370. this._compute(firstNormal);
  6371. }
  6372. /**
  6373. * Returns the Path3D array of successive Vector3 designing its curve.
  6374. */
  6375. Path3D.prototype.getCurve = function () {
  6376. return this._curve;
  6377. };
  6378. /**
  6379. * Returns an array populated with tangent vectors on each Path3D curve point.
  6380. */
  6381. Path3D.prototype.getTangents = function () {
  6382. return this._tangents;
  6383. };
  6384. /**
  6385. * Returns an array populated with normal vectors on each Path3D curve point.
  6386. */
  6387. Path3D.prototype.getNormals = function () {
  6388. return this._normals;
  6389. };
  6390. /**
  6391. * Returns an array populated with binormal vectors on each Path3D curve point.
  6392. */
  6393. Path3D.prototype.getBinormals = function () {
  6394. return this._binormals;
  6395. };
  6396. /**
  6397. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  6398. */
  6399. Path3D.prototype.getDistances = function () {
  6400. return this._distances;
  6401. };
  6402. /**
  6403. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  6404. * Returns the same object updated.
  6405. */
  6406. Path3D.prototype.update = function (path, firstNormal) {
  6407. if (firstNormal === void 0) { firstNormal = null; }
  6408. for (var p = 0; p < path.length; p++) {
  6409. this._curve[p].x = path[p].x;
  6410. this._curve[p].y = path[p].y;
  6411. this._curve[p].z = path[p].z;
  6412. }
  6413. this._compute(firstNormal);
  6414. return this;
  6415. };
  6416. // private function compute() : computes tangents, normals and binormals
  6417. Path3D.prototype._compute = function (firstNormal) {
  6418. var l = this._curve.length;
  6419. // first and last tangents
  6420. this._tangents[0] = this._getFirstNonNullVector(0);
  6421. if (!this._raw) {
  6422. this._tangents[0].normalize();
  6423. }
  6424. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  6425. if (!this._raw) {
  6426. this._tangents[l - 1].normalize();
  6427. }
  6428. // normals and binormals at first point : arbitrary vector with _normalVector()
  6429. var tg0 = this._tangents[0];
  6430. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  6431. this._normals[0] = pp0;
  6432. if (!this._raw) {
  6433. this._normals[0].normalize();
  6434. }
  6435. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  6436. if (!this._raw) {
  6437. this._binormals[0].normalize();
  6438. }
  6439. this._distances[0] = 0.0;
  6440. // normals and binormals : next points
  6441. var prev; // previous vector (segment)
  6442. var cur; // current vector (segment)
  6443. var curTang; // current tangent
  6444. // previous normal
  6445. var prevBinor; // previous binormal
  6446. for (var i = 1; i < l; i++) {
  6447. // tangents
  6448. prev = this._getLastNonNullVector(i);
  6449. if (i < l - 1) {
  6450. cur = this._getFirstNonNullVector(i);
  6451. this._tangents[i] = prev.add(cur);
  6452. this._tangents[i].normalize();
  6453. }
  6454. this._distances[i] = this._distances[i - 1] + prev.length();
  6455. // normals and binormals
  6456. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  6457. curTang = this._tangents[i];
  6458. prevBinor = this._binormals[i - 1];
  6459. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  6460. if (!this._raw) {
  6461. this._normals[i].normalize();
  6462. }
  6463. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  6464. if (!this._raw) {
  6465. this._binormals[i].normalize();
  6466. }
  6467. }
  6468. };
  6469. // private function getFirstNonNullVector(index)
  6470. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  6471. Path3D.prototype._getFirstNonNullVector = function (index) {
  6472. var i = 1;
  6473. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  6474. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  6475. i++;
  6476. nNVector = this._curve[index + i].subtract(this._curve[index]);
  6477. }
  6478. return nNVector;
  6479. };
  6480. // private function getLastNonNullVector(index)
  6481. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  6482. Path3D.prototype._getLastNonNullVector = function (index) {
  6483. var i = 1;
  6484. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  6485. while (nLVector.length() === 0 && index > i + 1) {
  6486. i++;
  6487. nLVector = this._curve[index].subtract(this._curve[index - i]);
  6488. }
  6489. return nLVector;
  6490. };
  6491. // private function normalVector(v0, vt, va) :
  6492. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  6493. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  6494. Path3D.prototype._normalVector = function (v0, vt, va) {
  6495. var normal0;
  6496. var tgl = vt.length();
  6497. if (tgl === 0.0) {
  6498. tgl = 1.0;
  6499. }
  6500. if (va === undefined || va === null) {
  6501. var point;
  6502. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  6503. point = new Vector3(0.0, -1.0, 0.0);
  6504. }
  6505. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  6506. point = new Vector3(1.0, 0.0, 0.0);
  6507. }
  6508. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  6509. point = new Vector3(0.0, 0.0, 1.0);
  6510. }
  6511. else {
  6512. point = Vector3.Zero();
  6513. }
  6514. normal0 = Vector3.Cross(vt, point);
  6515. }
  6516. else {
  6517. normal0 = Vector3.Cross(vt, va);
  6518. Vector3.CrossToRef(normal0, vt, normal0);
  6519. }
  6520. normal0.normalize();
  6521. return normal0;
  6522. };
  6523. return Path3D;
  6524. }());
  6525. BABYLON.Path3D = Path3D;
  6526. var Curve3 = /** @class */ (function () {
  6527. /**
  6528. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  6529. * A Curve3 is designed from a series of successive Vector3.
  6530. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  6531. */
  6532. function Curve3(points) {
  6533. this._length = 0.0;
  6534. this._points = points;
  6535. this._length = this._computeLength(points);
  6536. }
  6537. /**
  6538. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  6539. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  6540. * @param v1 (Vector3) the control point
  6541. * @param v2 (Vector3) the end point of the Quadratic Bezier
  6542. * @param nbPoints (integer) the wanted number of points in the curve
  6543. */
  6544. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  6545. nbPoints = nbPoints > 2 ? nbPoints : 3;
  6546. var bez = new Array();
  6547. var equation = function (t, val0, val1, val2) {
  6548. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  6549. return res;
  6550. };
  6551. for (var i = 0; i <= nbPoints; i++) {
  6552. 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)));
  6553. }
  6554. return new Curve3(bez);
  6555. };
  6556. /**
  6557. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  6558. * @param v0 (Vector3) the origin point of the Cubic Bezier
  6559. * @param v1 (Vector3) the first control point
  6560. * @param v2 (Vector3) the second control point
  6561. * @param v3 (Vector3) the end point of the Cubic Bezier
  6562. * @param nbPoints (integer) the wanted number of points in the curve
  6563. */
  6564. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  6565. nbPoints = nbPoints > 3 ? nbPoints : 4;
  6566. var bez = new Array();
  6567. var equation = function (t, val0, val1, val2, val3) {
  6568. 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;
  6569. return res;
  6570. };
  6571. for (var i = 0; i <= nbPoints; i++) {
  6572. 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)));
  6573. }
  6574. return new Curve3(bez);
  6575. };
  6576. /**
  6577. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  6578. * @param p1 (Vector3) the origin point of the Hermite Spline
  6579. * @param t1 (Vector3) the tangent vector at the origin point
  6580. * @param p2 (Vector3) the end point of the Hermite Spline
  6581. * @param t2 (Vector3) the tangent vector at the end point
  6582. * @param nbPoints (integer) the wanted number of points in the curve
  6583. */
  6584. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  6585. var hermite = new Array();
  6586. var step = 1.0 / nbPoints;
  6587. for (var i = 0; i <= nbPoints; i++) {
  6588. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  6589. }
  6590. return new Curve3(hermite);
  6591. };
  6592. /**
  6593. * Returns a Curve3 object along a CatmullRom Spline curve :
  6594. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  6595. * @param nbPoints (integer) the wanted number of points between each curve control points.
  6596. */
  6597. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  6598. var totalPoints = new Array();
  6599. totalPoints.push(points[0].clone());
  6600. Array.prototype.push.apply(totalPoints, points);
  6601. totalPoints.push(points[points.length - 1].clone());
  6602. var catmullRom = new Array();
  6603. var step = 1.0 / nbPoints;
  6604. var amount = 0.0;
  6605. for (var i = 0; i < totalPoints.length - 3; i++) {
  6606. amount = 0;
  6607. for (var c = 0; c < nbPoints; c++) {
  6608. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  6609. amount += step;
  6610. }
  6611. }
  6612. i--;
  6613. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  6614. return new Curve3(catmullRom);
  6615. };
  6616. /**
  6617. * Returns the Curve3 stored array of successive Vector3
  6618. */
  6619. Curve3.prototype.getPoints = function () {
  6620. return this._points;
  6621. };
  6622. /**
  6623. * Returns the computed length (float) of the curve.
  6624. */
  6625. Curve3.prototype.length = function () {
  6626. return this._length;
  6627. };
  6628. /**
  6629. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  6630. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  6631. * curveA and curveB keep unchanged.
  6632. */
  6633. Curve3.prototype.continue = function (curve) {
  6634. var lastPoint = this._points[this._points.length - 1];
  6635. var continuedPoints = this._points.slice();
  6636. var curvePoints = curve.getPoints();
  6637. for (var i = 1; i < curvePoints.length; i++) {
  6638. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  6639. }
  6640. var continuedCurve = new Curve3(continuedPoints);
  6641. return continuedCurve;
  6642. };
  6643. Curve3.prototype._computeLength = function (path) {
  6644. var l = 0;
  6645. for (var i = 1; i < path.length; i++) {
  6646. l += (path[i].subtract(path[i - 1])).length();
  6647. }
  6648. return l;
  6649. };
  6650. return Curve3;
  6651. }());
  6652. BABYLON.Curve3 = Curve3;
  6653. // Vertex formats
  6654. var PositionNormalVertex = /** @class */ (function () {
  6655. function PositionNormalVertex(position, normal) {
  6656. if (position === void 0) { position = Vector3.Zero(); }
  6657. if (normal === void 0) { normal = Vector3.Up(); }
  6658. this.position = position;
  6659. this.normal = normal;
  6660. }
  6661. PositionNormalVertex.prototype.clone = function () {
  6662. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  6663. };
  6664. return PositionNormalVertex;
  6665. }());
  6666. BABYLON.PositionNormalVertex = PositionNormalVertex;
  6667. var PositionNormalTextureVertex = /** @class */ (function () {
  6668. function PositionNormalTextureVertex(position, normal, uv) {
  6669. if (position === void 0) { position = Vector3.Zero(); }
  6670. if (normal === void 0) { normal = Vector3.Up(); }
  6671. if (uv === void 0) { uv = Vector2.Zero(); }
  6672. this.position = position;
  6673. this.normal = normal;
  6674. this.uv = uv;
  6675. }
  6676. PositionNormalTextureVertex.prototype.clone = function () {
  6677. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  6678. };
  6679. return PositionNormalTextureVertex;
  6680. }());
  6681. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  6682. // Temporary pre-allocated objects for engine internal use
  6683. // usage in any internal function :
  6684. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  6685. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  6686. var Tmp = /** @class */ (function () {
  6687. function Tmp() {
  6688. }
  6689. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  6690. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  6691. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  6692. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  6693. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  6694. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  6695. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  6696. Matrix.Zero(), Matrix.Zero(),
  6697. Matrix.Zero(), Matrix.Zero(),
  6698. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  6699. return Tmp;
  6700. }());
  6701. BABYLON.Tmp = Tmp;
  6702. // Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
  6703. var MathTmp = /** @class */ (function () {
  6704. function MathTmp() {
  6705. }
  6706. MathTmp.Vector3 = [Vector3.Zero()];
  6707. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  6708. MathTmp.Quaternion = [Quaternion.Zero()];
  6709. return MathTmp;
  6710. }());
  6711. })(BABYLON || (BABYLON = {}));
  6712. //# sourceMappingURL=babylon.math.js.map
  6713. var BABYLON;
  6714. (function (BABYLON) {
  6715. var Scalar = /** @class */ (function () {
  6716. function Scalar() {
  6717. }
  6718. /**
  6719. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  6720. */
  6721. Scalar.WithinEpsilon = function (a, b, epsilon) {
  6722. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  6723. var num = a - b;
  6724. return -epsilon <= num && num <= epsilon;
  6725. };
  6726. /**
  6727. * Returns a string : the upper case translation of the number i to hexadecimal.
  6728. */
  6729. Scalar.ToHex = function (i) {
  6730. var str = i.toString(16);
  6731. if (i <= 15) {
  6732. return ("0" + str).toUpperCase();
  6733. }
  6734. return str.toUpperCase();
  6735. };
  6736. /**
  6737. * Returns -1 if value is negative and +1 is value is positive.
  6738. * Returns the value itself if it's equal to zero.
  6739. */
  6740. Scalar.Sign = function (value) {
  6741. value = +value; // convert to a number
  6742. if (value === 0 || isNaN(value))
  6743. return value;
  6744. return value > 0 ? 1 : -1;
  6745. };
  6746. /**
  6747. * Returns the value itself if it's between min and max.
  6748. * Returns min if the value is lower than min.
  6749. * Returns max if the value is greater than max.
  6750. */
  6751. Scalar.Clamp = function (value, min, max) {
  6752. if (min === void 0) { min = 0; }
  6753. if (max === void 0) { max = 1; }
  6754. return Math.min(max, Math.max(min, value));
  6755. };
  6756. /**
  6757. * Returns the log2 of value.
  6758. */
  6759. Scalar.Log2 = function (value) {
  6760. return Math.log(value) * Math.LOG2E;
  6761. };
  6762. /**
  6763. * Loops the value, so that it is never larger than length and never smaller than 0.
  6764. *
  6765. * This is similar to the modulo operator but it works with floating point numbers.
  6766. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  6767. * With t = 5 and length = 2.5, the result would be 0.0.
  6768. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  6769. */
  6770. Scalar.Repeat = function (value, length) {
  6771. return value - Math.floor(value / length) * length;
  6772. };
  6773. /**
  6774. * Normalize the value between 0.0 and 1.0 using min and max values
  6775. */
  6776. Scalar.Normalize = function (value, min, max) {
  6777. return (value - min) / (max - min);
  6778. };
  6779. /**
  6780. * Denormalize the value from 0.0 and 1.0 using min and max values
  6781. */
  6782. Scalar.Denormalize = function (normalized, min, max) {
  6783. return (normalized * (max - min) + min);
  6784. };
  6785. /**
  6786. * Calculates the shortest difference between two given angles given in degrees.
  6787. */
  6788. Scalar.DeltaAngle = function (current, target) {
  6789. var num = Scalar.Repeat(target - current, 360.0);
  6790. if (num > 180.0) {
  6791. num -= 360.0;
  6792. }
  6793. return num;
  6794. };
  6795. /**
  6796. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  6797. *
  6798. * The returned value will move back and forth between 0 and length
  6799. */
  6800. Scalar.PingPong = function (tx, length) {
  6801. var t = Scalar.Repeat(tx, length * 2.0);
  6802. return length - Math.abs(t - length);
  6803. };
  6804. /**
  6805. * Interpolates between min and max with smoothing at the limits.
  6806. *
  6807. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  6808. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  6809. */
  6810. Scalar.SmoothStep = function (from, to, tx) {
  6811. var t = Scalar.Clamp(tx);
  6812. t = -2.0 * t * t * t + 3.0 * t * t;
  6813. return to * t + from * (1.0 - t);
  6814. };
  6815. /**
  6816. * Moves a value current towards target.
  6817. *
  6818. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  6819. * Negative values of maxDelta pushes the value away from target.
  6820. */
  6821. Scalar.MoveTowards = function (current, target, maxDelta) {
  6822. var result = 0;
  6823. if (Math.abs(target - current) <= maxDelta) {
  6824. result = target;
  6825. }
  6826. else {
  6827. result = current + Scalar.Sign(target - current) * maxDelta;
  6828. }
  6829. return result;
  6830. };
  6831. /**
  6832. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  6833. *
  6834. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  6835. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  6836. */
  6837. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  6838. var num = Scalar.DeltaAngle(current, target);
  6839. var result = 0;
  6840. if (-maxDelta < num && num < maxDelta) {
  6841. result = target;
  6842. }
  6843. else {
  6844. target = current + num;
  6845. result = Scalar.MoveTowards(current, target, maxDelta);
  6846. }
  6847. return result;
  6848. };
  6849. /**
  6850. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  6851. */
  6852. Scalar.Lerp = function (start, end, amount) {
  6853. return start + ((end - start) * amount);
  6854. };
  6855. /**
  6856. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  6857. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  6858. */
  6859. Scalar.LerpAngle = function (start, end, amount) {
  6860. var num = Scalar.Repeat(end - start, 360.0);
  6861. if (num > 180.0) {
  6862. num -= 360.0;
  6863. }
  6864. return start + num * Scalar.Clamp(amount);
  6865. };
  6866. /**
  6867. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  6868. */
  6869. Scalar.InverseLerp = function (a, b, value) {
  6870. var result = 0;
  6871. if (a != b) {
  6872. result = Scalar.Clamp((value - a) / (b - a));
  6873. }
  6874. else {
  6875. result = 0.0;
  6876. }
  6877. return result;
  6878. };
  6879. /**
  6880. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  6881. */
  6882. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  6883. var squared = amount * amount;
  6884. var cubed = amount * squared;
  6885. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  6886. var part2 = (-2.0 * cubed) + (3.0 * squared);
  6887. var part3 = (cubed - (2.0 * squared)) + amount;
  6888. var part4 = cubed - squared;
  6889. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  6890. };
  6891. /**
  6892. * Returns a random float number between and min and max values
  6893. */
  6894. Scalar.RandomRange = function (min, max) {
  6895. if (min === max)
  6896. return min;
  6897. return ((Math.random() * (max - min)) + min);
  6898. };
  6899. /**
  6900. * This function returns percentage of a number in a given range.
  6901. *
  6902. * RangeToPercent(40,20,60) will return 0.5 (50%)
  6903. * RangeToPercent(34,0,100) will return 0.34 (34%)
  6904. */
  6905. Scalar.RangeToPercent = function (number, min, max) {
  6906. return ((number - min) / (max - min));
  6907. };
  6908. /**
  6909. * This function returns number that corresponds to the percentage in a given range.
  6910. *
  6911. * PercentToRange(0.34,0,100) will return 34.
  6912. */
  6913. Scalar.PercentToRange = function (percent, min, max) {
  6914. return ((max - min) * percent + min);
  6915. };
  6916. /**
  6917. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  6918. * @param angle The angle to normalize in radian.
  6919. * @return The converted angle.
  6920. */
  6921. Scalar.NormalizeRadians = function (angle) {
  6922. // More precise but slower version kept for reference.
  6923. // angle = angle % Tools.TwoPi;
  6924. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  6925. //if (angle > Math.PI) {
  6926. // angle -= Tools.TwoPi;
  6927. //}
  6928. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  6929. return angle;
  6930. };
  6931. /**
  6932. * Two pi constants convenient for computation.
  6933. */
  6934. Scalar.TwoPi = Math.PI * 2;
  6935. return Scalar;
  6936. }());
  6937. BABYLON.Scalar = Scalar;
  6938. })(BABYLON || (BABYLON = {}));
  6939. //# sourceMappingURL=babylon.math.scalar.js.map
  6940. //# sourceMappingURL=babylon.mixins.js.map
  6941. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  6942. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  6943. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  6944. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  6945. //# sourceMappingURL=babylon.webgl2.js.map
  6946. var BABYLON;
  6947. (function (BABYLON) {
  6948. var __decoratorInitialStore = {};
  6949. var __mergedStore = {};
  6950. var _copySource = function (creationFunction, source, instanciate) {
  6951. var destination = creationFunction();
  6952. // Tags
  6953. if (BABYLON.Tags) {
  6954. BABYLON.Tags.AddTagsTo(destination, source.tags);
  6955. }
  6956. var classStore = getMergedStore(destination);
  6957. // Properties
  6958. for (var property in classStore) {
  6959. var propertyDescriptor = classStore[property];
  6960. var sourceProperty = source[property];
  6961. var propertyType = propertyDescriptor.type;
  6962. if (sourceProperty !== undefined && sourceProperty !== null) {
  6963. switch (propertyType) {
  6964. case 0: // Value
  6965. case 6:// Mesh reference
  6966. destination[property] = sourceProperty;
  6967. break;
  6968. case 1:// Texture
  6969. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  6970. break;
  6971. case 2: // Color3
  6972. case 3: // FresnelParameters
  6973. case 4: // Vector2
  6974. case 5: // Vector3
  6975. case 7: // Color Curves
  6976. case 10:// Quaternion
  6977. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  6978. break;
  6979. }
  6980. }
  6981. }
  6982. return destination;
  6983. };
  6984. function getDirectStore(target) {
  6985. var classKey = target.getClassName();
  6986. if (!__decoratorInitialStore[classKey]) {
  6987. __decoratorInitialStore[classKey] = {};
  6988. }
  6989. return __decoratorInitialStore[classKey];
  6990. }
  6991. /**
  6992. * Return the list of properties flagged as serializable
  6993. * @param target: host object
  6994. */
  6995. function getMergedStore(target) {
  6996. var classKey = target.getClassName();
  6997. if (__mergedStore[classKey]) {
  6998. return __mergedStore[classKey];
  6999. }
  7000. __mergedStore[classKey] = {};
  7001. var store = __mergedStore[classKey];
  7002. var currentTarget = target;
  7003. var currentKey = classKey;
  7004. while (currentKey) {
  7005. var initialStore = __decoratorInitialStore[currentKey];
  7006. for (var property in initialStore) {
  7007. store[property] = initialStore[property];
  7008. }
  7009. var parent_1 = void 0;
  7010. var done = false;
  7011. do {
  7012. parent_1 = Object.getPrototypeOf(currentTarget);
  7013. if (!parent_1.getClassName) {
  7014. done = true;
  7015. break;
  7016. }
  7017. if (parent_1.getClassName() !== currentKey) {
  7018. break;
  7019. }
  7020. currentTarget = parent_1;
  7021. } while (parent_1);
  7022. if (done) {
  7023. break;
  7024. }
  7025. currentKey = parent_1.getClassName();
  7026. currentTarget = parent_1;
  7027. }
  7028. return store;
  7029. }
  7030. function generateSerializableMember(type, sourceName) {
  7031. return function (target, propertyKey) {
  7032. var classStore = getDirectStore(target);
  7033. if (!classStore[propertyKey]) {
  7034. classStore[propertyKey] = { type: type, sourceName: sourceName };
  7035. }
  7036. };
  7037. }
  7038. function generateExpandMember(setCallback, targetKey) {
  7039. if (targetKey === void 0) { targetKey = null; }
  7040. return function (target, propertyKey) {
  7041. var key = targetKey || ("_" + propertyKey);
  7042. Object.defineProperty(target, propertyKey, {
  7043. get: function () {
  7044. return this[key];
  7045. },
  7046. set: function (value) {
  7047. if (this[key] === value) {
  7048. return;
  7049. }
  7050. this[key] = value;
  7051. target[setCallback].apply(this);
  7052. },
  7053. enumerable: true,
  7054. configurable: true
  7055. });
  7056. };
  7057. }
  7058. function expandToProperty(callback, targetKey) {
  7059. if (targetKey === void 0) { targetKey = null; }
  7060. return generateExpandMember(callback, targetKey);
  7061. }
  7062. BABYLON.expandToProperty = expandToProperty;
  7063. function serialize(sourceName) {
  7064. return generateSerializableMember(0, sourceName); // value member
  7065. }
  7066. BABYLON.serialize = serialize;
  7067. function serializeAsTexture(sourceName) {
  7068. return generateSerializableMember(1, sourceName); // texture member
  7069. }
  7070. BABYLON.serializeAsTexture = serializeAsTexture;
  7071. function serializeAsColor3(sourceName) {
  7072. return generateSerializableMember(2, sourceName); // color3 member
  7073. }
  7074. BABYLON.serializeAsColor3 = serializeAsColor3;
  7075. function serializeAsFresnelParameters(sourceName) {
  7076. return generateSerializableMember(3, sourceName); // fresnel parameters member
  7077. }
  7078. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  7079. function serializeAsVector2(sourceName) {
  7080. return generateSerializableMember(4, sourceName); // vector2 member
  7081. }
  7082. BABYLON.serializeAsVector2 = serializeAsVector2;
  7083. function serializeAsVector3(sourceName) {
  7084. return generateSerializableMember(5, sourceName); // vector3 member
  7085. }
  7086. BABYLON.serializeAsVector3 = serializeAsVector3;
  7087. function serializeAsMeshReference(sourceName) {
  7088. return generateSerializableMember(6, sourceName); // mesh reference member
  7089. }
  7090. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  7091. function serializeAsColorCurves(sourceName) {
  7092. return generateSerializableMember(7, sourceName); // color curves
  7093. }
  7094. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  7095. function serializeAsColor4(sourceName) {
  7096. return generateSerializableMember(8, sourceName); // color 4
  7097. }
  7098. BABYLON.serializeAsColor4 = serializeAsColor4;
  7099. function serializeAsImageProcessingConfiguration(sourceName) {
  7100. return generateSerializableMember(9, sourceName); // image processing
  7101. }
  7102. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  7103. function serializeAsQuaternion(sourceName) {
  7104. return generateSerializableMember(10, sourceName); // quaternion member
  7105. }
  7106. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  7107. var SerializationHelper = /** @class */ (function () {
  7108. function SerializationHelper() {
  7109. }
  7110. SerializationHelper.Serialize = function (entity, serializationObject) {
  7111. if (!serializationObject) {
  7112. serializationObject = {};
  7113. }
  7114. // Tags
  7115. if (BABYLON.Tags) {
  7116. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  7117. }
  7118. var serializedProperties = getMergedStore(entity);
  7119. // Properties
  7120. for (var property in serializedProperties) {
  7121. var propertyDescriptor = serializedProperties[property];
  7122. var targetPropertyName = propertyDescriptor.sourceName || property;
  7123. var propertyType = propertyDescriptor.type;
  7124. var sourceProperty = entity[property];
  7125. if (sourceProperty !== undefined && sourceProperty !== null) {
  7126. switch (propertyType) {
  7127. case 0:// Value
  7128. serializationObject[targetPropertyName] = sourceProperty;
  7129. break;
  7130. case 1:// Texture
  7131. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7132. break;
  7133. case 2:// Color3
  7134. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7135. break;
  7136. case 3:// FresnelParameters
  7137. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7138. break;
  7139. case 4:// Vector2
  7140. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7141. break;
  7142. case 5:// Vector3
  7143. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7144. break;
  7145. case 6:// Mesh reference
  7146. serializationObject[targetPropertyName] = sourceProperty.id;
  7147. break;
  7148. case 7:// Color Curves
  7149. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7150. break;
  7151. case 8:// Color 4
  7152. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7153. break;
  7154. case 9:// Image Processing
  7155. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7156. break;
  7157. }
  7158. }
  7159. }
  7160. return serializationObject;
  7161. };
  7162. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  7163. if (rootUrl === void 0) { rootUrl = null; }
  7164. var destination = creationFunction();
  7165. if (!rootUrl) {
  7166. rootUrl = "";
  7167. }
  7168. // Tags
  7169. if (BABYLON.Tags) {
  7170. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7171. }
  7172. var classStore = getMergedStore(destination);
  7173. // Properties
  7174. for (var property in classStore) {
  7175. var propertyDescriptor = classStore[property];
  7176. var sourceProperty = source[propertyDescriptor.sourceName || property];
  7177. var propertyType = propertyDescriptor.type;
  7178. if (sourceProperty !== undefined && sourceProperty !== null) {
  7179. var dest = destination;
  7180. switch (propertyType) {
  7181. case 0:// Value
  7182. dest[property] = sourceProperty;
  7183. break;
  7184. case 1:// Texture
  7185. if (scene) {
  7186. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  7187. }
  7188. break;
  7189. case 2:// Color3
  7190. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  7191. break;
  7192. case 3:// FresnelParameters
  7193. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  7194. break;
  7195. case 4:// Vector2
  7196. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  7197. break;
  7198. case 5:// Vector3
  7199. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  7200. break;
  7201. case 6:// Mesh reference
  7202. if (scene) {
  7203. dest[property] = scene.getLastMeshByID(sourceProperty);
  7204. }
  7205. break;
  7206. case 7:// Color Curves
  7207. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  7208. break;
  7209. case 8:// Color 4
  7210. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  7211. break;
  7212. case 9:// Image Processing
  7213. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  7214. break;
  7215. }
  7216. }
  7217. }
  7218. return destination;
  7219. };
  7220. SerializationHelper.Clone = function (creationFunction, source) {
  7221. return _copySource(creationFunction, source, false);
  7222. };
  7223. SerializationHelper.Instanciate = function (creationFunction, source) {
  7224. return _copySource(creationFunction, source, true);
  7225. };
  7226. return SerializationHelper;
  7227. }());
  7228. BABYLON.SerializationHelper = SerializationHelper;
  7229. })(BABYLON || (BABYLON = {}));
  7230. //# sourceMappingURL=babylon.decorators.js.map
  7231. var BABYLON;
  7232. (function (BABYLON) {
  7233. /**
  7234. * Wrapper class for promise with external resolve and reject.
  7235. */
  7236. var Deferred = /** @class */ (function () {
  7237. /**
  7238. * Constructor for this deferred object.
  7239. */
  7240. function Deferred() {
  7241. var _this = this;
  7242. this.promise = new Promise(function (resolve, reject) {
  7243. _this._resolve = resolve;
  7244. _this._reject = reject;
  7245. });
  7246. }
  7247. Object.defineProperty(Deferred.prototype, "resolve", {
  7248. /**
  7249. * The resolve method of the promise associated with this deferred object.
  7250. */
  7251. get: function () {
  7252. return this._resolve;
  7253. },
  7254. enumerable: true,
  7255. configurable: true
  7256. });
  7257. Object.defineProperty(Deferred.prototype, "reject", {
  7258. /**
  7259. * The reject method of the promise associated with this deferred object.
  7260. */
  7261. get: function () {
  7262. return this._reject;
  7263. },
  7264. enumerable: true,
  7265. configurable: true
  7266. });
  7267. return Deferred;
  7268. }());
  7269. BABYLON.Deferred = Deferred;
  7270. })(BABYLON || (BABYLON = {}));
  7271. //# sourceMappingURL=babylon.deferred.js.map
  7272. var BABYLON;
  7273. (function (BABYLON) {
  7274. /**
  7275. * A class serves as a medium between the observable and its observers
  7276. */
  7277. var EventState = /** @class */ (function () {
  7278. /**
  7279. * Create a new EventState
  7280. * @param mask defines the mask associated with this state
  7281. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7282. * @param target defines the original target of the state
  7283. * @param currentTarget defines the current target of the state
  7284. */
  7285. function EventState(mask, skipNextObservers, target, currentTarget) {
  7286. if (skipNextObservers === void 0) { skipNextObservers = false; }
  7287. this.initalize(mask, skipNextObservers, target, currentTarget);
  7288. }
  7289. /**
  7290. * Initialize the current event state
  7291. * @param mask defines the mask associated with this state
  7292. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7293. * @param target defines the original target of the state
  7294. * @param currentTarget defines the current target of the state
  7295. * @returns the current event state
  7296. */
  7297. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  7298. if (skipNextObservers === void 0) { skipNextObservers = false; }
  7299. this.mask = mask;
  7300. this.skipNextObservers = skipNextObservers;
  7301. this.target = target;
  7302. this.currentTarget = currentTarget;
  7303. return this;
  7304. };
  7305. return EventState;
  7306. }());
  7307. BABYLON.EventState = EventState;
  7308. /**
  7309. * Represent an Observer registered to a given Observable object.
  7310. */
  7311. var Observer = /** @class */ (function () {
  7312. /**
  7313. * Creates a new observer
  7314. * @param callback defines the callback to call when the observer is notified
  7315. * @param mask defines the mask of the observer (used to filter notifications)
  7316. * @param scope defines the current scope used to restore the JS context
  7317. */
  7318. function Observer(
  7319. /**
  7320. * Defines the callback to call when the observer is notified
  7321. */
  7322. callback,
  7323. /**
  7324. * Defines the mask of the observer (used to filter notifications)
  7325. */
  7326. mask,
  7327. /**
  7328. * Defines the current scope used to restore the JS context
  7329. */
  7330. scope) {
  7331. if (scope === void 0) { scope = null; }
  7332. this.callback = callback;
  7333. this.mask = mask;
  7334. this.scope = scope;
  7335. /** @ignore */
  7336. this._willBeUnregistered = false;
  7337. /**
  7338. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  7339. */
  7340. this.unregisterOnNextCall = false;
  7341. }
  7342. return Observer;
  7343. }());
  7344. BABYLON.Observer = Observer;
  7345. /**
  7346. * Represent a list of observers registered to multiple Observables object.
  7347. */
  7348. var MultiObserver = /** @class */ (function () {
  7349. function MultiObserver() {
  7350. }
  7351. /**
  7352. * Release associated resources
  7353. */
  7354. MultiObserver.prototype.dispose = function () {
  7355. if (this._observers && this._observables) {
  7356. for (var index = 0; index < this._observers.length; index++) {
  7357. this._observables[index].remove(this._observers[index]);
  7358. }
  7359. }
  7360. this._observers = null;
  7361. this._observables = null;
  7362. };
  7363. /**
  7364. * Raise a callback when one of the observable will notify
  7365. * @param observables defines a list of observables to watch
  7366. * @param callback defines the callback to call on notification
  7367. * @param mask defines the mask used to filter notifications
  7368. * @param scope defines the current scope used to restore the JS context
  7369. * @returns the new MultiObserver
  7370. */
  7371. MultiObserver.Watch = function (observables, callback, mask, scope) {
  7372. if (mask === void 0) { mask = -1; }
  7373. if (scope === void 0) { scope = null; }
  7374. var result = new MultiObserver();
  7375. result._observers = new Array();
  7376. result._observables = observables;
  7377. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  7378. var observable = observables_1[_i];
  7379. var observer = observable.add(callback, mask, false, scope);
  7380. if (observer) {
  7381. result._observers.push(observer);
  7382. }
  7383. }
  7384. return result;
  7385. };
  7386. return MultiObserver;
  7387. }());
  7388. BABYLON.MultiObserver = MultiObserver;
  7389. /**
  7390. * The Observable class is a simple implementation of the Observable pattern.
  7391. * 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.
  7392. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  7393. * 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).
  7394. * 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.
  7395. */
  7396. var Observable = /** @class */ (function () {
  7397. /**
  7398. * Creates a new observable
  7399. * @param onObserverAdded defines a callback to call when a new observer is added
  7400. */
  7401. function Observable(onObserverAdded) {
  7402. this._observers = new Array();
  7403. this._eventState = new EventState(0);
  7404. if (onObserverAdded) {
  7405. this._onObserverAdded = onObserverAdded;
  7406. }
  7407. }
  7408. /**
  7409. * Create a new Observer with the specified callback
  7410. * @param callback the callback that will be executed for that Observer
  7411. * @param mask the mask used to filter observers
  7412. * @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.
  7413. * @param scope optional scope for the callback to be called from
  7414. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  7415. * @returns the new observer created for the callback
  7416. */
  7417. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  7418. if (mask === void 0) { mask = -1; }
  7419. if (insertFirst === void 0) { insertFirst = false; }
  7420. if (scope === void 0) { scope = null; }
  7421. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  7422. if (!callback) {
  7423. return null;
  7424. }
  7425. var observer = new Observer(callback, mask, scope);
  7426. observer.unregisterOnNextCall = unregisterOnFirstCall;
  7427. if (insertFirst) {
  7428. this._observers.unshift(observer);
  7429. }
  7430. else {
  7431. this._observers.push(observer);
  7432. }
  7433. if (this._onObserverAdded) {
  7434. this._onObserverAdded(observer);
  7435. }
  7436. return observer;
  7437. };
  7438. /**
  7439. * Remove an Observer from the Observable object
  7440. * @param observer the instance of the Observer to remove
  7441. * @returns false if it doesn't belong to this Observable
  7442. */
  7443. Observable.prototype.remove = function (observer) {
  7444. if (!observer) {
  7445. return false;
  7446. }
  7447. var index = this._observers.indexOf(observer);
  7448. if (index !== -1) {
  7449. this._observers.splice(index, 1);
  7450. return true;
  7451. }
  7452. return false;
  7453. };
  7454. /**
  7455. * Remove a callback from the Observable object
  7456. * @param callback the callback to remove
  7457. * @param scope optional scope. If used only the callbacks with this scope will be removed
  7458. * @returns false if it doesn't belong to this Observable
  7459. */
  7460. Observable.prototype.removeCallback = function (callback, scope) {
  7461. for (var index = 0; index < this._observers.length; index++) {
  7462. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  7463. this._observers.splice(index, 1);
  7464. return true;
  7465. }
  7466. }
  7467. return false;
  7468. };
  7469. Observable.prototype._deferUnregister = function (observer) {
  7470. var _this = this;
  7471. observer.unregisterOnNextCall = false;
  7472. observer._willBeUnregistered = true;
  7473. BABYLON.Tools.SetImmediate(function () {
  7474. _this.remove(observer);
  7475. });
  7476. };
  7477. /**
  7478. * Notify all Observers by calling their respective callback with the given data
  7479. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  7480. * @param eventData defines the data to send to all observers
  7481. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  7482. * @param target defines the original target of the state
  7483. * @param currentTarget defines the current target of the state
  7484. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  7485. */
  7486. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  7487. if (mask === void 0) { mask = -1; }
  7488. if (!this._observers.length) {
  7489. return true;
  7490. }
  7491. var state = this._eventState;
  7492. state.mask = mask;
  7493. state.target = target;
  7494. state.currentTarget = currentTarget;
  7495. state.skipNextObservers = false;
  7496. state.lastReturnValue = eventData;
  7497. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  7498. var obs = _a[_i];
  7499. if (obs._willBeUnregistered) {
  7500. continue;
  7501. }
  7502. if (obs.mask & mask) {
  7503. if (obs.scope) {
  7504. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  7505. }
  7506. else {
  7507. state.lastReturnValue = obs.callback(eventData, state);
  7508. }
  7509. if (obs.unregisterOnNextCall) {
  7510. this._deferUnregister(obs);
  7511. }
  7512. }
  7513. if (state.skipNextObservers) {
  7514. return false;
  7515. }
  7516. }
  7517. return true;
  7518. };
  7519. /**
  7520. * Calling this will execute each callback, expecting it to be a promise or return a value.
  7521. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  7522. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  7523. * and it is crucial that all callbacks will be executed.
  7524. * The order of the callbacks is kept, callbacks are not executed parallel.
  7525. *
  7526. * @param eventData The data to be sent to each callback
  7527. * @param mask is used to filter observers defaults to -1
  7528. * @param target defines the callback target (see EventState)
  7529. * @param currentTarget defines he current object in the bubbling phase
  7530. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  7531. */
  7532. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  7533. var _this = this;
  7534. if (mask === void 0) { mask = -1; }
  7535. // create an empty promise
  7536. var p = Promise.resolve(eventData);
  7537. // no observers? return this promise.
  7538. if (!this._observers.length) {
  7539. return p;
  7540. }
  7541. var state = this._eventState;
  7542. state.mask = mask;
  7543. state.target = target;
  7544. state.currentTarget = currentTarget;
  7545. state.skipNextObservers = false;
  7546. // execute one callback after another (not using Promise.all, the order is important)
  7547. this._observers.forEach(function (obs) {
  7548. if (state.skipNextObservers) {
  7549. return;
  7550. }
  7551. if (obs._willBeUnregistered) {
  7552. return;
  7553. }
  7554. if (obs.mask & mask) {
  7555. if (obs.scope) {
  7556. p = p.then(function (lastReturnedValue) {
  7557. state.lastReturnValue = lastReturnedValue;
  7558. return obs.callback.apply(obs.scope, [eventData, state]);
  7559. });
  7560. }
  7561. else {
  7562. p = p.then(function (lastReturnedValue) {
  7563. state.lastReturnValue = lastReturnedValue;
  7564. return obs.callback(eventData, state);
  7565. });
  7566. }
  7567. if (obs.unregisterOnNextCall) {
  7568. _this._deferUnregister(obs);
  7569. }
  7570. }
  7571. });
  7572. // return the eventData
  7573. return p.then(function () { return eventData; });
  7574. };
  7575. /**
  7576. * Notify a specific observer
  7577. * @param observer defines the observer to notify
  7578. * @param eventData defines the data to be sent to each callback
  7579. * @param mask is used to filter observers defaults to -1
  7580. */
  7581. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  7582. if (mask === void 0) { mask = -1; }
  7583. var state = this._eventState;
  7584. state.mask = mask;
  7585. state.skipNextObservers = false;
  7586. observer.callback(eventData, state);
  7587. };
  7588. /**
  7589. * Gets a boolean indicating if the observable has at least one observer
  7590. * @returns true is the Observable has at least one Observer registered
  7591. */
  7592. Observable.prototype.hasObservers = function () {
  7593. return this._observers.length > 0;
  7594. };
  7595. /**
  7596. * Clear the list of observers
  7597. */
  7598. Observable.prototype.clear = function () {
  7599. this._observers = new Array();
  7600. this._onObserverAdded = null;
  7601. };
  7602. /**
  7603. * Clone the current observable
  7604. * @returns a new observable
  7605. */
  7606. Observable.prototype.clone = function () {
  7607. var result = new Observable();
  7608. result._observers = this._observers.slice(0);
  7609. return result;
  7610. };
  7611. /**
  7612. * Does this observable handles observer registered with a given mask
  7613. * @param mask defines the mask to be tested
  7614. * @return whether or not one observer registered with the given mask is handeled
  7615. **/
  7616. Observable.prototype.hasSpecificMask = function (mask) {
  7617. if (mask === void 0) { mask = -1; }
  7618. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  7619. var obs = _a[_i];
  7620. if (obs.mask & mask || obs.mask === mask) {
  7621. return true;
  7622. }
  7623. }
  7624. return false;
  7625. };
  7626. return Observable;
  7627. }());
  7628. BABYLON.Observable = Observable;
  7629. })(BABYLON || (BABYLON = {}));
  7630. //# sourceMappingURL=babylon.observable.js.map
  7631. var BABYLON;
  7632. (function (BABYLON) {
  7633. var SmartArray = /** @class */ (function () {
  7634. function SmartArray(capacity) {
  7635. this.length = 0;
  7636. this.data = new Array(capacity);
  7637. this._id = SmartArray._GlobalId++;
  7638. }
  7639. SmartArray.prototype.push = function (value) {
  7640. this.data[this.length++] = value;
  7641. if (this.length > this.data.length) {
  7642. this.data.length *= 2;
  7643. }
  7644. };
  7645. SmartArray.prototype.forEach = function (func) {
  7646. for (var index = 0; index < this.length; index++) {
  7647. func(this.data[index]);
  7648. }
  7649. };
  7650. SmartArray.prototype.sort = function (compareFn) {
  7651. this.data.sort(compareFn);
  7652. };
  7653. SmartArray.prototype.reset = function () {
  7654. this.length = 0;
  7655. };
  7656. SmartArray.prototype.dispose = function () {
  7657. this.reset();
  7658. if (this.data) {
  7659. this.data.length = 0;
  7660. this.data = [];
  7661. }
  7662. };
  7663. SmartArray.prototype.concat = function (array) {
  7664. if (array.length === 0) {
  7665. return;
  7666. }
  7667. if (this.length + array.length > this.data.length) {
  7668. this.data.length = (this.length + array.length) * 2;
  7669. }
  7670. for (var index = 0; index < array.length; index++) {
  7671. this.data[this.length++] = (array.data || array)[index];
  7672. }
  7673. };
  7674. SmartArray.prototype.indexOf = function (value) {
  7675. var position = this.data.indexOf(value);
  7676. if (position >= this.length) {
  7677. return -1;
  7678. }
  7679. return position;
  7680. };
  7681. SmartArray.prototype.contains = function (value) {
  7682. return this.data.indexOf(value) !== -1;
  7683. };
  7684. // Statics
  7685. SmartArray._GlobalId = 0;
  7686. return SmartArray;
  7687. }());
  7688. BABYLON.SmartArray = SmartArray;
  7689. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  7690. __extends(SmartArrayNoDuplicate, _super);
  7691. function SmartArrayNoDuplicate() {
  7692. var _this = _super !== null && _super.apply(this, arguments) || this;
  7693. _this._duplicateId = 0;
  7694. return _this;
  7695. }
  7696. SmartArrayNoDuplicate.prototype.push = function (value) {
  7697. _super.prototype.push.call(this, value);
  7698. if (!value.__smartArrayFlags) {
  7699. value.__smartArrayFlags = {};
  7700. }
  7701. value.__smartArrayFlags[this._id] = this._duplicateId;
  7702. };
  7703. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  7704. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  7705. return false;
  7706. }
  7707. this.push(value);
  7708. return true;
  7709. };
  7710. SmartArrayNoDuplicate.prototype.reset = function () {
  7711. _super.prototype.reset.call(this);
  7712. this._duplicateId++;
  7713. };
  7714. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  7715. if (array.length === 0) {
  7716. return;
  7717. }
  7718. if (this.length + array.length > this.data.length) {
  7719. this.data.length = (this.length + array.length) * 2;
  7720. }
  7721. for (var index = 0; index < array.length; index++) {
  7722. var item = (array.data || array)[index];
  7723. this.pushNoDuplicate(item);
  7724. }
  7725. };
  7726. return SmartArrayNoDuplicate;
  7727. }(SmartArray));
  7728. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  7729. })(BABYLON || (BABYLON = {}));
  7730. //# sourceMappingURL=babylon.smartArray.js.map
  7731. var BABYLON;
  7732. (function (BABYLON) {
  7733. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  7734. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  7735. var LoadFileError = /** @class */ (function (_super) {
  7736. __extends(LoadFileError, _super);
  7737. function LoadFileError(message, request) {
  7738. var _this = _super.call(this, message) || this;
  7739. _this.request = request;
  7740. _this.name = "LoadFileError";
  7741. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  7742. return _this;
  7743. }
  7744. // Polyfill for Object.setPrototypeOf if necessary.
  7745. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  7746. return LoadFileError;
  7747. }(Error));
  7748. BABYLON.LoadFileError = LoadFileError;
  7749. var RetryStrategy = /** @class */ (function () {
  7750. function RetryStrategy() {
  7751. }
  7752. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  7753. if (maxRetries === void 0) { maxRetries = 3; }
  7754. if (baseInterval === void 0) { baseInterval = 500; }
  7755. return function (url, request, retryIndex) {
  7756. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  7757. return -1;
  7758. }
  7759. return Math.pow(2, retryIndex) * baseInterval;
  7760. };
  7761. };
  7762. return RetryStrategy;
  7763. }());
  7764. BABYLON.RetryStrategy = RetryStrategy;
  7765. // Screenshots
  7766. var screenshotCanvas;
  7767. var cloneValue = function (source, destinationObject) {
  7768. if (!source)
  7769. return null;
  7770. if (source instanceof BABYLON.Mesh) {
  7771. return null;
  7772. }
  7773. if (source instanceof BABYLON.SubMesh) {
  7774. return source.clone(destinationObject);
  7775. }
  7776. else if (source.clone) {
  7777. return source.clone();
  7778. }
  7779. return null;
  7780. };
  7781. var Tools = /** @class */ (function () {
  7782. function Tools() {
  7783. }
  7784. /**
  7785. * Interpolates between a and b via alpha
  7786. * @param a The lower value (returned when alpha = 0)
  7787. * @param b The upper value (returned when alpha = 1)
  7788. * @param alpha The interpolation-factor
  7789. * @return The mixed value
  7790. */
  7791. Tools.Mix = function (a, b, alpha) {
  7792. return a * (1 - alpha) + b * alpha;
  7793. };
  7794. Tools.Instantiate = function (className) {
  7795. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  7796. return Tools.RegisteredExternalClasses[className];
  7797. }
  7798. var arr = className.split(".");
  7799. var fn = (window || this);
  7800. for (var i = 0, len = arr.length; i < len; i++) {
  7801. fn = fn[arr[i]];
  7802. }
  7803. if (typeof fn !== "function") {
  7804. return null;
  7805. }
  7806. return fn;
  7807. };
  7808. /**
  7809. * Provides a slice function that will work even on IE
  7810. * @param data defines the array to slice
  7811. * @returns the new sliced array
  7812. */
  7813. Tools.Slice = function (data) {
  7814. if (data.slice) {
  7815. return data.slice();
  7816. }
  7817. return Array.prototype.slice.call(data);
  7818. };
  7819. Tools.SetImmediate = function (action) {
  7820. if (window.setImmediate) {
  7821. window.setImmediate(action);
  7822. }
  7823. else {
  7824. setTimeout(action, 1);
  7825. }
  7826. };
  7827. Tools.IsExponentOfTwo = function (value) {
  7828. var count = 1;
  7829. do {
  7830. count *= 2;
  7831. } while (count < value);
  7832. return count === value;
  7833. };
  7834. /**
  7835. * Find the next highest power of two.
  7836. * @param x Number to start search from.
  7837. * @return Next highest power of two.
  7838. */
  7839. Tools.CeilingPOT = function (x) {
  7840. x--;
  7841. x |= x >> 1;
  7842. x |= x >> 2;
  7843. x |= x >> 4;
  7844. x |= x >> 8;
  7845. x |= x >> 16;
  7846. x++;
  7847. return x;
  7848. };
  7849. /**
  7850. * Find the next lowest power of two.
  7851. * @param x Number to start search from.
  7852. * @return Next lowest power of two.
  7853. */
  7854. Tools.FloorPOT = function (x) {
  7855. x = x | (x >> 1);
  7856. x = x | (x >> 2);
  7857. x = x | (x >> 4);
  7858. x = x | (x >> 8);
  7859. x = x | (x >> 16);
  7860. return x - (x >> 1);
  7861. };
  7862. /**
  7863. * Find the nearest power of two.
  7864. * @param x Number to start search from.
  7865. * @return Next nearest power of two.
  7866. */
  7867. Tools.NearestPOT = function (x) {
  7868. var c = Tools.CeilingPOT(x);
  7869. var f = Tools.FloorPOT(x);
  7870. return (c - x) > (x - f) ? f : c;
  7871. };
  7872. Tools.GetExponentOfTwo = function (value, max, mode) {
  7873. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  7874. var pot;
  7875. switch (mode) {
  7876. case BABYLON.Engine.SCALEMODE_FLOOR:
  7877. pot = Tools.FloorPOT(value);
  7878. break;
  7879. case BABYLON.Engine.SCALEMODE_NEAREST:
  7880. pot = Tools.NearestPOT(value);
  7881. break;
  7882. case BABYLON.Engine.SCALEMODE_CEILING:
  7883. default:
  7884. pot = Tools.CeilingPOT(value);
  7885. break;
  7886. }
  7887. return Math.min(pot, max);
  7888. };
  7889. Tools.GetFilename = function (path) {
  7890. var index = path.lastIndexOf("/");
  7891. if (index < 0)
  7892. return path;
  7893. return path.substring(index + 1);
  7894. };
  7895. /**
  7896. * Extracts the "folder" part of a path (everything before the filename).
  7897. * @param uri The URI to extract the info from
  7898. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  7899. * @returns The "folder" part of the path
  7900. */
  7901. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  7902. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  7903. var index = uri.lastIndexOf("/");
  7904. if (index < 0) {
  7905. if (returnUnchangedIfNoSlash) {
  7906. return uri;
  7907. }
  7908. return "";
  7909. }
  7910. return uri.substring(0, index + 1);
  7911. };
  7912. Tools.GetDOMTextContent = function (element) {
  7913. var result = "";
  7914. var child = element.firstChild;
  7915. while (child) {
  7916. if (child.nodeType === 3) {
  7917. result += child.textContent;
  7918. }
  7919. child = child.nextSibling;
  7920. }
  7921. return result;
  7922. };
  7923. Tools.ToDegrees = function (angle) {
  7924. return angle * 180 / Math.PI;
  7925. };
  7926. Tools.ToRadians = function (angle) {
  7927. return angle * Math.PI / 180;
  7928. };
  7929. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  7930. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  7931. var output = "";
  7932. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  7933. var i = 0;
  7934. var bytes = new Uint8Array(buffer);
  7935. while (i < bytes.length) {
  7936. chr1 = bytes[i++];
  7937. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  7938. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  7939. enc1 = chr1 >> 2;
  7940. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  7941. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  7942. enc4 = chr3 & 63;
  7943. if (isNaN(chr2)) {
  7944. enc3 = enc4 = 64;
  7945. }
  7946. else if (isNaN(chr3)) {
  7947. enc4 = 64;
  7948. }
  7949. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  7950. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  7951. }
  7952. return "data:image/png;base64," + output;
  7953. };
  7954. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  7955. if (bias === void 0) { bias = null; }
  7956. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7957. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  7958. for (var index = indexStart; index < indexStart + indexCount; index++) {
  7959. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  7960. minimum = BABYLON.Vector3.Minimize(current, minimum);
  7961. maximum = BABYLON.Vector3.Maximize(current, maximum);
  7962. }
  7963. if (bias) {
  7964. minimum.x -= minimum.x * bias.x + bias.y;
  7965. minimum.y -= minimum.y * bias.x + bias.y;
  7966. minimum.z -= minimum.z * bias.x + bias.y;
  7967. maximum.x += maximum.x * bias.x + bias.y;
  7968. maximum.y += maximum.y * bias.x + bias.y;
  7969. maximum.z += maximum.z * bias.x + bias.y;
  7970. }
  7971. return {
  7972. minimum: minimum,
  7973. maximum: maximum
  7974. };
  7975. };
  7976. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  7977. if (bias === void 0) { bias = null; }
  7978. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7979. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  7980. if (!stride) {
  7981. stride = 3;
  7982. }
  7983. for (var index = start; index < start + count; index++) {
  7984. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  7985. minimum = BABYLON.Vector3.Minimize(current, minimum);
  7986. maximum = BABYLON.Vector3.Maximize(current, maximum);
  7987. }
  7988. if (bias) {
  7989. minimum.x -= minimum.x * bias.x + bias.y;
  7990. minimum.y -= minimum.y * bias.x + bias.y;
  7991. minimum.z -= minimum.z * bias.x + bias.y;
  7992. maximum.x += maximum.x * bias.x + bias.y;
  7993. maximum.y += maximum.y * bias.x + bias.y;
  7994. maximum.z += maximum.z * bias.x + bias.y;
  7995. }
  7996. return {
  7997. minimum: minimum,
  7998. maximum: maximum
  7999. };
  8000. };
  8001. Tools.Vector2ArrayFeeder = function (array) {
  8002. return function (index) {
  8003. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  8004. var length = isFloatArray ? array.length / 2 : array.length;
  8005. if (index >= length) {
  8006. return null;
  8007. }
  8008. if (isFloatArray) {
  8009. var fa = array;
  8010. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  8011. }
  8012. var a = array;
  8013. return a[index];
  8014. };
  8015. };
  8016. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  8017. if (bias === void 0) { bias = null; }
  8018. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  8019. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  8020. var i = 0;
  8021. var cur = feeder(i++);
  8022. while (cur) {
  8023. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  8024. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  8025. cur = feeder(i++);
  8026. }
  8027. if (bias) {
  8028. minimum.x -= minimum.x * bias.x + bias.y;
  8029. minimum.y -= minimum.y * bias.x + bias.y;
  8030. maximum.x += maximum.x * bias.x + bias.y;
  8031. maximum.y += maximum.y * bias.x + bias.y;
  8032. }
  8033. return {
  8034. minimum: minimum,
  8035. maximum: maximum
  8036. };
  8037. };
  8038. Tools.MakeArray = function (obj, allowsNullUndefined) {
  8039. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  8040. return null;
  8041. return Array.isArray(obj) ? obj : [obj];
  8042. };
  8043. // Misc.
  8044. Tools.GetPointerPrefix = function () {
  8045. var eventPrefix = "pointer";
  8046. // Check if pointer events are supported
  8047. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  8048. eventPrefix = "mouse";
  8049. }
  8050. return eventPrefix;
  8051. };
  8052. /**
  8053. * @param func - the function to be called
  8054. * @param requester - the object that will request the next frame. Falls back to window.
  8055. */
  8056. Tools.QueueNewFrame = function (func, requester) {
  8057. if (!Tools.IsWindowObjectExist()) {
  8058. return setTimeout(func, 16);
  8059. }
  8060. if (!requester) {
  8061. requester = window;
  8062. }
  8063. if (requester.requestAnimationFrame) {
  8064. return requester.requestAnimationFrame(func);
  8065. }
  8066. else if (requester.msRequestAnimationFrame) {
  8067. return requester.msRequestAnimationFrame(func);
  8068. }
  8069. else if (requester.webkitRequestAnimationFrame) {
  8070. return requester.webkitRequestAnimationFrame(func);
  8071. }
  8072. else if (requester.mozRequestAnimationFrame) {
  8073. return requester.mozRequestAnimationFrame(func);
  8074. }
  8075. else if (requester.oRequestAnimationFrame) {
  8076. return requester.oRequestAnimationFrame(func);
  8077. }
  8078. else {
  8079. return window.setTimeout(func, 16);
  8080. }
  8081. };
  8082. Tools.RequestFullscreen = function (element) {
  8083. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  8084. if (!requestFunction)
  8085. return;
  8086. requestFunction.call(element);
  8087. };
  8088. Tools.ExitFullscreen = function () {
  8089. if (document.exitFullscreen) {
  8090. document.exitFullscreen();
  8091. }
  8092. else if (document.mozCancelFullScreen) {
  8093. document.mozCancelFullScreen();
  8094. }
  8095. else if (document.webkitCancelFullScreen) {
  8096. document.webkitCancelFullScreen();
  8097. }
  8098. else if (document.msCancelFullScreen) {
  8099. document.msCancelFullScreen();
  8100. }
  8101. };
  8102. Tools.SetCorsBehavior = function (url, element) {
  8103. if (url && url.indexOf("data:") === 0) {
  8104. return;
  8105. }
  8106. if (Tools.CorsBehavior) {
  8107. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  8108. element.crossOrigin = Tools.CorsBehavior;
  8109. }
  8110. else {
  8111. var result = Tools.CorsBehavior(url);
  8112. if (result) {
  8113. element.crossOrigin = result;
  8114. }
  8115. }
  8116. }
  8117. };
  8118. // External files
  8119. Tools.CleanUrl = function (url) {
  8120. url = url.replace(/#/mg, "%23");
  8121. return url;
  8122. };
  8123. Tools.LoadImage = function (url, onLoad, onError, database) {
  8124. if (url instanceof ArrayBuffer) {
  8125. url = Tools.EncodeArrayBufferTobase64(url);
  8126. }
  8127. url = Tools.CleanUrl(url);
  8128. url = Tools.PreprocessUrl(url);
  8129. var img = new Image();
  8130. Tools.SetCorsBehavior(url, img);
  8131. var loadHandler = function () {
  8132. img.removeEventListener("load", loadHandler);
  8133. img.removeEventListener("error", errorHandler);
  8134. onLoad(img);
  8135. };
  8136. var errorHandler = function (err) {
  8137. img.removeEventListener("load", loadHandler);
  8138. img.removeEventListener("error", errorHandler);
  8139. Tools.Error("Error while trying to load image: " + url);
  8140. if (onError) {
  8141. onError("Error while trying to load image: " + url, err);
  8142. }
  8143. };
  8144. img.addEventListener("load", loadHandler);
  8145. img.addEventListener("error", errorHandler);
  8146. var noIndexedDB = function () {
  8147. img.src = url;
  8148. };
  8149. var loadFromIndexedDB = function () {
  8150. if (database) {
  8151. database.loadImageFromDB(url, img);
  8152. }
  8153. };
  8154. //ANY database to do!
  8155. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  8156. database.openAsync(loadFromIndexedDB, noIndexedDB);
  8157. }
  8158. else {
  8159. if (url.indexOf("file:") !== -1) {
  8160. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  8161. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  8162. try {
  8163. var blobURL;
  8164. try {
  8165. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  8166. }
  8167. catch (ex) {
  8168. // Chrome doesn't support oneTimeOnly parameter
  8169. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  8170. }
  8171. img.src = blobURL;
  8172. }
  8173. catch (e) {
  8174. img.src = "";
  8175. }
  8176. return img;
  8177. }
  8178. }
  8179. noIndexedDB();
  8180. }
  8181. return img;
  8182. };
  8183. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  8184. url = Tools.CleanUrl(url);
  8185. url = Tools.PreprocessUrl(url);
  8186. // If file and file input are set
  8187. if (url.indexOf("file:") !== -1) {
  8188. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  8189. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  8190. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  8191. }
  8192. }
  8193. var loadUrl = Tools.BaseUrl + url;
  8194. var aborted = false;
  8195. var fileRequest = {
  8196. onCompleteObservable: new BABYLON.Observable(),
  8197. abort: function () { return aborted = true; },
  8198. };
  8199. var requestFile = function () {
  8200. var request = new XMLHttpRequest();
  8201. var retryHandle = null;
  8202. fileRequest.abort = function () {
  8203. aborted = true;
  8204. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  8205. request.abort();
  8206. }
  8207. if (retryHandle !== null) {
  8208. clearTimeout(retryHandle);
  8209. retryHandle = null;
  8210. }
  8211. };
  8212. var retryLoop = function (retryIndex) {
  8213. request.open('GET', loadUrl, true);
  8214. if (useArrayBuffer) {
  8215. request.responseType = "arraybuffer";
  8216. }
  8217. if (onProgress) {
  8218. request.addEventListener("progress", onProgress);
  8219. }
  8220. var onLoadEnd = function () {
  8221. request.removeEventListener("loadend", onLoadEnd);
  8222. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8223. fileRequest.onCompleteObservable.clear();
  8224. };
  8225. request.addEventListener("loadend", onLoadEnd);
  8226. var onReadyStateChange = function () {
  8227. if (aborted) {
  8228. return;
  8229. }
  8230. // In case of undefined state in some browsers.
  8231. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  8232. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  8233. request.removeEventListener("readystatechange", onReadyStateChange);
  8234. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  8235. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  8236. return;
  8237. }
  8238. var retryStrategy = Tools.DefaultRetryStrategy;
  8239. if (retryStrategy) {
  8240. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  8241. if (waitTime !== -1) {
  8242. // Prevent the request from completing for retry.
  8243. request.removeEventListener("loadend", onLoadEnd);
  8244. request = new XMLHttpRequest();
  8245. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  8246. return;
  8247. }
  8248. }
  8249. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  8250. if (onError) {
  8251. onError(request, e);
  8252. }
  8253. else {
  8254. throw e;
  8255. }
  8256. }
  8257. };
  8258. request.addEventListener("readystatechange", onReadyStateChange);
  8259. request.send();
  8260. };
  8261. retryLoop(0);
  8262. };
  8263. // Caching all files
  8264. if (database && database.enableSceneOffline) {
  8265. var noIndexedDB_1 = function () {
  8266. if (!aborted) {
  8267. requestFile();
  8268. }
  8269. };
  8270. var loadFromIndexedDB = function () {
  8271. // TODO: database needs to support aborting and should return a IFileRequest
  8272. if (aborted) {
  8273. return;
  8274. }
  8275. if (database) {
  8276. database.loadFileFromDB(url, function (data) {
  8277. if (!aborted) {
  8278. onSuccess(data);
  8279. }
  8280. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8281. }, onProgress ? function (event) {
  8282. if (!aborted) {
  8283. onProgress(event);
  8284. }
  8285. } : undefined, noIndexedDB_1, useArrayBuffer);
  8286. }
  8287. };
  8288. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  8289. }
  8290. else {
  8291. requestFile();
  8292. }
  8293. return fileRequest;
  8294. };
  8295. /**
  8296. * Load a script (identified by an url). When the url returns, the
  8297. * content of this file is added into a new script element, attached to the DOM (body element)
  8298. */
  8299. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  8300. var head = document.getElementsByTagName('head')[0];
  8301. var script = document.createElement('script');
  8302. script.type = 'text/javascript';
  8303. script.src = scriptUrl;
  8304. script.onload = function () {
  8305. if (onSuccess) {
  8306. onSuccess();
  8307. }
  8308. };
  8309. script.onerror = function (e) {
  8310. if (onError) {
  8311. onError("Unable to load script", e);
  8312. }
  8313. };
  8314. head.appendChild(script);
  8315. };
  8316. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  8317. var reader = new FileReader();
  8318. var request = {
  8319. onCompleteObservable: new BABYLON.Observable(),
  8320. abort: function () { return reader.abort(); },
  8321. };
  8322. reader.onloadend = function (e) {
  8323. request.onCompleteObservable.notifyObservers(request);
  8324. };
  8325. reader.onload = function (e) {
  8326. //target doesn't have result from ts 1.3
  8327. callback(e.target['result']);
  8328. };
  8329. reader.onprogress = progressCallback;
  8330. reader.readAsDataURL(fileToLoad);
  8331. return request;
  8332. };
  8333. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  8334. var reader = new FileReader();
  8335. var request = {
  8336. onCompleteObservable: new BABYLON.Observable(),
  8337. abort: function () { return reader.abort(); },
  8338. };
  8339. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  8340. reader.onerror = function (e) {
  8341. Tools.Log("Error while reading file: " + fileToLoad.name);
  8342. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  8343. };
  8344. reader.onload = function (e) {
  8345. //target doesn't have result from ts 1.3
  8346. callback(e.target['result']);
  8347. };
  8348. if (progressCallBack) {
  8349. reader.onprogress = progressCallBack;
  8350. }
  8351. if (!useArrayBuffer) {
  8352. // Asynchronous read
  8353. reader.readAsText(fileToLoad);
  8354. }
  8355. else {
  8356. reader.readAsArrayBuffer(fileToLoad);
  8357. }
  8358. return request;
  8359. };
  8360. //returns a downloadable url to a file content.
  8361. Tools.FileAsURL = function (content) {
  8362. var fileBlob = new Blob([content]);
  8363. var url = window.URL || window.webkitURL;
  8364. var link = url.createObjectURL(fileBlob);
  8365. return link;
  8366. };
  8367. // Misc.
  8368. Tools.Format = function (value, decimals) {
  8369. if (decimals === void 0) { decimals = 2; }
  8370. return value.toFixed(decimals);
  8371. };
  8372. Tools.CheckExtends = function (v, min, max) {
  8373. if (v.x < min.x)
  8374. min.x = v.x;
  8375. if (v.y < min.y)
  8376. min.y = v.y;
  8377. if (v.z < min.z)
  8378. min.z = v.z;
  8379. if (v.x > max.x)
  8380. max.x = v.x;
  8381. if (v.y > max.y)
  8382. max.y = v.y;
  8383. if (v.z > max.z)
  8384. max.z = v.z;
  8385. };
  8386. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  8387. for (var prop in source) {
  8388. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  8389. continue;
  8390. }
  8391. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  8392. continue;
  8393. }
  8394. var sourceValue = source[prop];
  8395. var typeOfSourceValue = typeof sourceValue;
  8396. if (typeOfSourceValue === "function") {
  8397. continue;
  8398. }
  8399. if (typeOfSourceValue === "object") {
  8400. if (sourceValue instanceof Array) {
  8401. destination[prop] = [];
  8402. if (sourceValue.length > 0) {
  8403. if (typeof sourceValue[0] == "object") {
  8404. for (var index = 0; index < sourceValue.length; index++) {
  8405. var clonedValue = cloneValue(sourceValue[index], destination);
  8406. if (destination[prop].indexOf(clonedValue) === -1) {
  8407. destination[prop].push(clonedValue);
  8408. }
  8409. }
  8410. }
  8411. else {
  8412. destination[prop] = sourceValue.slice(0);
  8413. }
  8414. }
  8415. }
  8416. else {
  8417. destination[prop] = cloneValue(sourceValue, destination);
  8418. }
  8419. }
  8420. else {
  8421. destination[prop] = sourceValue;
  8422. }
  8423. }
  8424. };
  8425. Tools.IsEmpty = function (obj) {
  8426. for (var i in obj) {
  8427. if (obj.hasOwnProperty(i)) {
  8428. return false;
  8429. }
  8430. }
  8431. return true;
  8432. };
  8433. Tools.RegisterTopRootEvents = function (events) {
  8434. for (var index = 0; index < events.length; index++) {
  8435. var event = events[index];
  8436. window.addEventListener(event.name, event.handler, false);
  8437. try {
  8438. if (window.parent) {
  8439. window.parent.addEventListener(event.name, event.handler, false);
  8440. }
  8441. }
  8442. catch (e) {
  8443. // Silently fails...
  8444. }
  8445. }
  8446. };
  8447. Tools.UnregisterTopRootEvents = function (events) {
  8448. for (var index = 0; index < events.length; index++) {
  8449. var event = events[index];
  8450. window.removeEventListener(event.name, event.handler);
  8451. try {
  8452. if (window.parent) {
  8453. window.parent.removeEventListener(event.name, event.handler);
  8454. }
  8455. }
  8456. catch (e) {
  8457. // Silently fails...
  8458. }
  8459. }
  8460. };
  8461. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  8462. if (mimeType === void 0) { mimeType = "image/png"; }
  8463. // Read the contents of the framebuffer
  8464. var numberOfChannelsByLine = width * 4;
  8465. var halfHeight = height / 2;
  8466. //Reading datas from WebGL
  8467. var data = engine.readPixels(0, 0, width, height);
  8468. //To flip image on Y axis.
  8469. for (var i = 0; i < halfHeight; i++) {
  8470. for (var j = 0; j < numberOfChannelsByLine; j++) {
  8471. var currentCell = j + i * numberOfChannelsByLine;
  8472. var targetLine = height - i - 1;
  8473. var targetCell = j + targetLine * numberOfChannelsByLine;
  8474. var temp = data[currentCell];
  8475. data[currentCell] = data[targetCell];
  8476. data[targetCell] = temp;
  8477. }
  8478. }
  8479. // Create a 2D canvas to store the result
  8480. if (!screenshotCanvas) {
  8481. screenshotCanvas = document.createElement('canvas');
  8482. }
  8483. screenshotCanvas.width = width;
  8484. screenshotCanvas.height = height;
  8485. var context = screenshotCanvas.getContext('2d');
  8486. if (context) {
  8487. // Copy the pixels to a 2D canvas
  8488. var imageData = context.createImageData(width, height);
  8489. var castData = (imageData.data);
  8490. castData.set(data);
  8491. context.putImageData(imageData, 0, 0);
  8492. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  8493. }
  8494. };
  8495. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  8496. if (mimeType === void 0) { mimeType = "image/png"; }
  8497. var base64Image = screenshotCanvas.toDataURL(mimeType);
  8498. if (successCallback) {
  8499. successCallback(base64Image);
  8500. }
  8501. else {
  8502. // We need HTMLCanvasElement.toBlob for HD screenshots
  8503. if (!screenshotCanvas.toBlob) {
  8504. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  8505. screenshotCanvas.toBlob = function (callback, type, quality) {
  8506. var _this = this;
  8507. setTimeout(function () {
  8508. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  8509. for (var i = 0; i < len; i++) {
  8510. arr[i] = binStr.charCodeAt(i);
  8511. }
  8512. callback(new Blob([arr], { type: type || 'image/png' }));
  8513. });
  8514. };
  8515. }
  8516. screenshotCanvas.toBlob(function (blob) {
  8517. var url = URL.createObjectURL(blob);
  8518. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  8519. if (("download" in document.createElement("a"))) {
  8520. var a = window.document.createElement("a");
  8521. a.href = url;
  8522. if (fileName) {
  8523. a.setAttribute("download", fileName);
  8524. }
  8525. else {
  8526. var date = new Date();
  8527. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  8528. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  8529. }
  8530. window.document.body.appendChild(a);
  8531. a.addEventListener("click", function () {
  8532. if (a.parentElement) {
  8533. a.parentElement.removeChild(a);
  8534. }
  8535. });
  8536. a.click();
  8537. }
  8538. else {
  8539. var newWindow = window.open("");
  8540. if (!newWindow)
  8541. return;
  8542. var img = newWindow.document.createElement("img");
  8543. img.onload = function () {
  8544. // no longer need to read the blob so it's revoked
  8545. URL.revokeObjectURL(url);
  8546. };
  8547. img.src = url;
  8548. newWindow.document.body.appendChild(img);
  8549. }
  8550. });
  8551. }
  8552. };
  8553. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  8554. if (mimeType === void 0) { mimeType = "image/png"; }
  8555. var width;
  8556. var height;
  8557. // If a precision value is specified
  8558. if (size.precision) {
  8559. width = Math.round(engine.getRenderWidth() * size.precision);
  8560. height = Math.round(width / engine.getAspectRatio(camera));
  8561. }
  8562. else if (size.width && size.height) {
  8563. width = size.width;
  8564. height = size.height;
  8565. }
  8566. else if (size.width && !size.height) {
  8567. width = size.width;
  8568. height = Math.round(width / engine.getAspectRatio(camera));
  8569. }
  8570. else if (size.height && !size.width) {
  8571. height = size.height;
  8572. width = Math.round(height * engine.getAspectRatio(camera));
  8573. }
  8574. else if (!isNaN(size)) {
  8575. height = size;
  8576. width = size;
  8577. }
  8578. else {
  8579. Tools.Error("Invalid 'size' parameter !");
  8580. return;
  8581. }
  8582. if (!screenshotCanvas) {
  8583. screenshotCanvas = document.createElement('canvas');
  8584. }
  8585. screenshotCanvas.width = width;
  8586. screenshotCanvas.height = height;
  8587. var renderContext = screenshotCanvas.getContext("2d");
  8588. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  8589. var newWidth = width;
  8590. var newHeight = newWidth / ratio;
  8591. if (newHeight > height) {
  8592. newHeight = height;
  8593. newWidth = newHeight * ratio;
  8594. }
  8595. var offsetX = Math.max(0, width - newWidth) / 2;
  8596. var offsetY = Math.max(0, height - newHeight) / 2;
  8597. var renderingCanvas = engine.getRenderingCanvas();
  8598. if (renderContext && renderingCanvas) {
  8599. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  8600. }
  8601. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  8602. };
  8603. /**
  8604. * Generates an image screenshot from the specified camera.
  8605. *
  8606. * @param engine The engine to use for rendering
  8607. * @param camera The camera to use for rendering
  8608. * @param size This parameter can be set to a single number or to an object with the
  8609. * following (optional) properties: precision, width, height. If a single number is passed,
  8610. * it will be used for both width and height. If an object is passed, the screenshot size
  8611. * will be derived from the parameters. The precision property is a multiplier allowing
  8612. * rendering at a higher or lower resolution.
  8613. * @param successCallback The callback receives a single parameter which contains the
  8614. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  8615. * src parameter of an <img> to display it.
  8616. * @param mimeType The MIME type of the screenshot image (default: image/png).
  8617. * Check your browser for supported MIME types.
  8618. * @param samples Texture samples (default: 1)
  8619. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  8620. * @param fileName A name for for the downloaded file.
  8621. * @constructor
  8622. */
  8623. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  8624. if (mimeType === void 0) { mimeType = "image/png"; }
  8625. if (samples === void 0) { samples = 1; }
  8626. if (antialiasing === void 0) { antialiasing = false; }
  8627. var width;
  8628. var height;
  8629. //If a precision value is specified
  8630. if (size.precision) {
  8631. width = Math.round(engine.getRenderWidth() * size.precision);
  8632. height = Math.round(width / engine.getAspectRatio(camera));
  8633. size = { width: width, height: height };
  8634. }
  8635. else if (size.width && size.height) {
  8636. width = size.width;
  8637. height = size.height;
  8638. }
  8639. else if (size.width && !size.height) {
  8640. width = size.width;
  8641. height = Math.round(width / engine.getAspectRatio(camera));
  8642. size = { width: width, height: height };
  8643. }
  8644. else if (size.height && !size.width) {
  8645. height = size.height;
  8646. width = Math.round(height * engine.getAspectRatio(camera));
  8647. size = { width: width, height: height };
  8648. }
  8649. else if (!isNaN(size)) {
  8650. height = size;
  8651. width = size;
  8652. }
  8653. else {
  8654. Tools.Error("Invalid 'size' parameter !");
  8655. return;
  8656. }
  8657. var scene = camera.getScene();
  8658. var previousCamera = null;
  8659. if (scene.activeCamera !== camera) {
  8660. previousCamera = scene.activeCamera;
  8661. scene.activeCamera = camera;
  8662. }
  8663. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  8664. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8665. texture.renderList = null;
  8666. texture.samples = samples;
  8667. if (antialiasing) {
  8668. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  8669. }
  8670. texture.onAfterRenderObservable.add(function () {
  8671. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  8672. });
  8673. scene.incrementRenderId();
  8674. scene.resetCachedMaterial();
  8675. texture.render(true);
  8676. texture.dispose();
  8677. if (previousCamera) {
  8678. scene.activeCamera = previousCamera;
  8679. }
  8680. camera.getProjectionMatrix(true); // Force cache refresh;
  8681. };
  8682. // XHR response validator for local file scenario
  8683. Tools.ValidateXHRData = function (xhr, dataType) {
  8684. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  8685. if (dataType === void 0) { dataType = 7; }
  8686. try {
  8687. if (dataType & 1) {
  8688. if (xhr.responseText && xhr.responseText.length > 0) {
  8689. return true;
  8690. }
  8691. else if (dataType === 1) {
  8692. return false;
  8693. }
  8694. }
  8695. if (dataType & 2) {
  8696. // Check header width and height since there is no "TGA" magic number
  8697. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  8698. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  8699. return true;
  8700. }
  8701. else if (dataType === 2) {
  8702. return false;
  8703. }
  8704. }
  8705. if (dataType & 4) {
  8706. // Check for the "DDS" magic number
  8707. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  8708. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  8709. return true;
  8710. }
  8711. else {
  8712. return false;
  8713. }
  8714. }
  8715. }
  8716. catch (e) {
  8717. // Global protection
  8718. }
  8719. return false;
  8720. };
  8721. /**
  8722. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  8723. * Be aware Math.random() could cause collisions, but:
  8724. * "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"
  8725. */
  8726. Tools.RandomId = function () {
  8727. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  8728. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  8729. return v.toString(16);
  8730. });
  8731. };
  8732. /**
  8733. * Test if the given uri is a base64 string.
  8734. * @param uri The uri to test
  8735. * @return True if the uri is a base64 string or false otherwise.
  8736. */
  8737. Tools.IsBase64 = function (uri) {
  8738. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  8739. };
  8740. /**
  8741. * Decode the given base64 uri.
  8742. * @param uri The uri to decode
  8743. * @return The decoded base64 data.
  8744. */
  8745. Tools.DecodeBase64 = function (uri) {
  8746. var decodedString = atob(uri.split(",")[1]);
  8747. var bufferLength = decodedString.length;
  8748. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  8749. for (var i = 0; i < bufferLength; i++) {
  8750. bufferView[i] = decodedString.charCodeAt(i);
  8751. }
  8752. return bufferView.buffer;
  8753. };
  8754. Object.defineProperty(Tools, "NoneLogLevel", {
  8755. get: function () {
  8756. return Tools._NoneLogLevel;
  8757. },
  8758. enumerable: true,
  8759. configurable: true
  8760. });
  8761. Object.defineProperty(Tools, "MessageLogLevel", {
  8762. get: function () {
  8763. return Tools._MessageLogLevel;
  8764. },
  8765. enumerable: true,
  8766. configurable: true
  8767. });
  8768. Object.defineProperty(Tools, "WarningLogLevel", {
  8769. get: function () {
  8770. return Tools._WarningLogLevel;
  8771. },
  8772. enumerable: true,
  8773. configurable: true
  8774. });
  8775. Object.defineProperty(Tools, "ErrorLogLevel", {
  8776. get: function () {
  8777. return Tools._ErrorLogLevel;
  8778. },
  8779. enumerable: true,
  8780. configurable: true
  8781. });
  8782. Object.defineProperty(Tools, "AllLogLevel", {
  8783. get: function () {
  8784. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  8785. },
  8786. enumerable: true,
  8787. configurable: true
  8788. });
  8789. Tools._AddLogEntry = function (entry) {
  8790. Tools._LogCache = entry + Tools._LogCache;
  8791. if (Tools.OnNewCacheEntry) {
  8792. Tools.OnNewCacheEntry(entry);
  8793. }
  8794. };
  8795. Tools._FormatMessage = function (message) {
  8796. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  8797. var date = new Date();
  8798. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  8799. };
  8800. Tools._LogDisabled = function (message) {
  8801. // nothing to do
  8802. };
  8803. Tools._LogEnabled = function (message) {
  8804. var formattedMessage = Tools._FormatMessage(message);
  8805. console.log("BJS - " + formattedMessage);
  8806. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  8807. Tools._AddLogEntry(entry);
  8808. };
  8809. Tools._WarnDisabled = function (message) {
  8810. // nothing to do
  8811. };
  8812. Tools._WarnEnabled = function (message) {
  8813. var formattedMessage = Tools._FormatMessage(message);
  8814. console.warn("BJS - " + formattedMessage);
  8815. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  8816. Tools._AddLogEntry(entry);
  8817. };
  8818. Tools._ErrorDisabled = function (message) {
  8819. // nothing to do
  8820. };
  8821. Tools._ErrorEnabled = function (message) {
  8822. Tools.errorsCount++;
  8823. var formattedMessage = Tools._FormatMessage(message);
  8824. console.error("BJS - " + formattedMessage);
  8825. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  8826. Tools._AddLogEntry(entry);
  8827. };
  8828. Object.defineProperty(Tools, "LogCache", {
  8829. get: function () {
  8830. return Tools._LogCache;
  8831. },
  8832. enumerable: true,
  8833. configurable: true
  8834. });
  8835. Tools.ClearLogCache = function () {
  8836. Tools._LogCache = "";
  8837. Tools.errorsCount = 0;
  8838. };
  8839. Object.defineProperty(Tools, "LogLevels", {
  8840. set: function (level) {
  8841. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  8842. Tools.Log = Tools._LogEnabled;
  8843. }
  8844. else {
  8845. Tools.Log = Tools._LogDisabled;
  8846. }
  8847. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  8848. Tools.Warn = Tools._WarnEnabled;
  8849. }
  8850. else {
  8851. Tools.Warn = Tools._WarnDisabled;
  8852. }
  8853. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  8854. Tools.Error = Tools._ErrorEnabled;
  8855. }
  8856. else {
  8857. Tools.Error = Tools._ErrorDisabled;
  8858. }
  8859. },
  8860. enumerable: true,
  8861. configurable: true
  8862. });
  8863. Tools.IsWindowObjectExist = function () {
  8864. return (typeof window) !== "undefined";
  8865. };
  8866. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  8867. get: function () {
  8868. return Tools._PerformanceNoneLogLevel;
  8869. },
  8870. enumerable: true,
  8871. configurable: true
  8872. });
  8873. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  8874. get: function () {
  8875. return Tools._PerformanceUserMarkLogLevel;
  8876. },
  8877. enumerable: true,
  8878. configurable: true
  8879. });
  8880. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  8881. get: function () {
  8882. return Tools._PerformanceConsoleLogLevel;
  8883. },
  8884. enumerable: true,
  8885. configurable: true
  8886. });
  8887. Object.defineProperty(Tools, "PerformanceLogLevel", {
  8888. set: function (level) {
  8889. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  8890. Tools.StartPerformanceCounter = Tools._StartUserMark;
  8891. Tools.EndPerformanceCounter = Tools._EndUserMark;
  8892. return;
  8893. }
  8894. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  8895. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  8896. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  8897. return;
  8898. }
  8899. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  8900. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  8901. },
  8902. enumerable: true,
  8903. configurable: true
  8904. });
  8905. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  8906. };
  8907. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  8908. };
  8909. Tools._StartUserMark = function (counterName, condition) {
  8910. if (condition === void 0) { condition = true; }
  8911. if (!Tools._performance) {
  8912. if (!Tools.IsWindowObjectExist()) {
  8913. return;
  8914. }
  8915. Tools._performance = window.performance;
  8916. }
  8917. if (!condition || !Tools._performance.mark) {
  8918. return;
  8919. }
  8920. Tools._performance.mark(counterName + "-Begin");
  8921. };
  8922. Tools._EndUserMark = function (counterName, condition) {
  8923. if (condition === void 0) { condition = true; }
  8924. if (!condition || !Tools._performance.mark) {
  8925. return;
  8926. }
  8927. Tools._performance.mark(counterName + "-End");
  8928. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  8929. };
  8930. Tools._StartPerformanceConsole = function (counterName, condition) {
  8931. if (condition === void 0) { condition = true; }
  8932. if (!condition) {
  8933. return;
  8934. }
  8935. Tools._StartUserMark(counterName, condition);
  8936. if (console.time) {
  8937. console.time(counterName);
  8938. }
  8939. };
  8940. Tools._EndPerformanceConsole = function (counterName, condition) {
  8941. if (condition === void 0) { condition = true; }
  8942. if (!condition) {
  8943. return;
  8944. }
  8945. Tools._EndUserMark(counterName, condition);
  8946. if (console.time) {
  8947. console.timeEnd(counterName);
  8948. }
  8949. };
  8950. Object.defineProperty(Tools, "Now", {
  8951. get: function () {
  8952. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  8953. return window.performance.now();
  8954. }
  8955. return new Date().getTime();
  8956. },
  8957. enumerable: true,
  8958. configurable: true
  8959. });
  8960. /**
  8961. * This method will return the name of the class used to create the instance of the given object.
  8962. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  8963. * @param object the object to get the class name from
  8964. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  8965. */
  8966. Tools.GetClassName = function (object, isType) {
  8967. if (isType === void 0) { isType = false; }
  8968. var name = null;
  8969. if (!isType && object.getClassName) {
  8970. name = object.getClassName();
  8971. }
  8972. else {
  8973. if (object instanceof Object) {
  8974. var classObj = isType ? object : Object.getPrototypeOf(object);
  8975. name = classObj.constructor["__bjsclassName__"];
  8976. }
  8977. if (!name) {
  8978. name = typeof object;
  8979. }
  8980. }
  8981. return name;
  8982. };
  8983. Tools.First = function (array, predicate) {
  8984. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  8985. var el = array_1[_i];
  8986. if (predicate(el)) {
  8987. return el;
  8988. }
  8989. }
  8990. return null;
  8991. };
  8992. /**
  8993. * This method will return the name of the full name of the class, including its owning module (if any).
  8994. * 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).
  8995. * @param object the object to get the class name from
  8996. * @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.
  8997. */
  8998. Tools.getFullClassName = function (object, isType) {
  8999. if (isType === void 0) { isType = false; }
  9000. var className = null;
  9001. var moduleName = null;
  9002. if (!isType && object.getClassName) {
  9003. className = object.getClassName();
  9004. }
  9005. else {
  9006. if (object instanceof Object) {
  9007. var classObj = isType ? object : Object.getPrototypeOf(object);
  9008. className = classObj.constructor["__bjsclassName__"];
  9009. moduleName = classObj.constructor["__bjsmoduleName__"];
  9010. }
  9011. if (!className) {
  9012. className = typeof object;
  9013. }
  9014. }
  9015. if (!className) {
  9016. return null;
  9017. }
  9018. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  9019. };
  9020. /**
  9021. * 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.
  9022. * @param array
  9023. */
  9024. Tools.arrayOrStringFeeder = function (array) {
  9025. return function (index) {
  9026. if (index >= array.length) {
  9027. return null;
  9028. }
  9029. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  9030. if (val && val.getHashCode) {
  9031. val = val.getHashCode();
  9032. }
  9033. if (typeof val === "string") {
  9034. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  9035. }
  9036. return val;
  9037. };
  9038. };
  9039. /**
  9040. * Compute the hashCode of a stream of number
  9041. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  9042. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  9043. * @return the hash code computed
  9044. */
  9045. Tools.hashCodeFromStream = function (feeder) {
  9046. // Based from here: http://stackoverflow.com/a/7616484/802124
  9047. var hash = 0;
  9048. var index = 0;
  9049. var chr = feeder(index++);
  9050. while (chr != null) {
  9051. hash = ((hash << 5) - hash) + chr;
  9052. hash |= 0; // Convert to 32bit integer
  9053. chr = feeder(index++);
  9054. }
  9055. return hash;
  9056. };
  9057. /**
  9058. * Returns a promise that resolves after the given amount of time.
  9059. * @param delay Number of milliseconds to delay
  9060. * @returns Promise that resolves after the given amount of time
  9061. */
  9062. Tools.DelayAsync = function (delay) {
  9063. return new Promise(function (resolve) {
  9064. setTimeout(function () {
  9065. resolve();
  9066. }, delay);
  9067. });
  9068. };
  9069. Tools.BaseUrl = "";
  9070. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  9071. /**
  9072. * Default behaviour for cors in the application.
  9073. * It can be a string if the expected behavior is identical in the entire app.
  9074. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  9075. */
  9076. Tools.CorsBehavior = "anonymous";
  9077. Tools.UseFallbackTexture = true;
  9078. /**
  9079. * Use this object to register external classes like custom textures or material
  9080. * to allow the laoders to instantiate them
  9081. */
  9082. Tools.RegisteredExternalClasses = {};
  9083. // Used in case of a texture loading problem
  9084. 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";
  9085. Tools.PreprocessUrl = function (url) {
  9086. return url;
  9087. };
  9088. // Logs
  9089. Tools._NoneLogLevel = 0;
  9090. Tools._MessageLogLevel = 1;
  9091. Tools._WarningLogLevel = 2;
  9092. Tools._ErrorLogLevel = 4;
  9093. Tools._LogCache = "";
  9094. Tools.errorsCount = 0;
  9095. Tools.Log = Tools._LogEnabled;
  9096. Tools.Warn = Tools._WarnEnabled;
  9097. Tools.Error = Tools._ErrorEnabled;
  9098. // Performances
  9099. Tools._PerformanceNoneLogLevel = 0;
  9100. Tools._PerformanceUserMarkLogLevel = 1;
  9101. Tools._PerformanceConsoleLogLevel = 2;
  9102. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9103. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9104. return Tools;
  9105. }());
  9106. BABYLON.Tools = Tools;
  9107. /**
  9108. * This class is used to track a performance counter which is number based.
  9109. * The user has access to many properties which give statistics of different nature
  9110. *
  9111. * The implementer can track two kinds of Performance Counter: time and count
  9112. * 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.
  9113. * 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.
  9114. */
  9115. var PerfCounter = /** @class */ (function () {
  9116. function PerfCounter() {
  9117. this._startMonitoringTime = 0;
  9118. this._min = 0;
  9119. this._max = 0;
  9120. this._average = 0;
  9121. this._lastSecAverage = 0;
  9122. this._current = 0;
  9123. this._totalValueCount = 0;
  9124. this._totalAccumulated = 0;
  9125. this._lastSecAccumulated = 0;
  9126. this._lastSecTime = 0;
  9127. this._lastSecValueCount = 0;
  9128. }
  9129. Object.defineProperty(PerfCounter.prototype, "min", {
  9130. /**
  9131. * Returns the smallest value ever
  9132. */
  9133. get: function () {
  9134. return this._min;
  9135. },
  9136. enumerable: true,
  9137. configurable: true
  9138. });
  9139. Object.defineProperty(PerfCounter.prototype, "max", {
  9140. /**
  9141. * Returns the biggest value ever
  9142. */
  9143. get: function () {
  9144. return this._max;
  9145. },
  9146. enumerable: true,
  9147. configurable: true
  9148. });
  9149. Object.defineProperty(PerfCounter.prototype, "average", {
  9150. /**
  9151. * Returns the average value since the performance counter is running
  9152. */
  9153. get: function () {
  9154. return this._average;
  9155. },
  9156. enumerable: true,
  9157. configurable: true
  9158. });
  9159. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  9160. /**
  9161. * Returns the average value of the last second the counter was monitored
  9162. */
  9163. get: function () {
  9164. return this._lastSecAverage;
  9165. },
  9166. enumerable: true,
  9167. configurable: true
  9168. });
  9169. Object.defineProperty(PerfCounter.prototype, "current", {
  9170. /**
  9171. * Returns the current value
  9172. */
  9173. get: function () {
  9174. return this._current;
  9175. },
  9176. enumerable: true,
  9177. configurable: true
  9178. });
  9179. Object.defineProperty(PerfCounter.prototype, "total", {
  9180. get: function () {
  9181. return this._totalAccumulated;
  9182. },
  9183. enumerable: true,
  9184. configurable: true
  9185. });
  9186. Object.defineProperty(PerfCounter.prototype, "count", {
  9187. get: function () {
  9188. return this._totalValueCount;
  9189. },
  9190. enumerable: true,
  9191. configurable: true
  9192. });
  9193. /**
  9194. * Call this method to start monitoring a new frame.
  9195. * 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.
  9196. */
  9197. PerfCounter.prototype.fetchNewFrame = function () {
  9198. this._totalValueCount++;
  9199. this._current = 0;
  9200. this._lastSecValueCount++;
  9201. };
  9202. /**
  9203. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  9204. * @param newCount the count value to add to the monitored count
  9205. * @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.
  9206. */
  9207. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  9208. if (!PerfCounter.Enabled) {
  9209. return;
  9210. }
  9211. this._current += newCount;
  9212. if (fetchResult) {
  9213. this._fetchResult();
  9214. }
  9215. };
  9216. /**
  9217. * Start monitoring this performance counter
  9218. */
  9219. PerfCounter.prototype.beginMonitoring = function () {
  9220. if (!PerfCounter.Enabled) {
  9221. return;
  9222. }
  9223. this._startMonitoringTime = Tools.Now;
  9224. };
  9225. /**
  9226. * Compute the time lapsed since the previous beginMonitoring() call.
  9227. * @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
  9228. */
  9229. PerfCounter.prototype.endMonitoring = function (newFrame) {
  9230. if (newFrame === void 0) { newFrame = true; }
  9231. if (!PerfCounter.Enabled) {
  9232. return;
  9233. }
  9234. if (newFrame) {
  9235. this.fetchNewFrame();
  9236. }
  9237. var currentTime = Tools.Now;
  9238. this._current = currentTime - this._startMonitoringTime;
  9239. if (newFrame) {
  9240. this._fetchResult();
  9241. }
  9242. };
  9243. PerfCounter.prototype._fetchResult = function () {
  9244. this._totalAccumulated += this._current;
  9245. this._lastSecAccumulated += this._current;
  9246. // Min/Max update
  9247. this._min = Math.min(this._min, this._current);
  9248. this._max = Math.max(this._max, this._current);
  9249. this._average = this._totalAccumulated / this._totalValueCount;
  9250. // Reset last sec?
  9251. var now = Tools.Now;
  9252. if ((now - this._lastSecTime) > 1000) {
  9253. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  9254. this._lastSecTime = now;
  9255. this._lastSecAccumulated = 0;
  9256. this._lastSecValueCount = 0;
  9257. }
  9258. };
  9259. PerfCounter.Enabled = true;
  9260. return PerfCounter;
  9261. }());
  9262. BABYLON.PerfCounter = PerfCounter;
  9263. /**
  9264. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  9265. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  9266. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  9267. * @param name The name of the class, case should be preserved
  9268. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  9269. */
  9270. function className(name, module) {
  9271. return function (target) {
  9272. target["__bjsclassName__"] = name;
  9273. target["__bjsmoduleName__"] = (module != null) ? module : null;
  9274. };
  9275. }
  9276. BABYLON.className = className;
  9277. /**
  9278. * An implementation of a loop for asynchronous functions.
  9279. */
  9280. var AsyncLoop = /** @class */ (function () {
  9281. /**
  9282. * Constroctor.
  9283. * @param iterations the number of iterations.
  9284. * @param _fn the function to run each iteration
  9285. * @param _successCallback the callback that will be called upon succesful execution
  9286. * @param offset starting offset.
  9287. */
  9288. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  9289. if (offset === void 0) { offset = 0; }
  9290. this.iterations = iterations;
  9291. this._fn = _fn;
  9292. this._successCallback = _successCallback;
  9293. this.index = offset - 1;
  9294. this._done = false;
  9295. }
  9296. /**
  9297. * Execute the next iteration. Must be called after the last iteration was finished.
  9298. */
  9299. AsyncLoop.prototype.executeNext = function () {
  9300. if (!this._done) {
  9301. if (this.index + 1 < this.iterations) {
  9302. ++this.index;
  9303. this._fn(this);
  9304. }
  9305. else {
  9306. this.breakLoop();
  9307. }
  9308. }
  9309. };
  9310. /**
  9311. * Break the loop and run the success callback.
  9312. */
  9313. AsyncLoop.prototype.breakLoop = function () {
  9314. this._done = true;
  9315. this._successCallback();
  9316. };
  9317. /**
  9318. * Helper function
  9319. */
  9320. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  9321. if (offset === void 0) { offset = 0; }
  9322. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  9323. loop.executeNext();
  9324. return loop;
  9325. };
  9326. /**
  9327. * A for-loop that will run a given number of iterations synchronous and the rest async.
  9328. * @param iterations total number of iterations
  9329. * @param syncedIterations number of synchronous iterations in each async iteration.
  9330. * @param fn the function to call each iteration.
  9331. * @param callback a success call back that will be called when iterating stops.
  9332. * @param breakFunction a break condition (optional)
  9333. * @param timeout timeout settings for the setTimeout function. default - 0.
  9334. * @constructor
  9335. */
  9336. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  9337. if (timeout === void 0) { timeout = 0; }
  9338. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  9339. if (breakFunction && breakFunction())
  9340. loop.breakLoop();
  9341. else {
  9342. setTimeout(function () {
  9343. for (var i = 0; i < syncedIterations; ++i) {
  9344. var iteration = (loop.index * syncedIterations) + i;
  9345. if (iteration >= iterations)
  9346. break;
  9347. fn(iteration);
  9348. if (breakFunction && breakFunction()) {
  9349. loop.breakLoop();
  9350. break;
  9351. }
  9352. }
  9353. loop.executeNext();
  9354. }, timeout);
  9355. }
  9356. }, callback);
  9357. };
  9358. return AsyncLoop;
  9359. }());
  9360. BABYLON.AsyncLoop = AsyncLoop;
  9361. })(BABYLON || (BABYLON = {}));
  9362. //# sourceMappingURL=babylon.tools.js.map
  9363. var BABYLON;
  9364. (function (BABYLON) {
  9365. var PromiseStates;
  9366. (function (PromiseStates) {
  9367. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  9368. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  9369. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  9370. })(PromiseStates || (PromiseStates = {}));
  9371. var FulFillmentAgregator = /** @class */ (function () {
  9372. function FulFillmentAgregator() {
  9373. this.count = 0;
  9374. this.target = 0;
  9375. this.results = [];
  9376. }
  9377. return FulFillmentAgregator;
  9378. }());
  9379. var InternalPromise = /** @class */ (function () {
  9380. function InternalPromise(resolver) {
  9381. var _this = this;
  9382. this._state = PromiseStates.Pending;
  9383. this._children = new Array();
  9384. this._rejectWasConsumed = false;
  9385. if (!resolver) {
  9386. return;
  9387. }
  9388. try {
  9389. resolver(function (value) {
  9390. _this._resolve(value);
  9391. }, function (reason) {
  9392. _this._reject(reason);
  9393. });
  9394. }
  9395. catch (e) {
  9396. this._reject(e);
  9397. }
  9398. }
  9399. InternalPromise.prototype.catch = function (onRejected) {
  9400. return this.then(undefined, onRejected);
  9401. };
  9402. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  9403. var _this = this;
  9404. var newPromise = new InternalPromise();
  9405. newPromise._onFulfilled = onFulfilled;
  9406. newPromise._onRejected = onRejected;
  9407. // Composition
  9408. this._children.push(newPromise);
  9409. if (this._state !== PromiseStates.Pending) {
  9410. BABYLON.Tools.SetImmediate(function () {
  9411. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  9412. var returnedValue = newPromise._resolve(_this._result);
  9413. if (returnedValue !== undefined && returnedValue !== null) {
  9414. if (returnedValue._state !== undefined) {
  9415. var returnedPromise = returnedValue;
  9416. newPromise._children.push(returnedPromise);
  9417. newPromise = returnedPromise;
  9418. }
  9419. else {
  9420. newPromise._result = returnedValue;
  9421. }
  9422. }
  9423. }
  9424. else {
  9425. newPromise._reject(_this._reason);
  9426. }
  9427. });
  9428. }
  9429. return newPromise;
  9430. };
  9431. InternalPromise.prototype._moveChildren = function (children) {
  9432. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  9433. if (this._state === PromiseStates.Fulfilled) {
  9434. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  9435. var child = _b[_i];
  9436. child._resolve(this._result);
  9437. }
  9438. }
  9439. else if (this._state === PromiseStates.Rejected) {
  9440. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  9441. var child = _d[_c];
  9442. child._reject(this._reason);
  9443. }
  9444. }
  9445. var _a;
  9446. };
  9447. InternalPromise.prototype._resolve = function (value) {
  9448. try {
  9449. this._state = PromiseStates.Fulfilled;
  9450. this._result = value;
  9451. var returnedValue = null;
  9452. if (this._onFulfilled) {
  9453. returnedValue = this._onFulfilled(value);
  9454. }
  9455. if (returnedValue !== undefined && returnedValue !== null) {
  9456. if (returnedValue._state !== undefined) {
  9457. // Transmit children
  9458. var returnedPromise = returnedValue;
  9459. returnedPromise._moveChildren(this._children);
  9460. }
  9461. else {
  9462. value = returnedValue;
  9463. }
  9464. }
  9465. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  9466. var child = _a[_i];
  9467. child._resolve(value);
  9468. }
  9469. this._children.length = 0;
  9470. delete this._onFulfilled;
  9471. delete this._onRejected;
  9472. return returnedValue;
  9473. }
  9474. catch (e) {
  9475. this._reject(e, true);
  9476. }
  9477. return null;
  9478. };
  9479. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  9480. if (onLocalThrow === void 0) { onLocalThrow = false; }
  9481. this._state = PromiseStates.Rejected;
  9482. this._reason = reason;
  9483. if (this._onRejected && !onLocalThrow) {
  9484. try {
  9485. this._onRejected(reason);
  9486. this._rejectWasConsumed = true;
  9487. }
  9488. catch (e) {
  9489. reason = e;
  9490. }
  9491. }
  9492. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  9493. var child = _a[_i];
  9494. if (this._rejectWasConsumed) {
  9495. child._resolve(null);
  9496. }
  9497. else {
  9498. child._reject(reason);
  9499. }
  9500. }
  9501. this._children.length = 0;
  9502. delete this._onFulfilled;
  9503. delete this._onRejected;
  9504. };
  9505. InternalPromise.resolve = function (value) {
  9506. var newPromise = new InternalPromise();
  9507. newPromise._resolve(value);
  9508. return newPromise;
  9509. };
  9510. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  9511. promise.then(function (value) {
  9512. agregator.results[index] = value;
  9513. agregator.count++;
  9514. if (agregator.count === agregator.target) {
  9515. agregator.rootPromise._resolve(agregator.results);
  9516. }
  9517. return null;
  9518. }, function (reason) {
  9519. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  9520. agregator.rootPromise._reject(reason);
  9521. }
  9522. });
  9523. };
  9524. InternalPromise.all = function (promises) {
  9525. var newPromise = new InternalPromise();
  9526. var agregator = new FulFillmentAgregator();
  9527. agregator.target = promises.length;
  9528. agregator.rootPromise = newPromise;
  9529. if (promises.length) {
  9530. for (var index = 0; index < promises.length; index++) {
  9531. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  9532. }
  9533. }
  9534. else {
  9535. newPromise._resolve([]);
  9536. }
  9537. return newPromise;
  9538. };
  9539. return InternalPromise;
  9540. }());
  9541. /**
  9542. * Helper class that provides a small promise polyfill
  9543. */
  9544. var PromisePolyfill = /** @class */ (function () {
  9545. function PromisePolyfill() {
  9546. }
  9547. /**
  9548. * Static function used to check if the polyfill is required
  9549. * If this is the case then the function will inject the polyfill to window.Promise
  9550. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  9551. */
  9552. PromisePolyfill.Apply = function (force) {
  9553. if (force === void 0) { force = false; }
  9554. if (force || typeof Promise === 'undefined') {
  9555. var root = window;
  9556. root.Promise = InternalPromise;
  9557. }
  9558. };
  9559. return PromisePolyfill;
  9560. }());
  9561. BABYLON.PromisePolyfill = PromisePolyfill;
  9562. })(BABYLON || (BABYLON = {}));
  9563. //# sourceMappingURL=babylon.promise.js.map
  9564. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  9565. var BABYLON;
  9566. (function (BABYLON) {
  9567. /**
  9568. * Helper class to push actions to a pool of workers.
  9569. */
  9570. var WorkerPool = /** @class */ (function () {
  9571. /**
  9572. * Constructor
  9573. * @param workers Array of workers to use for actions
  9574. */
  9575. function WorkerPool(workers) {
  9576. this._pendingActions = new Array();
  9577. this._workerInfos = workers.map(function (worker) { return ({
  9578. worker: worker,
  9579. active: false
  9580. }); });
  9581. }
  9582. /**
  9583. * Terminates all workers and clears any pending actions.
  9584. */
  9585. WorkerPool.prototype.dispose = function () {
  9586. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  9587. var workerInfo = _a[_i];
  9588. workerInfo.worker.terminate();
  9589. }
  9590. delete this._workerInfos;
  9591. delete this._pendingActions;
  9592. };
  9593. /**
  9594. * Pushes an action to the worker pool. If all the workers are active, the action will be
  9595. * pended until a worker has completed its action.
  9596. * @param action The action to perform. Call onComplete when the action is complete.
  9597. */
  9598. WorkerPool.prototype.push = function (action) {
  9599. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  9600. var workerInfo = _a[_i];
  9601. if (!workerInfo.active) {
  9602. this._execute(workerInfo, action);
  9603. return;
  9604. }
  9605. }
  9606. this._pendingActions.push(action);
  9607. };
  9608. WorkerPool.prototype._execute = function (workerInfo, action) {
  9609. var _this = this;
  9610. workerInfo.active = true;
  9611. action(workerInfo.worker, function () {
  9612. workerInfo.active = false;
  9613. var nextAction = _this._pendingActions.shift();
  9614. if (nextAction) {
  9615. _this._execute(workerInfo, nextAction);
  9616. }
  9617. });
  9618. };
  9619. return WorkerPool;
  9620. }());
  9621. BABYLON.WorkerPool = WorkerPool;
  9622. })(BABYLON || (BABYLON = {}));
  9623. //# sourceMappingURL=babylon.workerPool.js.map
  9624. var BABYLON;
  9625. (function (BABYLON) {
  9626. var _AlphaState = /** @class */ (function () {
  9627. /**
  9628. * Initializes the state.
  9629. */
  9630. function _AlphaState() {
  9631. this._isAlphaBlendDirty = false;
  9632. this._isBlendFunctionParametersDirty = false;
  9633. this._isBlendEquationParametersDirty = false;
  9634. this._isBlendConstantsDirty = false;
  9635. this._alphaBlend = false;
  9636. this._blendFunctionParameters = new Array(4);
  9637. this._blendEquationParameters = new Array(2);
  9638. this._blendConstants = new Array(4);
  9639. this.reset();
  9640. }
  9641. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  9642. get: function () {
  9643. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  9644. },
  9645. enumerable: true,
  9646. configurable: true
  9647. });
  9648. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  9649. get: function () {
  9650. return this._alphaBlend;
  9651. },
  9652. set: function (value) {
  9653. if (this._alphaBlend === value) {
  9654. return;
  9655. }
  9656. this._alphaBlend = value;
  9657. this._isAlphaBlendDirty = true;
  9658. },
  9659. enumerable: true,
  9660. configurable: true
  9661. });
  9662. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  9663. if (this._blendConstants[0] === r &&
  9664. this._blendConstants[1] === g &&
  9665. this._blendConstants[2] === b &&
  9666. this._blendConstants[3] === a) {
  9667. return;
  9668. }
  9669. this._blendConstants[0] = r;
  9670. this._blendConstants[1] = g;
  9671. this._blendConstants[2] = b;
  9672. this._blendConstants[3] = a;
  9673. this._isBlendConstantsDirty = true;
  9674. };
  9675. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  9676. if (this._blendFunctionParameters[0] === value0 &&
  9677. this._blendFunctionParameters[1] === value1 &&
  9678. this._blendFunctionParameters[2] === value2 &&
  9679. this._blendFunctionParameters[3] === value3) {
  9680. return;
  9681. }
  9682. this._blendFunctionParameters[0] = value0;
  9683. this._blendFunctionParameters[1] = value1;
  9684. this._blendFunctionParameters[2] = value2;
  9685. this._blendFunctionParameters[3] = value3;
  9686. this._isBlendFunctionParametersDirty = true;
  9687. };
  9688. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  9689. if (this._blendEquationParameters[0] === rgb &&
  9690. this._blendEquationParameters[1] === alpha) {
  9691. return;
  9692. }
  9693. this._blendEquationParameters[0] = rgb;
  9694. this._blendEquationParameters[1] = alpha;
  9695. this._isBlendEquationParametersDirty = true;
  9696. };
  9697. _AlphaState.prototype.reset = function () {
  9698. this._alphaBlend = false;
  9699. this._blendFunctionParameters[0] = null;
  9700. this._blendFunctionParameters[1] = null;
  9701. this._blendFunctionParameters[2] = null;
  9702. this._blendFunctionParameters[3] = null;
  9703. this._blendEquationParameters[0] = null;
  9704. this._blendEquationParameters[1] = null;
  9705. this._blendConstants[0] = null;
  9706. this._blendConstants[1] = null;
  9707. this._blendConstants[2] = null;
  9708. this._blendConstants[3] = null;
  9709. this._isAlphaBlendDirty = true;
  9710. this._isBlendFunctionParametersDirty = false;
  9711. this._isBlendEquationParametersDirty = false;
  9712. this._isBlendConstantsDirty = false;
  9713. };
  9714. _AlphaState.prototype.apply = function (gl) {
  9715. if (!this.isDirty) {
  9716. return;
  9717. }
  9718. // Alpha blend
  9719. if (this._isAlphaBlendDirty) {
  9720. if (this._alphaBlend) {
  9721. gl.enable(gl.BLEND);
  9722. }
  9723. else {
  9724. gl.disable(gl.BLEND);
  9725. }
  9726. this._isAlphaBlendDirty = false;
  9727. }
  9728. // Alpha function
  9729. if (this._isBlendFunctionParametersDirty) {
  9730. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  9731. this._isBlendFunctionParametersDirty = false;
  9732. }
  9733. // Alpha equation
  9734. if (this._isBlendEquationParametersDirty) {
  9735. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  9736. this._isBlendEquationParametersDirty = false;
  9737. }
  9738. // Constants
  9739. if (this._isBlendConstantsDirty) {
  9740. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  9741. this._isBlendConstantsDirty = false;
  9742. }
  9743. };
  9744. return _AlphaState;
  9745. }());
  9746. BABYLON._AlphaState = _AlphaState;
  9747. })(BABYLON || (BABYLON = {}));
  9748. //# sourceMappingURL=babylon.alphaCullingState.js.map
  9749. var BABYLON;
  9750. (function (BABYLON) {
  9751. var _DepthCullingState = /** @class */ (function () {
  9752. /**
  9753. * Initializes the state.
  9754. */
  9755. function _DepthCullingState() {
  9756. this._isDepthTestDirty = false;
  9757. this._isDepthMaskDirty = false;
  9758. this._isDepthFuncDirty = false;
  9759. this._isCullFaceDirty = false;
  9760. this._isCullDirty = false;
  9761. this._isZOffsetDirty = false;
  9762. this._isFrontFaceDirty = false;
  9763. this.reset();
  9764. }
  9765. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  9766. get: function () {
  9767. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  9768. },
  9769. enumerable: true,
  9770. configurable: true
  9771. });
  9772. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  9773. get: function () {
  9774. return this._zOffset;
  9775. },
  9776. set: function (value) {
  9777. if (this._zOffset === value) {
  9778. return;
  9779. }
  9780. this._zOffset = value;
  9781. this._isZOffsetDirty = true;
  9782. },
  9783. enumerable: true,
  9784. configurable: true
  9785. });
  9786. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  9787. get: function () {
  9788. return this._cullFace;
  9789. },
  9790. set: function (value) {
  9791. if (this._cullFace === value) {
  9792. return;
  9793. }
  9794. this._cullFace = value;
  9795. this._isCullFaceDirty = true;
  9796. },
  9797. enumerable: true,
  9798. configurable: true
  9799. });
  9800. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  9801. get: function () {
  9802. return this._cull;
  9803. },
  9804. set: function (value) {
  9805. if (this._cull === value) {
  9806. return;
  9807. }
  9808. this._cull = value;
  9809. this._isCullDirty = true;
  9810. },
  9811. enumerable: true,
  9812. configurable: true
  9813. });
  9814. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  9815. get: function () {
  9816. return this._depthFunc;
  9817. },
  9818. set: function (value) {
  9819. if (this._depthFunc === value) {
  9820. return;
  9821. }
  9822. this._depthFunc = value;
  9823. this._isDepthFuncDirty = true;
  9824. },
  9825. enumerable: true,
  9826. configurable: true
  9827. });
  9828. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  9829. get: function () {
  9830. return this._depthMask;
  9831. },
  9832. set: function (value) {
  9833. if (this._depthMask === value) {
  9834. return;
  9835. }
  9836. this._depthMask = value;
  9837. this._isDepthMaskDirty = true;
  9838. },
  9839. enumerable: true,
  9840. configurable: true
  9841. });
  9842. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  9843. get: function () {
  9844. return this._depthTest;
  9845. },
  9846. set: function (value) {
  9847. if (this._depthTest === value) {
  9848. return;
  9849. }
  9850. this._depthTest = value;
  9851. this._isDepthTestDirty = true;
  9852. },
  9853. enumerable: true,
  9854. configurable: true
  9855. });
  9856. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  9857. get: function () {
  9858. return this._frontFace;
  9859. },
  9860. set: function (value) {
  9861. if (this._frontFace === value) {
  9862. return;
  9863. }
  9864. this._frontFace = value;
  9865. this._isFrontFaceDirty = true;
  9866. },
  9867. enumerable: true,
  9868. configurable: true
  9869. });
  9870. _DepthCullingState.prototype.reset = function () {
  9871. this._depthMask = true;
  9872. this._depthTest = true;
  9873. this._depthFunc = null;
  9874. this._cullFace = null;
  9875. this._cull = null;
  9876. this._zOffset = 0;
  9877. this._frontFace = null;
  9878. this._isDepthTestDirty = true;
  9879. this._isDepthMaskDirty = true;
  9880. this._isDepthFuncDirty = false;
  9881. this._isCullFaceDirty = false;
  9882. this._isCullDirty = false;
  9883. this._isZOffsetDirty = false;
  9884. this._isFrontFaceDirty = false;
  9885. };
  9886. _DepthCullingState.prototype.apply = function (gl) {
  9887. if (!this.isDirty) {
  9888. return;
  9889. }
  9890. // Cull
  9891. if (this._isCullDirty) {
  9892. if (this.cull) {
  9893. gl.enable(gl.CULL_FACE);
  9894. }
  9895. else {
  9896. gl.disable(gl.CULL_FACE);
  9897. }
  9898. this._isCullDirty = false;
  9899. }
  9900. // Cull face
  9901. if (this._isCullFaceDirty) {
  9902. gl.cullFace(this.cullFace);
  9903. this._isCullFaceDirty = false;
  9904. }
  9905. // Depth mask
  9906. if (this._isDepthMaskDirty) {
  9907. gl.depthMask(this.depthMask);
  9908. this._isDepthMaskDirty = false;
  9909. }
  9910. // Depth test
  9911. if (this._isDepthTestDirty) {
  9912. if (this.depthTest) {
  9913. gl.enable(gl.DEPTH_TEST);
  9914. }
  9915. else {
  9916. gl.disable(gl.DEPTH_TEST);
  9917. }
  9918. this._isDepthTestDirty = false;
  9919. }
  9920. // Depth func
  9921. if (this._isDepthFuncDirty) {
  9922. gl.depthFunc(this.depthFunc);
  9923. this._isDepthFuncDirty = false;
  9924. }
  9925. // zOffset
  9926. if (this._isZOffsetDirty) {
  9927. if (this.zOffset) {
  9928. gl.enable(gl.POLYGON_OFFSET_FILL);
  9929. gl.polygonOffset(this.zOffset, 0);
  9930. }
  9931. else {
  9932. gl.disable(gl.POLYGON_OFFSET_FILL);
  9933. }
  9934. this._isZOffsetDirty = false;
  9935. }
  9936. // Front face
  9937. if (this._isFrontFaceDirty) {
  9938. gl.frontFace(this.frontFace);
  9939. this._isFrontFaceDirty = false;
  9940. }
  9941. };
  9942. return _DepthCullingState;
  9943. }());
  9944. BABYLON._DepthCullingState = _DepthCullingState;
  9945. })(BABYLON || (BABYLON = {}));
  9946. //# sourceMappingURL=babylon.depthCullingState.js.map
  9947. var BABYLON;
  9948. (function (BABYLON) {
  9949. var _StencilState = /** @class */ (function () {
  9950. function _StencilState() {
  9951. this._isStencilTestDirty = false;
  9952. this._isStencilMaskDirty = false;
  9953. this._isStencilFuncDirty = false;
  9954. this._isStencilOpDirty = false;
  9955. this.reset();
  9956. }
  9957. Object.defineProperty(_StencilState.prototype, "isDirty", {
  9958. get: function () {
  9959. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  9960. },
  9961. enumerable: true,
  9962. configurable: true
  9963. });
  9964. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  9965. get: function () {
  9966. return this._stencilFunc;
  9967. },
  9968. set: function (value) {
  9969. if (this._stencilFunc === value) {
  9970. return;
  9971. }
  9972. this._stencilFunc = value;
  9973. this._isStencilFuncDirty = true;
  9974. },
  9975. enumerable: true,
  9976. configurable: true
  9977. });
  9978. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  9979. get: function () {
  9980. return this._stencilFuncRef;
  9981. },
  9982. set: function (value) {
  9983. if (this._stencilFuncRef === value) {
  9984. return;
  9985. }
  9986. this._stencilFuncRef = value;
  9987. this._isStencilFuncDirty = true;
  9988. },
  9989. enumerable: true,
  9990. configurable: true
  9991. });
  9992. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  9993. get: function () {
  9994. return this._stencilFuncMask;
  9995. },
  9996. set: function (value) {
  9997. if (this._stencilFuncMask === value) {
  9998. return;
  9999. }
  10000. this._stencilFuncMask = value;
  10001. this._isStencilFuncDirty = true;
  10002. },
  10003. enumerable: true,
  10004. configurable: true
  10005. });
  10006. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  10007. get: function () {
  10008. return this._stencilOpStencilFail;
  10009. },
  10010. set: function (value) {
  10011. if (this._stencilOpStencilFail === value) {
  10012. return;
  10013. }
  10014. this._stencilOpStencilFail = value;
  10015. this._isStencilOpDirty = true;
  10016. },
  10017. enumerable: true,
  10018. configurable: true
  10019. });
  10020. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  10021. get: function () {
  10022. return this._stencilOpDepthFail;
  10023. },
  10024. set: function (value) {
  10025. if (this._stencilOpDepthFail === value) {
  10026. return;
  10027. }
  10028. this._stencilOpDepthFail = value;
  10029. this._isStencilOpDirty = true;
  10030. },
  10031. enumerable: true,
  10032. configurable: true
  10033. });
  10034. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  10035. get: function () {
  10036. return this._stencilOpStencilDepthPass;
  10037. },
  10038. set: function (value) {
  10039. if (this._stencilOpStencilDepthPass === value) {
  10040. return;
  10041. }
  10042. this._stencilOpStencilDepthPass = value;
  10043. this._isStencilOpDirty = true;
  10044. },
  10045. enumerable: true,
  10046. configurable: true
  10047. });
  10048. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  10049. get: function () {
  10050. return this._stencilMask;
  10051. },
  10052. set: function (value) {
  10053. if (this._stencilMask === value) {
  10054. return;
  10055. }
  10056. this._stencilMask = value;
  10057. this._isStencilMaskDirty = true;
  10058. },
  10059. enumerable: true,
  10060. configurable: true
  10061. });
  10062. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  10063. get: function () {
  10064. return this._stencilTest;
  10065. },
  10066. set: function (value) {
  10067. if (this._stencilTest === value) {
  10068. return;
  10069. }
  10070. this._stencilTest = value;
  10071. this._isStencilTestDirty = true;
  10072. },
  10073. enumerable: true,
  10074. configurable: true
  10075. });
  10076. _StencilState.prototype.reset = function () {
  10077. this._stencilTest = false;
  10078. this._stencilMask = 0xFF;
  10079. this._stencilFunc = BABYLON.Engine.ALWAYS;
  10080. this._stencilFuncRef = 1;
  10081. this._stencilFuncMask = 0xFF;
  10082. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  10083. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  10084. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  10085. this._isStencilTestDirty = true;
  10086. this._isStencilMaskDirty = true;
  10087. this._isStencilFuncDirty = true;
  10088. this._isStencilOpDirty = true;
  10089. };
  10090. _StencilState.prototype.apply = function (gl) {
  10091. if (!this.isDirty) {
  10092. return;
  10093. }
  10094. // Stencil test
  10095. if (this._isStencilTestDirty) {
  10096. if (this.stencilTest) {
  10097. gl.enable(gl.STENCIL_TEST);
  10098. }
  10099. else {
  10100. gl.disable(gl.STENCIL_TEST);
  10101. }
  10102. this._isStencilTestDirty = false;
  10103. }
  10104. // Stencil mask
  10105. if (this._isStencilMaskDirty) {
  10106. gl.stencilMask(this.stencilMask);
  10107. this._isStencilMaskDirty = false;
  10108. }
  10109. // Stencil func
  10110. if (this._isStencilFuncDirty) {
  10111. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  10112. this._isStencilFuncDirty = false;
  10113. }
  10114. // Stencil op
  10115. if (this._isStencilOpDirty) {
  10116. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  10117. this._isStencilOpDirty = false;
  10118. }
  10119. };
  10120. return _StencilState;
  10121. }());
  10122. BABYLON._StencilState = _StencilState;
  10123. })(BABYLON || (BABYLON = {}));
  10124. //# sourceMappingURL=babylon.stencilState.js.map
  10125. var __assign = (this && this.__assign) || Object.assign || function(t) {
  10126. for (var s, i = 1, n = arguments.length; i < n; i++) {
  10127. s = arguments[i];
  10128. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  10129. t[p] = s[p];
  10130. }
  10131. return t;
  10132. };
  10133. var BABYLON;
  10134. (function (BABYLON) {
  10135. var compileShader = function (gl, source, type, defines, shaderVersion) {
  10136. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  10137. };
  10138. var compileRawShader = function (gl, source, type) {
  10139. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  10140. gl.shaderSource(shader, source);
  10141. gl.compileShader(shader);
  10142. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  10143. var log = gl.getShaderInfoLog(shader);
  10144. if (log) {
  10145. throw new Error(log);
  10146. }
  10147. }
  10148. if (!shader) {
  10149. throw new Error("Something went wrong while compile the shader.");
  10150. }
  10151. return shader;
  10152. };
  10153. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  10154. var magFilter = gl.NEAREST;
  10155. var minFilter = gl.NEAREST;
  10156. switch (samplingMode) {
  10157. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  10158. magFilter = gl.LINEAR;
  10159. if (generateMipMaps) {
  10160. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10161. }
  10162. else {
  10163. minFilter = gl.LINEAR;
  10164. }
  10165. break;
  10166. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  10167. magFilter = gl.LINEAR;
  10168. if (generateMipMaps) {
  10169. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10170. }
  10171. else {
  10172. minFilter = gl.LINEAR;
  10173. }
  10174. break;
  10175. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  10176. magFilter = gl.NEAREST;
  10177. if (generateMipMaps) {
  10178. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10179. }
  10180. else {
  10181. minFilter = gl.NEAREST;
  10182. }
  10183. break;
  10184. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  10185. magFilter = gl.NEAREST;
  10186. if (generateMipMaps) {
  10187. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10188. }
  10189. else {
  10190. minFilter = gl.NEAREST;
  10191. }
  10192. break;
  10193. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  10194. magFilter = gl.NEAREST;
  10195. if (generateMipMaps) {
  10196. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10197. }
  10198. else {
  10199. minFilter = gl.LINEAR;
  10200. }
  10201. break;
  10202. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  10203. magFilter = gl.NEAREST;
  10204. if (generateMipMaps) {
  10205. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10206. }
  10207. else {
  10208. minFilter = gl.LINEAR;
  10209. }
  10210. break;
  10211. case BABYLON.Texture.NEAREST_LINEAR:
  10212. magFilter = gl.NEAREST;
  10213. minFilter = gl.LINEAR;
  10214. break;
  10215. case BABYLON.Texture.NEAREST_NEAREST:
  10216. magFilter = gl.NEAREST;
  10217. minFilter = gl.NEAREST;
  10218. break;
  10219. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  10220. magFilter = gl.LINEAR;
  10221. if (generateMipMaps) {
  10222. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10223. }
  10224. else {
  10225. minFilter = gl.NEAREST;
  10226. }
  10227. break;
  10228. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  10229. magFilter = gl.LINEAR;
  10230. if (generateMipMaps) {
  10231. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10232. }
  10233. else {
  10234. minFilter = gl.NEAREST;
  10235. }
  10236. break;
  10237. case BABYLON.Texture.LINEAR_LINEAR:
  10238. magFilter = gl.LINEAR;
  10239. minFilter = gl.LINEAR;
  10240. break;
  10241. case BABYLON.Texture.LINEAR_NEAREST:
  10242. magFilter = gl.LINEAR;
  10243. minFilter = gl.NEAREST;
  10244. break;
  10245. }
  10246. return {
  10247. min: minFilter,
  10248. mag: magFilter
  10249. };
  10250. };
  10251. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  10252. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  10253. var img;
  10254. var onload = function () {
  10255. loadedImages[index] = img;
  10256. loadedImages._internalCount++;
  10257. if (scene) {
  10258. scene._removePendingData(img);
  10259. }
  10260. if (loadedImages._internalCount === 6) {
  10261. onfinish(loadedImages);
  10262. }
  10263. };
  10264. var onerror = function (message, exception) {
  10265. if (scene) {
  10266. scene._removePendingData(img);
  10267. }
  10268. if (onErrorCallBack) {
  10269. onErrorCallBack(message, exception);
  10270. }
  10271. };
  10272. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  10273. if (scene) {
  10274. scene._addPendingData(img);
  10275. }
  10276. };
  10277. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  10278. if (onError === void 0) { onError = null; }
  10279. var loadedImages = [];
  10280. loadedImages._internalCount = 0;
  10281. for (var index = 0; index < 6; index++) {
  10282. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  10283. }
  10284. };
  10285. var BufferPointer = /** @class */ (function () {
  10286. function BufferPointer() {
  10287. }
  10288. return BufferPointer;
  10289. }());
  10290. var InstancingAttributeInfo = /** @class */ (function () {
  10291. function InstancingAttributeInfo() {
  10292. }
  10293. return InstancingAttributeInfo;
  10294. }());
  10295. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  10296. /**
  10297. * Define options used to create a render target texture
  10298. */
  10299. var RenderTargetCreationOptions = /** @class */ (function () {
  10300. function RenderTargetCreationOptions() {
  10301. }
  10302. return RenderTargetCreationOptions;
  10303. }());
  10304. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  10305. /**
  10306. * Define options used to create a depth texture
  10307. */
  10308. var DepthTextureCreationOptions = /** @class */ (function () {
  10309. function DepthTextureCreationOptions() {
  10310. }
  10311. return DepthTextureCreationOptions;
  10312. }());
  10313. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  10314. /**
  10315. * Regroup several parameters relative to the browser in use
  10316. */
  10317. var EngineCapabilities = /** @class */ (function () {
  10318. function EngineCapabilities() {
  10319. }
  10320. return EngineCapabilities;
  10321. }());
  10322. BABYLON.EngineCapabilities = EngineCapabilities;
  10323. /**
  10324. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  10325. */
  10326. var Engine = /** @class */ (function () {
  10327. /**
  10328. * @constructor
  10329. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  10330. * @param antialias defines enable antialiasing (default: false)
  10331. * @param options defines further options to be sent to the getContext() function
  10332. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  10333. */
  10334. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  10335. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  10336. var _this = this;
  10337. // Public members
  10338. this.forcePOTTextures = false;
  10339. this.isFullscreen = false;
  10340. this.isPointerLock = false;
  10341. this.cullBackFaces = true;
  10342. this.renderEvenInBackground = true;
  10343. this.preventCacheWipeBetweenFrames = false;
  10344. // To enable/disable IDB support and avoid XHR on .manifest
  10345. this.enableOfflineSupport = false;
  10346. this.scenes = new Array();
  10347. this.postProcesses = new Array();
  10348. // Observables
  10349. /**
  10350. * Observable event triggered each time the rendering canvas is resized
  10351. */
  10352. this.onResizeObservable = new BABYLON.Observable();
  10353. /**
  10354. * Observable event triggered each time the canvas loses focus
  10355. */
  10356. this.onCanvasBlurObservable = new BABYLON.Observable();
  10357. /**
  10358. * Observable event triggered each time the canvas gains focus
  10359. */
  10360. this.onCanvasFocusObservable = new BABYLON.Observable();
  10361. /**
  10362. * Observable event triggered each time the canvas receives pointerout event
  10363. */
  10364. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  10365. /**
  10366. * Observable event triggered before each texture is initialized
  10367. */
  10368. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  10369. //WebVR
  10370. this._vrDisplay = undefined;
  10371. this._vrSupported = false;
  10372. this._vrExclusivePointerMode = false;
  10373. // Uniform buffers list
  10374. this.disableUniformBuffers = false;
  10375. this._uniformBuffers = new Array();
  10376. // Observables
  10377. /**
  10378. * Observable raised when the engine begins a new frame
  10379. */
  10380. this.onBeginFrameObservable = new BABYLON.Observable();
  10381. /**
  10382. * Observable raised when the engine ends the current frame
  10383. */
  10384. this.onEndFrameObservable = new BABYLON.Observable();
  10385. /**
  10386. * Observable raised when the engine is about to compile a shader
  10387. */
  10388. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  10389. /**
  10390. * Observable raised when the engine has jsut compiled a shader
  10391. */
  10392. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  10393. this._windowIsBackground = false;
  10394. this._webGLVersion = 1.0;
  10395. this._badOS = false;
  10396. this._badDesktopOS = false;
  10397. /**
  10398. * Gets or sets a value indicating if we want to disable texture binding optmization.
  10399. * This could be required on some buggy drivers which wants to have textures bound in a progressive order
  10400. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is.
  10401. */
  10402. this.disableTextureBindingOptimization = false;
  10403. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  10404. this.onVRRequestPresentComplete = new BABYLON.Observable();
  10405. this.onVRRequestPresentStart = new BABYLON.Observable();
  10406. this._colorWrite = true;
  10407. this._drawCalls = new BABYLON.PerfCounter();
  10408. this._textureCollisions = new BABYLON.PerfCounter();
  10409. this._renderingQueueLaunched = false;
  10410. this._activeRenderLoops = new Array();
  10411. // Deterministic lockstepMaxSteps
  10412. this._deterministicLockstep = false;
  10413. this._lockstepMaxSteps = 4;
  10414. // Lost context
  10415. this.onContextLostObservable = new BABYLON.Observable();
  10416. this.onContextRestoredObservable = new BABYLON.Observable();
  10417. this._contextWasLost = false;
  10418. this._doNotHandleContextLost = false;
  10419. // FPS
  10420. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  10421. this._fps = 60;
  10422. this._deltaTime = 0;
  10423. /**
  10424. * Turn this value on if you want to pause FPS computation when in background
  10425. */
  10426. this.disablePerformanceMonitorInBackground = false;
  10427. // States
  10428. this._depthCullingState = new BABYLON._DepthCullingState();
  10429. this._stencilState = new BABYLON._StencilState();
  10430. this._alphaState = new BABYLON._AlphaState();
  10431. this._alphaMode = Engine.ALPHA_DISABLE;
  10432. // Cache
  10433. this._internalTexturesCache = new Array();
  10434. this._activeChannel = 0;
  10435. this._currentTextureChannel = -1;
  10436. this._boundTexturesCache = {};
  10437. this._compiledEffects = {};
  10438. this._vertexAttribArraysEnabled = [];
  10439. this._uintIndicesCurrentlySet = false;
  10440. this._currentBoundBuffer = new Array();
  10441. this._currentBufferPointers = new Array();
  10442. this._currentInstanceLocations = new Array();
  10443. this._currentInstanceBuffers = new Array();
  10444. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  10445. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  10446. this._vaoRecordInProgress = false;
  10447. this._mustWipeVertexAttributes = false;
  10448. this._nextFreeTextureSlots = new Array();
  10449. this._maxSimultaneousTextures = 0;
  10450. this._activeRequests = new Array();
  10451. // Hardware supported Compressed Textures
  10452. this._texturesSupported = new Array();
  10453. this._onVRFullScreenTriggered = function () {
  10454. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  10455. //get the old size before we change
  10456. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  10457. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  10458. //get the width and height, change the render size
  10459. var leftEye = _this._vrDisplay.getEyeParameters('left');
  10460. _this.setHardwareScalingLevel(1);
  10461. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  10462. }
  10463. else {
  10464. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  10465. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  10466. }
  10467. };
  10468. this._boundUniforms = {};
  10469. // Register promises
  10470. BABYLON.PromisePolyfill.Apply();
  10471. var canvas = null;
  10472. Engine.Instances.push(this);
  10473. if (!canvasOrContext) {
  10474. return;
  10475. }
  10476. options = options || {};
  10477. if (canvasOrContext.getContext) {
  10478. canvas = canvasOrContext;
  10479. this._renderingCanvas = canvas;
  10480. if (antialias != null) {
  10481. options.antialias = antialias;
  10482. }
  10483. if (options.deterministicLockstep === undefined) {
  10484. options.deterministicLockstep = false;
  10485. }
  10486. if (options.lockstepMaxSteps === undefined) {
  10487. options.lockstepMaxSteps = 4;
  10488. }
  10489. if (options.preserveDrawingBuffer === undefined) {
  10490. options.preserveDrawingBuffer = false;
  10491. }
  10492. if (options.audioEngine === undefined) {
  10493. options.audioEngine = true;
  10494. }
  10495. if (options.stencil === undefined) {
  10496. options.stencil = true;
  10497. }
  10498. this._deterministicLockstep = options.deterministicLockstep;
  10499. this._lockstepMaxSteps = options.lockstepMaxSteps;
  10500. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  10501. // Exceptions
  10502. if (navigator && navigator.userAgent) {
  10503. var ua = navigator.userAgent;
  10504. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  10505. var exception = _a[_i];
  10506. var key = exception.key;
  10507. var targets = exception.targets;
  10508. if (ua.indexOf(key) > -1) {
  10509. if (exception.capture && exception.captureConstraint) {
  10510. var capture = exception.capture;
  10511. var constraint = exception.captureConstraint;
  10512. var regex = new RegExp(capture);
  10513. var matches = regex.exec(ua);
  10514. if (matches && matches.length > 0) {
  10515. var capturedValue = parseInt(matches[matches.length - 1]);
  10516. if (capturedValue >= constraint) {
  10517. continue;
  10518. }
  10519. }
  10520. }
  10521. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  10522. var target = targets_1[_b];
  10523. switch (target) {
  10524. case "uniformBuffer":
  10525. this.disableUniformBuffers = true;
  10526. break;
  10527. case "textureBindingOptimization":
  10528. this.disableTextureBindingOptimization = true;
  10529. break;
  10530. }
  10531. }
  10532. break;
  10533. }
  10534. }
  10535. }
  10536. // GL
  10537. if (!options.disableWebGL2Support) {
  10538. try {
  10539. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  10540. if (this._gl) {
  10541. this._webGLVersion = 2.0;
  10542. }
  10543. }
  10544. catch (e) {
  10545. // Do nothing
  10546. }
  10547. }
  10548. if (!this._gl) {
  10549. if (!canvas) {
  10550. throw new Error("The provided canvas is null or undefined.");
  10551. }
  10552. try {
  10553. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  10554. }
  10555. catch (e) {
  10556. throw new Error("WebGL not supported");
  10557. }
  10558. }
  10559. if (!this._gl) {
  10560. throw new Error("WebGL not supported");
  10561. }
  10562. this._onCanvasFocus = function () {
  10563. _this.onCanvasFocusObservable.notifyObservers(_this);
  10564. };
  10565. this._onCanvasBlur = function () {
  10566. _this.onCanvasBlurObservable.notifyObservers(_this);
  10567. };
  10568. canvas.addEventListener("focus", this._onCanvasFocus);
  10569. canvas.addEventListener("blur", this._onCanvasBlur);
  10570. this._onBlur = function () {
  10571. if (_this.disablePerformanceMonitorInBackground) {
  10572. _this._performanceMonitor.disable();
  10573. }
  10574. _this._windowIsBackground = true;
  10575. };
  10576. this._onFocus = function () {
  10577. if (_this.disablePerformanceMonitorInBackground) {
  10578. _this._performanceMonitor.enable();
  10579. }
  10580. _this._windowIsBackground = false;
  10581. };
  10582. this._onCanvasPointerOut = function (ev) {
  10583. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  10584. };
  10585. window.addEventListener("blur", this._onBlur);
  10586. window.addEventListener("focus", this._onFocus);
  10587. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  10588. // Context lost
  10589. if (!this._doNotHandleContextLost) {
  10590. this._onContextLost = function (evt) {
  10591. evt.preventDefault();
  10592. _this._contextWasLost = true;
  10593. BABYLON.Tools.Warn("WebGL context lost.");
  10594. _this.onContextLostObservable.notifyObservers(_this);
  10595. };
  10596. this._onContextRestored = function (evt) {
  10597. // Adding a timeout to avoid race condition at browser level
  10598. setTimeout(function () {
  10599. // Rebuild gl context
  10600. _this._initGLContext();
  10601. // Rebuild effects
  10602. _this._rebuildEffects();
  10603. // Rebuild textures
  10604. _this._rebuildInternalTextures();
  10605. // Rebuild buffers
  10606. _this._rebuildBuffers();
  10607. // Cache
  10608. _this.wipeCaches(true);
  10609. BABYLON.Tools.Warn("WebGL context successfully restored.");
  10610. _this.onContextRestoredObservable.notifyObservers(_this);
  10611. _this._contextWasLost = false;
  10612. }, 0);
  10613. };
  10614. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  10615. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  10616. }
  10617. }
  10618. else {
  10619. this._gl = canvasOrContext;
  10620. this._renderingCanvas = this._gl.canvas;
  10621. if (this._gl.renderbufferStorageMultisample) {
  10622. this._webGLVersion = 2.0;
  10623. }
  10624. options.stencil = this._gl.getContextAttributes().stencil;
  10625. }
  10626. // Viewport
  10627. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  10628. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  10629. this.resize();
  10630. this._isStencilEnable = options.stencil ? true : false;
  10631. this._initGLContext();
  10632. if (canvas) {
  10633. // Fullscreen
  10634. this._onFullscreenChange = function () {
  10635. if (document.fullscreen !== undefined) {
  10636. _this.isFullscreen = document.fullscreen;
  10637. }
  10638. else if (document.mozFullScreen !== undefined) {
  10639. _this.isFullscreen = document.mozFullScreen;
  10640. }
  10641. else if (document.webkitIsFullScreen !== undefined) {
  10642. _this.isFullscreen = document.webkitIsFullScreen;
  10643. }
  10644. else if (document.msIsFullScreen !== undefined) {
  10645. _this.isFullscreen = document.msIsFullScreen;
  10646. }
  10647. // Pointer lock
  10648. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  10649. canvas.requestPointerLock = canvas.requestPointerLock ||
  10650. canvas.msRequestPointerLock ||
  10651. canvas.mozRequestPointerLock ||
  10652. canvas.webkitRequestPointerLock;
  10653. if (canvas.requestPointerLock) {
  10654. canvas.requestPointerLock();
  10655. }
  10656. }
  10657. };
  10658. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  10659. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  10660. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  10661. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  10662. // Pointer lock
  10663. this._onPointerLockChange = function () {
  10664. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  10665. document.webkitPointerLockElement === canvas ||
  10666. document.msPointerLockElement === canvas ||
  10667. document.pointerLockElement === canvas);
  10668. };
  10669. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  10670. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  10671. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  10672. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  10673. this._onVRDisplayPointerRestricted = function () {
  10674. if (canvas) {
  10675. canvas.requestPointerLock();
  10676. }
  10677. };
  10678. this._onVRDisplayPointerUnrestricted = function () {
  10679. document.exitPointerLock();
  10680. };
  10681. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  10682. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  10683. }
  10684. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  10685. Engine.audioEngine = new BABYLON.AudioEngine();
  10686. }
  10687. // Prepare buffer pointers
  10688. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  10689. this._currentBufferPointers[i] = new BufferPointer();
  10690. }
  10691. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  10692. // Load WebVR Devices
  10693. if (options.autoEnableWebVR) {
  10694. this.initWebVR();
  10695. }
  10696. // Detect if we are running on a faulty buggy OS.
  10697. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  10698. // Detect if we are running on a faulty buggy desktop OS.
  10699. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  10700. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  10701. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  10702. }
  10703. Object.defineProperty(Engine, "LastCreatedEngine", {
  10704. get: function () {
  10705. if (Engine.Instances.length === 0) {
  10706. return null;
  10707. }
  10708. return Engine.Instances[Engine.Instances.length - 1];
  10709. },
  10710. enumerable: true,
  10711. configurable: true
  10712. });
  10713. Object.defineProperty(Engine, "LastCreatedScene", {
  10714. get: function () {
  10715. var lastCreatedEngine = Engine.LastCreatedEngine;
  10716. if (!lastCreatedEngine) {
  10717. return null;
  10718. }
  10719. if (lastCreatedEngine.scenes.length === 0) {
  10720. return null;
  10721. }
  10722. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  10723. },
  10724. enumerable: true,
  10725. configurable: true
  10726. });
  10727. /**
  10728. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  10729. */
  10730. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  10731. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  10732. var engine = Engine.Instances[engineIndex];
  10733. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  10734. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  10735. }
  10736. }
  10737. };
  10738. Object.defineProperty(Engine, "NEVER", {
  10739. get: function () {
  10740. return Engine._NEVER;
  10741. },
  10742. enumerable: true,
  10743. configurable: true
  10744. });
  10745. Object.defineProperty(Engine, "ALWAYS", {
  10746. get: function () {
  10747. return Engine._ALWAYS;
  10748. },
  10749. enumerable: true,
  10750. configurable: true
  10751. });
  10752. Object.defineProperty(Engine, "LESS", {
  10753. get: function () {
  10754. return Engine._LESS;
  10755. },
  10756. enumerable: true,
  10757. configurable: true
  10758. });
  10759. Object.defineProperty(Engine, "EQUAL", {
  10760. get: function () {
  10761. return Engine._EQUAL;
  10762. },
  10763. enumerable: true,
  10764. configurable: true
  10765. });
  10766. Object.defineProperty(Engine, "LEQUAL", {
  10767. get: function () {
  10768. return Engine._LEQUAL;
  10769. },
  10770. enumerable: true,
  10771. configurable: true
  10772. });
  10773. Object.defineProperty(Engine, "GREATER", {
  10774. get: function () {
  10775. return Engine._GREATER;
  10776. },
  10777. enumerable: true,
  10778. configurable: true
  10779. });
  10780. Object.defineProperty(Engine, "GEQUAL", {
  10781. get: function () {
  10782. return Engine._GEQUAL;
  10783. },
  10784. enumerable: true,
  10785. configurable: true
  10786. });
  10787. Object.defineProperty(Engine, "NOTEQUAL", {
  10788. get: function () {
  10789. return Engine._NOTEQUAL;
  10790. },
  10791. enumerable: true,
  10792. configurable: true
  10793. });
  10794. Object.defineProperty(Engine, "KEEP", {
  10795. get: function () {
  10796. return Engine._KEEP;
  10797. },
  10798. enumerable: true,
  10799. configurable: true
  10800. });
  10801. Object.defineProperty(Engine, "REPLACE", {
  10802. get: function () {
  10803. return Engine._REPLACE;
  10804. },
  10805. enumerable: true,
  10806. configurable: true
  10807. });
  10808. Object.defineProperty(Engine, "INCR", {
  10809. get: function () {
  10810. return Engine._INCR;
  10811. },
  10812. enumerable: true,
  10813. configurable: true
  10814. });
  10815. Object.defineProperty(Engine, "DECR", {
  10816. get: function () {
  10817. return Engine._DECR;
  10818. },
  10819. enumerable: true,
  10820. configurable: true
  10821. });
  10822. Object.defineProperty(Engine, "INVERT", {
  10823. get: function () {
  10824. return Engine._INVERT;
  10825. },
  10826. enumerable: true,
  10827. configurable: true
  10828. });
  10829. Object.defineProperty(Engine, "INCR_WRAP", {
  10830. get: function () {
  10831. return Engine._INCR_WRAP;
  10832. },
  10833. enumerable: true,
  10834. configurable: true
  10835. });
  10836. Object.defineProperty(Engine, "DECR_WRAP", {
  10837. get: function () {
  10838. return Engine._DECR_WRAP;
  10839. },
  10840. enumerable: true,
  10841. configurable: true
  10842. });
  10843. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  10844. get: function () {
  10845. return Engine._ALPHA_DISABLE;
  10846. },
  10847. enumerable: true,
  10848. configurable: true
  10849. });
  10850. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  10851. get: function () {
  10852. return Engine._ALPHA_ONEONE;
  10853. },
  10854. enumerable: true,
  10855. configurable: true
  10856. });
  10857. Object.defineProperty(Engine, "ALPHA_ADD", {
  10858. get: function () {
  10859. return Engine._ALPHA_ADD;
  10860. },
  10861. enumerable: true,
  10862. configurable: true
  10863. });
  10864. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  10865. get: function () {
  10866. return Engine._ALPHA_COMBINE;
  10867. },
  10868. enumerable: true,
  10869. configurable: true
  10870. });
  10871. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  10872. get: function () {
  10873. return Engine._ALPHA_SUBTRACT;
  10874. },
  10875. enumerable: true,
  10876. configurable: true
  10877. });
  10878. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  10879. get: function () {
  10880. return Engine._ALPHA_MULTIPLY;
  10881. },
  10882. enumerable: true,
  10883. configurable: true
  10884. });
  10885. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  10886. get: function () {
  10887. return Engine._ALPHA_MAXIMIZED;
  10888. },
  10889. enumerable: true,
  10890. configurable: true
  10891. });
  10892. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  10893. get: function () {
  10894. return Engine._ALPHA_PREMULTIPLIED;
  10895. },
  10896. enumerable: true,
  10897. configurable: true
  10898. });
  10899. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  10900. get: function () {
  10901. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  10902. },
  10903. enumerable: true,
  10904. configurable: true
  10905. });
  10906. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  10907. get: function () {
  10908. return Engine._ALPHA_INTERPOLATE;
  10909. },
  10910. enumerable: true,
  10911. configurable: true
  10912. });
  10913. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  10914. get: function () {
  10915. return Engine._ALPHA_SCREENMODE;
  10916. },
  10917. enumerable: true,
  10918. configurable: true
  10919. });
  10920. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  10921. get: function () {
  10922. return Engine._DELAYLOADSTATE_NONE;
  10923. },
  10924. enumerable: true,
  10925. configurable: true
  10926. });
  10927. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  10928. get: function () {
  10929. return Engine._DELAYLOADSTATE_LOADED;
  10930. },
  10931. enumerable: true,
  10932. configurable: true
  10933. });
  10934. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  10935. get: function () {
  10936. return Engine._DELAYLOADSTATE_LOADING;
  10937. },
  10938. enumerable: true,
  10939. configurable: true
  10940. });
  10941. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  10942. get: function () {
  10943. return Engine._DELAYLOADSTATE_NOTLOADED;
  10944. },
  10945. enumerable: true,
  10946. configurable: true
  10947. });
  10948. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  10949. get: function () {
  10950. return Engine._TEXTUREFORMAT_ALPHA;
  10951. },
  10952. enumerable: true,
  10953. configurable: true
  10954. });
  10955. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  10956. get: function () {
  10957. return Engine._TEXTUREFORMAT_LUMINANCE;
  10958. },
  10959. enumerable: true,
  10960. configurable: true
  10961. });
  10962. Object.defineProperty(Engine, "TEXTUREFORMAT_R32F", {
  10963. /**
  10964. * R32F
  10965. */
  10966. get: function () {
  10967. return Engine._TEXTUREFORMAT_R32F;
  10968. },
  10969. enumerable: true,
  10970. configurable: true
  10971. });
  10972. Object.defineProperty(Engine, "TEXTUREFORMAT_RG32F", {
  10973. /**
  10974. * RG32F
  10975. */
  10976. get: function () {
  10977. return Engine._TEXTUREFORMAT_RG32F;
  10978. },
  10979. enumerable: true,
  10980. configurable: true
  10981. });
  10982. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB32F", {
  10983. /**
  10984. * RGB32F
  10985. */
  10986. get: function () {
  10987. return Engine._TEXTUREFORMAT_RGB32F;
  10988. },
  10989. enumerable: true,
  10990. configurable: true
  10991. });
  10992. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA32F", {
  10993. /**
  10994. * RGBA32F
  10995. */
  10996. get: function () {
  10997. return Engine._TEXTUREFORMAT_RGBA32F;
  10998. },
  10999. enumerable: true,
  11000. configurable: true
  11001. });
  11002. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  11003. get: function () {
  11004. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  11005. },
  11006. enumerable: true,
  11007. configurable: true
  11008. });
  11009. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  11010. get: function () {
  11011. return Engine._TEXTUREFORMAT_RGB;
  11012. },
  11013. enumerable: true,
  11014. configurable: true
  11015. });
  11016. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  11017. get: function () {
  11018. return Engine._TEXTUREFORMAT_RGBA;
  11019. },
  11020. enumerable: true,
  11021. configurable: true
  11022. });
  11023. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  11024. get: function () {
  11025. return Engine._TEXTURETYPE_UNSIGNED_INT;
  11026. },
  11027. enumerable: true,
  11028. configurable: true
  11029. });
  11030. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  11031. get: function () {
  11032. return Engine._TEXTURETYPE_FLOAT;
  11033. },
  11034. enumerable: true,
  11035. configurable: true
  11036. });
  11037. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  11038. get: function () {
  11039. return Engine._TEXTURETYPE_HALF_FLOAT;
  11040. },
  11041. enumerable: true,
  11042. configurable: true
  11043. });
  11044. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  11045. get: function () {
  11046. return Engine._SCALEMODE_FLOOR;
  11047. },
  11048. enumerable: true,
  11049. configurable: true
  11050. });
  11051. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  11052. get: function () {
  11053. return Engine._SCALEMODE_NEAREST;
  11054. },
  11055. enumerable: true,
  11056. configurable: true
  11057. });
  11058. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  11059. get: function () {
  11060. return Engine._SCALEMODE_CEILING;
  11061. },
  11062. enumerable: true,
  11063. configurable: true
  11064. });
  11065. Object.defineProperty(Engine, "Version", {
  11066. get: function () {
  11067. return "3.2.0-alpha10";
  11068. },
  11069. enumerable: true,
  11070. configurable: true
  11071. });
  11072. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  11073. get: function () {
  11074. return this._vrExclusivePointerMode;
  11075. },
  11076. enumerable: true,
  11077. configurable: true
  11078. });
  11079. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  11080. get: function () {
  11081. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  11082. },
  11083. enumerable: true,
  11084. configurable: true
  11085. });
  11086. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  11087. get: function () {
  11088. return this._webGLVersion < 2 || this.forcePOTTextures;
  11089. },
  11090. enumerable: true,
  11091. configurable: true
  11092. });
  11093. Object.defineProperty(Engine.prototype, "badOS", {
  11094. get: function () {
  11095. return this._badOS;
  11096. },
  11097. enumerable: true,
  11098. configurable: true
  11099. });
  11100. Object.defineProperty(Engine.prototype, "badDesktopOS", {
  11101. get: function () {
  11102. return this._badDesktopOS;
  11103. },
  11104. enumerable: true,
  11105. configurable: true
  11106. });
  11107. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  11108. get: function () {
  11109. return this._performanceMonitor;
  11110. },
  11111. enumerable: true,
  11112. configurable: true
  11113. });
  11114. Object.defineProperty(Engine.prototype, "texturesSupported", {
  11115. get: function () {
  11116. return this._texturesSupported;
  11117. },
  11118. enumerable: true,
  11119. configurable: true
  11120. });
  11121. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  11122. get: function () {
  11123. return this._textureFormatInUse;
  11124. },
  11125. enumerable: true,
  11126. configurable: true
  11127. });
  11128. Object.defineProperty(Engine.prototype, "currentViewport", {
  11129. get: function () {
  11130. return this._cachedViewport;
  11131. },
  11132. enumerable: true,
  11133. configurable: true
  11134. });
  11135. Object.defineProperty(Engine.prototype, "emptyTexture", {
  11136. // Empty texture
  11137. get: function () {
  11138. if (!this._emptyTexture) {
  11139. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11140. }
  11141. return this._emptyTexture;
  11142. },
  11143. enumerable: true,
  11144. configurable: true
  11145. });
  11146. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  11147. get: function () {
  11148. if (!this._emptyTexture3D) {
  11149. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11150. }
  11151. return this._emptyTexture3D;
  11152. },
  11153. enumerable: true,
  11154. configurable: true
  11155. });
  11156. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  11157. get: function () {
  11158. if (!this._emptyCubeTexture) {
  11159. var faceData = new Uint8Array(4);
  11160. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  11161. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11162. }
  11163. return this._emptyCubeTexture;
  11164. },
  11165. enumerable: true,
  11166. configurable: true
  11167. });
  11168. Engine.prototype._rebuildInternalTextures = function () {
  11169. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  11170. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  11171. var internalTexture = currentState_1[_i];
  11172. internalTexture._rebuild();
  11173. }
  11174. };
  11175. Engine.prototype._rebuildEffects = function () {
  11176. for (var key in this._compiledEffects) {
  11177. var effect = this._compiledEffects[key];
  11178. effect._prepareEffect();
  11179. }
  11180. BABYLON.Effect.ResetCache();
  11181. };
  11182. Engine.prototype._rebuildBuffers = function () {
  11183. // Index / Vertex
  11184. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  11185. var scene = _a[_i];
  11186. scene.resetCachedMaterial();
  11187. scene._rebuildGeometries();
  11188. scene._rebuildTextures();
  11189. }
  11190. // Uniforms
  11191. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  11192. var uniformBuffer = _c[_b];
  11193. uniformBuffer._rebuild();
  11194. }
  11195. };
  11196. Engine.prototype._initGLContext = function () {
  11197. // Caps
  11198. this._caps = new EngineCapabilities();
  11199. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  11200. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  11201. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  11202. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  11203. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  11204. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  11205. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  11206. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  11207. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  11208. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  11209. // Infos
  11210. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  11211. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  11212. if (rendererInfo != null) {
  11213. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  11214. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  11215. }
  11216. if (!this._glVendor) {
  11217. this._glVendor = "Unknown vendor";
  11218. }
  11219. if (!this._glRenderer) {
  11220. this._glRenderer = "Unknown renderer";
  11221. }
  11222. // Constants
  11223. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  11224. if (this._gl.RGBA16F !== 0x881A) {
  11225. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  11226. }
  11227. if (this._gl.RGBA32F !== 0x8814) {
  11228. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  11229. }
  11230. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  11231. this._gl.DEPTH24_STENCIL8 = 35056;
  11232. }
  11233. // Extensions
  11234. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  11235. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  11236. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  11237. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  11238. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  11239. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  11240. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  11241. 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');
  11242. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  11243. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  11244. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  11245. this._caps.highPrecisionShaderSupported = true;
  11246. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  11247. if (this._caps.timerQuery) {
  11248. if (this._webGLVersion === 1) {
  11249. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  11250. }
  11251. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  11252. }
  11253. // Checks if some of the format renders first to allow the use of webgl inspector.
  11254. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  11255. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  11256. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  11257. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  11258. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  11259. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  11260. if (this._webGLVersion > 1) {
  11261. this._gl.HALF_FLOAT_OES = 0x140B;
  11262. }
  11263. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  11264. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  11265. // Draw buffers
  11266. if (this._webGLVersion > 1) {
  11267. this._caps.drawBuffersExtension = true;
  11268. }
  11269. else {
  11270. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  11271. if (drawBuffersExtension !== null) {
  11272. this._caps.drawBuffersExtension = true;
  11273. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  11274. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  11275. for (var i = 0; i < 16; i++) {
  11276. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  11277. }
  11278. }
  11279. else {
  11280. this._caps.drawBuffersExtension = false;
  11281. }
  11282. }
  11283. // Depth Texture
  11284. if (this._webGLVersion > 1) {
  11285. this._caps.depthTextureExtension = true;
  11286. }
  11287. else {
  11288. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  11289. if (depthTextureExtension != null) {
  11290. this._caps.depthTextureExtension = true;
  11291. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  11292. }
  11293. }
  11294. // Vertex array object
  11295. if (this._webGLVersion > 1) {
  11296. this._caps.vertexArrayObject = true;
  11297. }
  11298. else {
  11299. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  11300. if (vertexArrayObjectExtension != null) {
  11301. this._caps.vertexArrayObject = true;
  11302. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  11303. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  11304. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  11305. }
  11306. else {
  11307. this._caps.vertexArrayObject = false;
  11308. }
  11309. }
  11310. // Instances count
  11311. if (this._webGLVersion > 1) {
  11312. this._caps.instancedArrays = true;
  11313. }
  11314. else {
  11315. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  11316. if (instanceExtension != null) {
  11317. this._caps.instancedArrays = true;
  11318. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  11319. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  11320. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  11321. }
  11322. else {
  11323. this._caps.instancedArrays = false;
  11324. }
  11325. }
  11326. // Intelligently add supported compressed formats in order to check for.
  11327. // Check for ASTC support first as it is most powerful and to be very cross platform.
  11328. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  11329. // Likely no hardware which supports both PVR & DXT, so order matters little.
  11330. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  11331. if (this._caps.astc)
  11332. this.texturesSupported.push('-astc.ktx');
  11333. if (this._caps.s3tc)
  11334. this.texturesSupported.push('-dxt.ktx');
  11335. if (this._caps.pvrtc)
  11336. this.texturesSupported.push('-pvrtc.ktx');
  11337. if (this._caps.etc2)
  11338. this.texturesSupported.push('-etc2.ktx');
  11339. if (this._caps.etc1)
  11340. this.texturesSupported.push('-etc1.ktx');
  11341. if (this._gl.getShaderPrecisionFormat) {
  11342. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  11343. if (highp) {
  11344. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  11345. }
  11346. }
  11347. // Depth buffer
  11348. this.setDepthBuffer(true);
  11349. this.setDepthFunctionToLessOrEqual();
  11350. this.setDepthWrite(true);
  11351. // Texture maps
  11352. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  11353. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  11354. this._nextFreeTextureSlots.push(slot);
  11355. }
  11356. };
  11357. Object.defineProperty(Engine.prototype, "webGLVersion", {
  11358. get: function () {
  11359. return this._webGLVersion;
  11360. },
  11361. enumerable: true,
  11362. configurable: true
  11363. });
  11364. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  11365. /**
  11366. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  11367. */
  11368. get: function () {
  11369. return this._isStencilEnable;
  11370. },
  11371. enumerable: true,
  11372. configurable: true
  11373. });
  11374. Engine.prototype._prepareWorkingCanvas = function () {
  11375. if (this._workingCanvas) {
  11376. return;
  11377. }
  11378. this._workingCanvas = document.createElement("canvas");
  11379. var context = this._workingCanvas.getContext("2d");
  11380. if (context) {
  11381. this._workingContext = context;
  11382. }
  11383. };
  11384. Engine.prototype.resetTextureCache = function () {
  11385. for (var key in this._boundTexturesCache) {
  11386. var boundTexture = this._boundTexturesCache[key];
  11387. if (boundTexture) {
  11388. this._removeDesignatedSlot(boundTexture);
  11389. }
  11390. this._boundTexturesCache[key] = null;
  11391. }
  11392. if (!this.disableTextureBindingOptimization) {
  11393. this._nextFreeTextureSlots = [];
  11394. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  11395. this._nextFreeTextureSlots.push(slot);
  11396. }
  11397. }
  11398. this._currentTextureChannel = -1;
  11399. };
  11400. Engine.prototype.isDeterministicLockStep = function () {
  11401. return this._deterministicLockstep;
  11402. };
  11403. Engine.prototype.getLockstepMaxSteps = function () {
  11404. return this._lockstepMaxSteps;
  11405. };
  11406. Engine.prototype.getGlInfo = function () {
  11407. return {
  11408. vendor: this._glVendor,
  11409. renderer: this._glRenderer,
  11410. version: this._glVersion
  11411. };
  11412. };
  11413. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  11414. if (useScreen === void 0) { useScreen = false; }
  11415. var viewport = camera.viewport;
  11416. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  11417. };
  11418. Engine.prototype.getRenderWidth = function (useScreen) {
  11419. if (useScreen === void 0) { useScreen = false; }
  11420. if (!useScreen && this._currentRenderTarget) {
  11421. return this._currentRenderTarget.width;
  11422. }
  11423. return this._gl.drawingBufferWidth;
  11424. };
  11425. Engine.prototype.getRenderHeight = function (useScreen) {
  11426. if (useScreen === void 0) { useScreen = false; }
  11427. if (!useScreen && this._currentRenderTarget) {
  11428. return this._currentRenderTarget.height;
  11429. }
  11430. return this._gl.drawingBufferHeight;
  11431. };
  11432. Engine.prototype.getRenderingCanvas = function () {
  11433. return this._renderingCanvas;
  11434. };
  11435. Engine.prototype.getRenderingCanvasClientRect = function () {
  11436. if (!this._renderingCanvas) {
  11437. return null;
  11438. }
  11439. return this._renderingCanvas.getBoundingClientRect();
  11440. };
  11441. Engine.prototype.setHardwareScalingLevel = function (level) {
  11442. this._hardwareScalingLevel = level;
  11443. this.resize();
  11444. };
  11445. Engine.prototype.getHardwareScalingLevel = function () {
  11446. return this._hardwareScalingLevel;
  11447. };
  11448. Engine.prototype.getLoadedTexturesCache = function () {
  11449. return this._internalTexturesCache;
  11450. };
  11451. Engine.prototype.getCaps = function () {
  11452. return this._caps;
  11453. };
  11454. Object.defineProperty(Engine.prototype, "drawCalls", {
  11455. /** The number of draw calls submitted last frame */
  11456. get: function () {
  11457. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  11458. return 0;
  11459. },
  11460. enumerable: true,
  11461. configurable: true
  11462. });
  11463. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  11464. get: function () {
  11465. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  11466. return null;
  11467. },
  11468. enumerable: true,
  11469. configurable: true
  11470. });
  11471. Engine.prototype.getDepthFunction = function () {
  11472. return this._depthCullingState.depthFunc;
  11473. };
  11474. Engine.prototype.setDepthFunction = function (depthFunc) {
  11475. this._depthCullingState.depthFunc = depthFunc;
  11476. };
  11477. Engine.prototype.setDepthFunctionToGreater = function () {
  11478. this._depthCullingState.depthFunc = this._gl.GREATER;
  11479. };
  11480. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  11481. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  11482. };
  11483. Engine.prototype.setDepthFunctionToLess = function () {
  11484. this._depthCullingState.depthFunc = this._gl.LESS;
  11485. };
  11486. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  11487. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  11488. };
  11489. Engine.prototype.getStencilBuffer = function () {
  11490. return this._stencilState.stencilTest;
  11491. };
  11492. Engine.prototype.setStencilBuffer = function (enable) {
  11493. this._stencilState.stencilTest = enable;
  11494. };
  11495. Engine.prototype.getStencilMask = function () {
  11496. return this._stencilState.stencilMask;
  11497. };
  11498. Engine.prototype.setStencilMask = function (mask) {
  11499. this._stencilState.stencilMask = mask;
  11500. };
  11501. Engine.prototype.getStencilFunction = function () {
  11502. return this._stencilState.stencilFunc;
  11503. };
  11504. Engine.prototype.getStencilFunctionReference = function () {
  11505. return this._stencilState.stencilFuncRef;
  11506. };
  11507. Engine.prototype.getStencilFunctionMask = function () {
  11508. return this._stencilState.stencilFuncMask;
  11509. };
  11510. Engine.prototype.setStencilFunction = function (stencilFunc) {
  11511. this._stencilState.stencilFunc = stencilFunc;
  11512. };
  11513. Engine.prototype.setStencilFunctionReference = function (reference) {
  11514. this._stencilState.stencilFuncRef = reference;
  11515. };
  11516. Engine.prototype.setStencilFunctionMask = function (mask) {
  11517. this._stencilState.stencilFuncMask = mask;
  11518. };
  11519. Engine.prototype.getStencilOperationFail = function () {
  11520. return this._stencilState.stencilOpStencilFail;
  11521. };
  11522. Engine.prototype.getStencilOperationDepthFail = function () {
  11523. return this._stencilState.stencilOpDepthFail;
  11524. };
  11525. Engine.prototype.getStencilOperationPass = function () {
  11526. return this._stencilState.stencilOpStencilDepthPass;
  11527. };
  11528. Engine.prototype.setStencilOperationFail = function (operation) {
  11529. this._stencilState.stencilOpStencilFail = operation;
  11530. };
  11531. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  11532. this._stencilState.stencilOpDepthFail = operation;
  11533. };
  11534. Engine.prototype.setStencilOperationPass = function (operation) {
  11535. this._stencilState.stencilOpStencilDepthPass = operation;
  11536. };
  11537. Engine.prototype.setDitheringState = function (value) {
  11538. if (value) {
  11539. this._gl.enable(this._gl.DITHER);
  11540. }
  11541. else {
  11542. this._gl.disable(this._gl.DITHER);
  11543. }
  11544. };
  11545. Engine.prototype.setRasterizerState = function (value) {
  11546. if (value) {
  11547. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  11548. }
  11549. else {
  11550. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  11551. }
  11552. };
  11553. /**
  11554. * stop executing a render loop function and remove it from the execution array
  11555. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  11556. */
  11557. Engine.prototype.stopRenderLoop = function (renderFunction) {
  11558. if (!renderFunction) {
  11559. this._activeRenderLoops = [];
  11560. return;
  11561. }
  11562. var index = this._activeRenderLoops.indexOf(renderFunction);
  11563. if (index >= 0) {
  11564. this._activeRenderLoops.splice(index, 1);
  11565. }
  11566. };
  11567. Engine.prototype._renderLoop = function () {
  11568. if (!this._contextWasLost) {
  11569. var shouldRender = true;
  11570. if (!this.renderEvenInBackground && this._windowIsBackground) {
  11571. shouldRender = false;
  11572. }
  11573. if (shouldRender) {
  11574. // Start new frame
  11575. this.beginFrame();
  11576. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  11577. var renderFunction = this._activeRenderLoops[index];
  11578. renderFunction();
  11579. }
  11580. // Present
  11581. this.endFrame();
  11582. }
  11583. }
  11584. if (this._activeRenderLoops.length > 0) {
  11585. // Register new frame
  11586. var requester = null;
  11587. if (this._vrDisplay && this._vrDisplay.isPresenting)
  11588. requester = this._vrDisplay;
  11589. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  11590. }
  11591. else {
  11592. this._renderingQueueLaunched = false;
  11593. }
  11594. };
  11595. /**
  11596. * Register and execute a render loop. The engine can have more than one render function.
  11597. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  11598. * @example
  11599. * engine.runRenderLoop(function () {
  11600. * scene.render()
  11601. * })
  11602. */
  11603. Engine.prototype.runRenderLoop = function (renderFunction) {
  11604. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  11605. return;
  11606. }
  11607. this._activeRenderLoops.push(renderFunction);
  11608. if (!this._renderingQueueLaunched) {
  11609. this._renderingQueueLaunched = true;
  11610. this._bindedRenderFunction = this._renderLoop.bind(this);
  11611. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  11612. }
  11613. };
  11614. /**
  11615. * Toggle full screen mode.
  11616. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  11617. * @param {any} options - an options object to be sent to the requestFullscreen function
  11618. */
  11619. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  11620. if (this.isFullscreen) {
  11621. BABYLON.Tools.ExitFullscreen();
  11622. }
  11623. else {
  11624. this._pointerLockRequested = requestPointerLock;
  11625. if (this._renderingCanvas) {
  11626. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  11627. }
  11628. }
  11629. };
  11630. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  11631. if (stencil === void 0) { stencil = false; }
  11632. this.applyStates();
  11633. var mode = 0;
  11634. if (backBuffer && color) {
  11635. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  11636. mode |= this._gl.COLOR_BUFFER_BIT;
  11637. }
  11638. if (depth) {
  11639. this._gl.clearDepth(1.0);
  11640. mode |= this._gl.DEPTH_BUFFER_BIT;
  11641. }
  11642. if (stencil) {
  11643. this._gl.clearStencil(0);
  11644. mode |= this._gl.STENCIL_BUFFER_BIT;
  11645. }
  11646. this._gl.clear(mode);
  11647. };
  11648. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  11649. var gl = this._gl;
  11650. // Save state
  11651. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  11652. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  11653. // Change state
  11654. gl.enable(gl.SCISSOR_TEST);
  11655. gl.scissor(x, y, width, height);
  11656. // Clear
  11657. this.clear(clearColor, true, true, true);
  11658. // Restore state
  11659. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  11660. if (curScissor === true) {
  11661. gl.enable(gl.SCISSOR_TEST);
  11662. }
  11663. else {
  11664. gl.disable(gl.SCISSOR_TEST);
  11665. }
  11666. };
  11667. /**
  11668. * Set the WebGL's viewport
  11669. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  11670. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  11671. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  11672. */
  11673. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  11674. var width = requiredWidth || this.getRenderWidth();
  11675. var height = requiredHeight || this.getRenderHeight();
  11676. var x = viewport.x || 0;
  11677. var y = viewport.y || 0;
  11678. this._cachedViewport = viewport;
  11679. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  11680. };
  11681. /**
  11682. * Directly set the WebGL Viewport
  11683. * The x, y, width & height are directly passed to the WebGL call
  11684. * @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.
  11685. */
  11686. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  11687. var currentViewport = this._cachedViewport;
  11688. this._cachedViewport = null;
  11689. this._gl.viewport(x, y, width, height);
  11690. return currentViewport;
  11691. };
  11692. Engine.prototype.beginFrame = function () {
  11693. this.onBeginFrameObservable.notifyObservers(this);
  11694. this._measureFps();
  11695. };
  11696. Engine.prototype.endFrame = function () {
  11697. //force a flush in case we are using a bad OS.
  11698. if (this._badOS) {
  11699. this.flushFramebuffer();
  11700. }
  11701. //submit frame to the vr device, if enabled
  11702. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  11703. // TODO: We should only submit the frame if we read frameData successfully.
  11704. this._vrDisplay.submitFrame();
  11705. }
  11706. this.onEndFrameObservable.notifyObservers(this);
  11707. };
  11708. /**
  11709. * resize the view according to the canvas' size.
  11710. * @example
  11711. * window.addEventListener("resize", function () {
  11712. * engine.resize();
  11713. * });
  11714. */
  11715. Engine.prototype.resize = function () {
  11716. // We're not resizing the size of the canvas while in VR mode & presenting
  11717. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  11718. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  11719. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  11720. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  11721. }
  11722. };
  11723. /**
  11724. * force a specific size of the canvas
  11725. * @param {number} width - the new canvas' width
  11726. * @param {number} height - the new canvas' height
  11727. */
  11728. Engine.prototype.setSize = function (width, height) {
  11729. if (!this._renderingCanvas) {
  11730. return;
  11731. }
  11732. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  11733. return;
  11734. }
  11735. this._renderingCanvas.width = width;
  11736. this._renderingCanvas.height = height;
  11737. for (var index = 0; index < this.scenes.length; index++) {
  11738. var scene = this.scenes[index];
  11739. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  11740. var cam = scene.cameras[camIndex];
  11741. cam._currentRenderId = 0;
  11742. }
  11743. }
  11744. if (this.onResizeObservable.hasObservers) {
  11745. this.onResizeObservable.notifyObservers(this);
  11746. }
  11747. };
  11748. // WebVR functions
  11749. Engine.prototype.isVRDevicePresent = function () {
  11750. return !!this._vrDisplay;
  11751. };
  11752. Engine.prototype.getVRDevice = function () {
  11753. return this._vrDisplay;
  11754. };
  11755. /**
  11756. * Initializes a webVR display and starts listening to display change events.
  11757. * The onVRDisplayChangedObservable will be notified upon these changes.
  11758. * @returns The onVRDisplayChangedObservable.
  11759. */
  11760. Engine.prototype.initWebVR = function () {
  11761. this.initWebVRAsync();
  11762. return this.onVRDisplayChangedObservable;
  11763. };
  11764. /**
  11765. * Initializes a webVR display and starts listening to display change events.
  11766. * The onVRDisplayChangedObservable will be notified upon these changes.
  11767. * @returns A promise containing a VRDisplay and if vr is supported.
  11768. */
  11769. Engine.prototype.initWebVRAsync = function () {
  11770. var _this = this;
  11771. var notifyObservers = function () {
  11772. var eventArgs = {
  11773. vrDisplay: _this._vrDisplay,
  11774. vrSupported: _this._vrSupported
  11775. };
  11776. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  11777. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  11778. };
  11779. if (!this._onVrDisplayConnect) {
  11780. this._onVrDisplayConnect = function (event) {
  11781. _this._vrDisplay = event.display;
  11782. notifyObservers();
  11783. };
  11784. this._onVrDisplayDisconnect = function () {
  11785. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  11786. _this._vrDisplay = undefined;
  11787. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  11788. notifyObservers();
  11789. };
  11790. this._onVrDisplayPresentChange = function () {
  11791. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  11792. };
  11793. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  11794. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  11795. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  11796. }
  11797. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  11798. this._webVRInitPromise.then(notifyObservers);
  11799. return this._webVRInitPromise;
  11800. };
  11801. Engine.prototype.enableVR = function () {
  11802. var _this = this;
  11803. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  11804. var onResolved = function () {
  11805. _this.onVRRequestPresentComplete.notifyObservers(true);
  11806. _this._onVRFullScreenTriggered();
  11807. };
  11808. var onRejected = function () {
  11809. _this.onVRRequestPresentComplete.notifyObservers(false);
  11810. };
  11811. this.onVRRequestPresentStart.notifyObservers(this);
  11812. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  11813. }
  11814. };
  11815. Engine.prototype.disableVR = function () {
  11816. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  11817. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  11818. }
  11819. };
  11820. Engine.prototype._getVRDisplaysAsync = function () {
  11821. var _this = this;
  11822. return new Promise(function (res, rej) {
  11823. if (navigator.getVRDisplays) {
  11824. navigator.getVRDisplays().then(function (devices) {
  11825. _this._vrSupported = true;
  11826. // note that devices may actually be an empty array. This is fine;
  11827. // we expect this._vrDisplay to be undefined in this case.
  11828. _this._vrDisplay = devices[0];
  11829. res({
  11830. vrDisplay: _this._vrDisplay,
  11831. vrSupported: _this._vrSupported
  11832. });
  11833. });
  11834. }
  11835. else {
  11836. _this._vrDisplay = undefined;
  11837. _this._vrSupported = false;
  11838. res({
  11839. vrDisplay: _this._vrDisplay,
  11840. vrSupported: _this._vrSupported
  11841. });
  11842. }
  11843. });
  11844. };
  11845. /**
  11846. * Binds the frame buffer to the specified texture.
  11847. * @param texture The texture to render to or null for the default canvas
  11848. * @param faceIndex The face of the texture to render to in case of cube texture
  11849. * @param requiredWidth The width of the target to render to
  11850. * @param requiredHeight The height of the target to render to
  11851. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  11852. * @param depthStencilTexture The depth stencil texture to use to render
  11853. */
  11854. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture) {
  11855. if (this._currentRenderTarget) {
  11856. this.unBindFramebuffer(this._currentRenderTarget);
  11857. }
  11858. this._currentRenderTarget = texture;
  11859. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  11860. var gl = this._gl;
  11861. if (texture.isCube) {
  11862. if (faceIndex === undefined) {
  11863. faceIndex = 0;
  11864. }
  11865. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  11866. if (depthStencilTexture) {
  11867. if (depthStencilTexture._generateStencilBuffer) {
  11868. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture, 0);
  11869. }
  11870. else {
  11871. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture, 0);
  11872. }
  11873. }
  11874. }
  11875. if (this._cachedViewport && !forceFullscreenViewport) {
  11876. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  11877. }
  11878. else {
  11879. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  11880. }
  11881. this.wipeCaches();
  11882. };
  11883. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  11884. if (this._currentFramebuffer !== framebuffer) {
  11885. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  11886. this._currentFramebuffer = framebuffer;
  11887. }
  11888. };
  11889. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  11890. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  11891. this._currentRenderTarget = null;
  11892. // If MSAA, we need to bitblt back to main texture
  11893. var gl = this._gl;
  11894. if (texture._MSAAFramebuffer) {
  11895. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  11896. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  11897. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  11898. }
  11899. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  11900. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  11901. gl.generateMipmap(gl.TEXTURE_2D);
  11902. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  11903. }
  11904. if (onBeforeUnbind) {
  11905. if (texture._MSAAFramebuffer) {
  11906. // Bind the correct framebuffer
  11907. this.bindUnboundFramebuffer(texture._framebuffer);
  11908. }
  11909. onBeforeUnbind();
  11910. }
  11911. this.bindUnboundFramebuffer(null);
  11912. };
  11913. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  11914. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  11915. this._currentRenderTarget = null;
  11916. // If MSAA, we need to bitblt back to main texture
  11917. var gl = this._gl;
  11918. if (textures[0]._MSAAFramebuffer) {
  11919. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  11920. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  11921. var attachments = textures[0]._attachments;
  11922. if (!attachments) {
  11923. attachments = new Array(textures.length);
  11924. textures[0]._attachments = attachments;
  11925. }
  11926. for (var i = 0; i < textures.length; i++) {
  11927. var texture = textures[i];
  11928. for (var j = 0; j < attachments.length; j++) {
  11929. attachments[j] = gl.NONE;
  11930. }
  11931. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  11932. gl.readBuffer(attachments[i]);
  11933. gl.drawBuffers(attachments);
  11934. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  11935. }
  11936. for (var i = 0; i < attachments.length; i++) {
  11937. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  11938. }
  11939. gl.drawBuffers(attachments);
  11940. }
  11941. for (var i = 0; i < textures.length; i++) {
  11942. var texture = textures[i];
  11943. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  11944. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  11945. gl.generateMipmap(gl.TEXTURE_2D);
  11946. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  11947. }
  11948. }
  11949. if (onBeforeUnbind) {
  11950. if (textures[0]._MSAAFramebuffer) {
  11951. // Bind the correct framebuffer
  11952. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  11953. }
  11954. onBeforeUnbind();
  11955. }
  11956. this.bindUnboundFramebuffer(null);
  11957. };
  11958. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  11959. if (texture.generateMipMaps) {
  11960. var gl = this._gl;
  11961. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  11962. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  11963. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  11964. }
  11965. };
  11966. Engine.prototype.flushFramebuffer = function () {
  11967. this._gl.flush();
  11968. };
  11969. Engine.prototype.restoreDefaultFramebuffer = function () {
  11970. if (this._currentRenderTarget) {
  11971. this.unBindFramebuffer(this._currentRenderTarget);
  11972. }
  11973. else {
  11974. this.bindUnboundFramebuffer(null);
  11975. }
  11976. if (this._cachedViewport) {
  11977. this.setViewport(this._cachedViewport);
  11978. }
  11979. this.wipeCaches();
  11980. };
  11981. // UBOs
  11982. Engine.prototype.createUniformBuffer = function (elements) {
  11983. var ubo = this._gl.createBuffer();
  11984. if (!ubo) {
  11985. throw new Error("Unable to create uniform buffer");
  11986. }
  11987. this.bindUniformBuffer(ubo);
  11988. if (elements instanceof Float32Array) {
  11989. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  11990. }
  11991. else {
  11992. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  11993. }
  11994. this.bindUniformBuffer(null);
  11995. ubo.references = 1;
  11996. return ubo;
  11997. };
  11998. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  11999. var ubo = this._gl.createBuffer();
  12000. if (!ubo) {
  12001. throw new Error("Unable to create dynamic uniform buffer");
  12002. }
  12003. this.bindUniformBuffer(ubo);
  12004. if (elements instanceof Float32Array) {
  12005. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  12006. }
  12007. else {
  12008. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  12009. }
  12010. this.bindUniformBuffer(null);
  12011. ubo.references = 1;
  12012. return ubo;
  12013. };
  12014. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  12015. this.bindUniformBuffer(uniformBuffer);
  12016. if (offset === undefined) {
  12017. offset = 0;
  12018. }
  12019. if (count === undefined) {
  12020. if (elements instanceof Float32Array) {
  12021. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  12022. }
  12023. else {
  12024. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  12025. }
  12026. }
  12027. else {
  12028. if (elements instanceof Float32Array) {
  12029. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  12030. }
  12031. else {
  12032. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  12033. }
  12034. }
  12035. this.bindUniformBuffer(null);
  12036. };
  12037. // VBOs
  12038. Engine.prototype._resetVertexBufferBinding = function () {
  12039. this.bindArrayBuffer(null);
  12040. this._cachedVertexBuffers = null;
  12041. };
  12042. Engine.prototype.createVertexBuffer = function (vertices) {
  12043. var vbo = this._gl.createBuffer();
  12044. if (!vbo) {
  12045. throw new Error("Unable to create vertex buffer");
  12046. }
  12047. this.bindArrayBuffer(vbo);
  12048. if (vertices instanceof Float32Array) {
  12049. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  12050. }
  12051. else {
  12052. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  12053. }
  12054. this._resetVertexBufferBinding();
  12055. vbo.references = 1;
  12056. return vbo;
  12057. };
  12058. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  12059. var vbo = this._gl.createBuffer();
  12060. if (!vbo) {
  12061. throw new Error("Unable to create dynamic vertex buffer");
  12062. }
  12063. this.bindArrayBuffer(vbo);
  12064. if (vertices instanceof Float32Array) {
  12065. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  12066. }
  12067. else {
  12068. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  12069. }
  12070. this._resetVertexBufferBinding();
  12071. vbo.references = 1;
  12072. return vbo;
  12073. };
  12074. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  12075. if (offset === void 0) { offset = 0; }
  12076. // Force cache update
  12077. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  12078. this.bindIndexBuffer(indexBuffer);
  12079. var arrayBuffer;
  12080. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  12081. arrayBuffer = indices;
  12082. }
  12083. else {
  12084. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  12085. }
  12086. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  12087. this._resetIndexBufferBinding();
  12088. };
  12089. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  12090. this.bindArrayBuffer(vertexBuffer);
  12091. if (offset === undefined) {
  12092. offset = 0;
  12093. }
  12094. if (count === undefined) {
  12095. if (vertices instanceof Float32Array) {
  12096. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  12097. }
  12098. else {
  12099. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  12100. }
  12101. }
  12102. else {
  12103. if (vertices instanceof Float32Array) {
  12104. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  12105. }
  12106. else {
  12107. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  12108. }
  12109. }
  12110. this._resetVertexBufferBinding();
  12111. };
  12112. Engine.prototype._resetIndexBufferBinding = function () {
  12113. this.bindIndexBuffer(null);
  12114. this._cachedIndexBuffer = null;
  12115. };
  12116. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  12117. var vbo = this._gl.createBuffer();
  12118. if (!vbo) {
  12119. throw new Error("Unable to create index buffer");
  12120. }
  12121. this.bindIndexBuffer(vbo);
  12122. // Check for 32 bits indices
  12123. var arrayBuffer;
  12124. var need32Bits = false;
  12125. if (indices instanceof Uint16Array) {
  12126. arrayBuffer = indices;
  12127. }
  12128. else {
  12129. //check 32 bit support
  12130. if (this._caps.uintIndices) {
  12131. if (indices instanceof Uint32Array) {
  12132. arrayBuffer = indices;
  12133. need32Bits = true;
  12134. }
  12135. else {
  12136. //number[] or Int32Array, check if 32 bit is necessary
  12137. for (var index = 0; index < indices.length; index++) {
  12138. if (indices[index] > 65535) {
  12139. need32Bits = true;
  12140. break;
  12141. }
  12142. }
  12143. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  12144. }
  12145. }
  12146. else {
  12147. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  12148. arrayBuffer = new Uint16Array(indices);
  12149. }
  12150. }
  12151. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  12152. this._resetIndexBufferBinding();
  12153. vbo.references = 1;
  12154. vbo.is32Bits = need32Bits;
  12155. return vbo;
  12156. };
  12157. Engine.prototype.bindArrayBuffer = function (buffer) {
  12158. if (!this._vaoRecordInProgress) {
  12159. this._unbindVertexArrayObject();
  12160. }
  12161. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  12162. };
  12163. Engine.prototype.bindUniformBuffer = function (buffer) {
  12164. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  12165. };
  12166. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  12167. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  12168. };
  12169. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  12170. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  12171. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  12172. };
  12173. ;
  12174. Engine.prototype.bindIndexBuffer = function (buffer) {
  12175. if (!this._vaoRecordInProgress) {
  12176. this._unbindVertexArrayObject();
  12177. }
  12178. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  12179. };
  12180. Engine.prototype.bindBuffer = function (buffer, target) {
  12181. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  12182. this._gl.bindBuffer(target, buffer);
  12183. this._currentBoundBuffer[target] = buffer;
  12184. }
  12185. };
  12186. Engine.prototype.updateArrayBuffer = function (data) {
  12187. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  12188. };
  12189. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  12190. var pointer = this._currentBufferPointers[indx];
  12191. var changed = false;
  12192. if (!pointer.active) {
  12193. changed = true;
  12194. pointer.active = true;
  12195. pointer.index = indx;
  12196. pointer.size = size;
  12197. pointer.type = type;
  12198. pointer.normalized = normalized;
  12199. pointer.stride = stride;
  12200. pointer.offset = offset;
  12201. pointer.buffer = buffer;
  12202. }
  12203. else {
  12204. if (pointer.buffer !== buffer) {
  12205. pointer.buffer = buffer;
  12206. changed = true;
  12207. }
  12208. if (pointer.size !== size) {
  12209. pointer.size = size;
  12210. changed = true;
  12211. }
  12212. if (pointer.type !== type) {
  12213. pointer.type = type;
  12214. changed = true;
  12215. }
  12216. if (pointer.normalized !== normalized) {
  12217. pointer.normalized = normalized;
  12218. changed = true;
  12219. }
  12220. if (pointer.stride !== stride) {
  12221. pointer.stride = stride;
  12222. changed = true;
  12223. }
  12224. if (pointer.offset !== offset) {
  12225. pointer.offset = offset;
  12226. changed = true;
  12227. }
  12228. }
  12229. if (changed || this._vaoRecordInProgress) {
  12230. this.bindArrayBuffer(buffer);
  12231. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  12232. }
  12233. };
  12234. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  12235. if (indexBuffer == null) {
  12236. return;
  12237. }
  12238. if (this._cachedIndexBuffer !== indexBuffer) {
  12239. this._cachedIndexBuffer = indexBuffer;
  12240. this.bindIndexBuffer(indexBuffer);
  12241. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  12242. }
  12243. };
  12244. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  12245. var attributes = effect.getAttributesNames();
  12246. if (!this._vaoRecordInProgress) {
  12247. this._unbindVertexArrayObject();
  12248. }
  12249. this.unbindAllAttributes();
  12250. for (var index = 0; index < attributes.length; index++) {
  12251. var order = effect.getAttributeLocation(index);
  12252. if (order >= 0) {
  12253. var vertexBuffer = vertexBuffers[attributes[index]];
  12254. if (!vertexBuffer) {
  12255. continue;
  12256. }
  12257. this._gl.enableVertexAttribArray(order);
  12258. if (!this._vaoRecordInProgress) {
  12259. this._vertexAttribArraysEnabled[order] = true;
  12260. }
  12261. var buffer = vertexBuffer.getBuffer();
  12262. if (buffer) {
  12263. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  12264. if (vertexBuffer.getIsInstanced()) {
  12265. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  12266. if (!this._vaoRecordInProgress) {
  12267. this._currentInstanceLocations.push(order);
  12268. this._currentInstanceBuffers.push(buffer);
  12269. }
  12270. }
  12271. }
  12272. }
  12273. }
  12274. };
  12275. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  12276. var vao = this._gl.createVertexArray();
  12277. this._vaoRecordInProgress = true;
  12278. this._gl.bindVertexArray(vao);
  12279. this._mustWipeVertexAttributes = true;
  12280. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  12281. this.bindIndexBuffer(indexBuffer);
  12282. this._vaoRecordInProgress = false;
  12283. this._gl.bindVertexArray(null);
  12284. return vao;
  12285. };
  12286. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  12287. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  12288. this._cachedVertexArrayObject = vertexArrayObject;
  12289. this._gl.bindVertexArray(vertexArrayObject);
  12290. this._cachedVertexBuffers = null;
  12291. this._cachedIndexBuffer = null;
  12292. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  12293. this._mustWipeVertexAttributes = true;
  12294. }
  12295. };
  12296. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  12297. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  12298. this._cachedVertexBuffers = vertexBuffer;
  12299. this._cachedEffectForVertexBuffers = effect;
  12300. var attributesCount = effect.getAttributesCount();
  12301. this._unbindVertexArrayObject();
  12302. this.unbindAllAttributes();
  12303. var offset = 0;
  12304. for (var index = 0; index < attributesCount; index++) {
  12305. if (index < vertexDeclaration.length) {
  12306. var order = effect.getAttributeLocation(index);
  12307. if (order >= 0) {
  12308. this._gl.enableVertexAttribArray(order);
  12309. this._vertexAttribArraysEnabled[order] = true;
  12310. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  12311. }
  12312. offset += vertexDeclaration[index] * 4;
  12313. }
  12314. }
  12315. }
  12316. this._bindIndexBufferWithCache(indexBuffer);
  12317. };
  12318. Engine.prototype._unbindVertexArrayObject = function () {
  12319. if (!this._cachedVertexArrayObject) {
  12320. return;
  12321. }
  12322. this._cachedVertexArrayObject = null;
  12323. this._gl.bindVertexArray(null);
  12324. };
  12325. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  12326. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  12327. this._cachedVertexBuffers = vertexBuffers;
  12328. this._cachedEffectForVertexBuffers = effect;
  12329. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  12330. }
  12331. this._bindIndexBufferWithCache(indexBuffer);
  12332. };
  12333. Engine.prototype.unbindInstanceAttributes = function () {
  12334. var boundBuffer;
  12335. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  12336. var instancesBuffer = this._currentInstanceBuffers[i];
  12337. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  12338. boundBuffer = instancesBuffer;
  12339. this.bindArrayBuffer(instancesBuffer);
  12340. }
  12341. var offsetLocation = this._currentInstanceLocations[i];
  12342. this._gl.vertexAttribDivisor(offsetLocation, 0);
  12343. }
  12344. this._currentInstanceBuffers.length = 0;
  12345. this._currentInstanceLocations.length = 0;
  12346. };
  12347. Engine.prototype.releaseVertexArrayObject = function (vao) {
  12348. this._gl.deleteVertexArray(vao);
  12349. };
  12350. Engine.prototype._releaseBuffer = function (buffer) {
  12351. buffer.references--;
  12352. if (buffer.references === 0) {
  12353. this._gl.deleteBuffer(buffer);
  12354. return true;
  12355. }
  12356. return false;
  12357. };
  12358. Engine.prototype.createInstancesBuffer = function (capacity) {
  12359. var buffer = this._gl.createBuffer();
  12360. if (!buffer) {
  12361. throw new Error("Unable to create instance buffer");
  12362. }
  12363. buffer.capacity = capacity;
  12364. this.bindArrayBuffer(buffer);
  12365. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  12366. return buffer;
  12367. };
  12368. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  12369. this._gl.deleteBuffer(buffer);
  12370. };
  12371. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  12372. this.bindArrayBuffer(instancesBuffer);
  12373. if (data) {
  12374. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  12375. }
  12376. if (offsetLocations[0].index !== undefined) {
  12377. var stride = 0;
  12378. for (var i = 0; i < offsetLocations.length; i++) {
  12379. var ai = offsetLocations[i];
  12380. stride += ai.attributeSize * 4;
  12381. }
  12382. for (var i = 0; i < offsetLocations.length; i++) {
  12383. var ai = offsetLocations[i];
  12384. if (!this._vertexAttribArraysEnabled[ai.index]) {
  12385. this._gl.enableVertexAttribArray(ai.index);
  12386. this._vertexAttribArraysEnabled[ai.index] = true;
  12387. }
  12388. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  12389. this._gl.vertexAttribDivisor(ai.index, 1);
  12390. this._currentInstanceLocations.push(ai.index);
  12391. this._currentInstanceBuffers.push(instancesBuffer);
  12392. }
  12393. }
  12394. else {
  12395. for (var index = 0; index < 4; index++) {
  12396. var offsetLocation = offsetLocations[index];
  12397. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  12398. this._gl.enableVertexAttribArray(offsetLocation);
  12399. this._vertexAttribArraysEnabled[offsetLocation] = true;
  12400. }
  12401. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  12402. this._gl.vertexAttribDivisor(offsetLocation, 1);
  12403. this._currentInstanceLocations.push(offsetLocation);
  12404. this._currentInstanceBuffers.push(instancesBuffer);
  12405. }
  12406. }
  12407. };
  12408. Engine.prototype.applyStates = function () {
  12409. this._depthCullingState.apply(this._gl);
  12410. this._stencilState.apply(this._gl);
  12411. this._alphaState.apply(this._gl);
  12412. };
  12413. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  12414. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  12415. };
  12416. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  12417. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  12418. };
  12419. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  12420. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  12421. };
  12422. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  12423. // Apply states
  12424. this.applyStates();
  12425. this._drawCalls.addCount(1, false);
  12426. // Render
  12427. var drawMode = this.DrawMode(fillMode);
  12428. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  12429. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  12430. if (instancesCount) {
  12431. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  12432. }
  12433. else {
  12434. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  12435. }
  12436. };
  12437. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  12438. // Apply states
  12439. this.applyStates();
  12440. this._drawCalls.addCount(1, false);
  12441. var drawMode = this.DrawMode(fillMode);
  12442. if (instancesCount) {
  12443. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  12444. }
  12445. else {
  12446. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  12447. }
  12448. };
  12449. Engine.prototype.DrawMode = function (fillMode) {
  12450. switch (fillMode) {
  12451. // Triangle views
  12452. case BABYLON.Material.TriangleFillMode:
  12453. return this._gl.TRIANGLES;
  12454. case BABYLON.Material.PointFillMode:
  12455. return this._gl.POINTS;
  12456. case BABYLON.Material.WireFrameFillMode:
  12457. return this._gl.LINES;
  12458. // Draw modes
  12459. case BABYLON.Material.PointListDrawMode:
  12460. return this._gl.POINTS;
  12461. case BABYLON.Material.LineListDrawMode:
  12462. return this._gl.LINES;
  12463. case BABYLON.Material.LineLoopDrawMode:
  12464. return this._gl.LINE_LOOP;
  12465. case BABYLON.Material.LineStripDrawMode:
  12466. return this._gl.LINE_STRIP;
  12467. case BABYLON.Material.TriangleStripDrawMode:
  12468. return this._gl.TRIANGLE_STRIP;
  12469. case BABYLON.Material.TriangleFanDrawMode:
  12470. return this._gl.TRIANGLE_FAN;
  12471. default:
  12472. return this._gl.TRIANGLES;
  12473. }
  12474. };
  12475. // Shaders
  12476. Engine.prototype._releaseEffect = function (effect) {
  12477. if (this._compiledEffects[effect._key]) {
  12478. delete this._compiledEffects[effect._key];
  12479. this._deleteProgram(effect.getProgram());
  12480. }
  12481. };
  12482. Engine.prototype._deleteProgram = function (program) {
  12483. if (program) {
  12484. program.__SPECTOR_rebuildProgram = null;
  12485. if (program.transformFeedback) {
  12486. this.deleteTransformFeedback(program.transformFeedback);
  12487. program.transformFeedback = null;
  12488. }
  12489. this._gl.deleteProgram(program);
  12490. }
  12491. };
  12492. /**
  12493. * @param baseName The base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  12494. * @param samplers An array of string used to represent textures
  12495. */
  12496. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  12497. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  12498. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  12499. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  12500. if (this._compiledEffects[name]) {
  12501. var compiledEffect = this._compiledEffects[name];
  12502. if (onCompiled && compiledEffect.isReady()) {
  12503. onCompiled(compiledEffect);
  12504. }
  12505. return compiledEffect;
  12506. }
  12507. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  12508. effect._key = name;
  12509. this._compiledEffects[name] = effect;
  12510. return effect;
  12511. };
  12512. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  12513. if (uniformsNames === void 0) { uniformsNames = []; }
  12514. if (samplers === void 0) { samplers = []; }
  12515. if (defines === void 0) { defines = ""; }
  12516. return this.createEffect({
  12517. vertex: "particles",
  12518. fragmentElement: fragmentName
  12519. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  12520. };
  12521. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  12522. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12523. context = context || this._gl;
  12524. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  12525. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  12526. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  12527. };
  12528. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  12529. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12530. context = context || this._gl;
  12531. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  12532. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  12533. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  12534. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  12535. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  12536. this.onAfterShaderCompilationObservable.notifyObservers(this);
  12537. return program;
  12538. };
  12539. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  12540. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12541. var shaderProgram = context.createProgram();
  12542. if (!shaderProgram) {
  12543. throw new Error("Unable to create program");
  12544. }
  12545. context.attachShader(shaderProgram, vertexShader);
  12546. context.attachShader(shaderProgram, fragmentShader);
  12547. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  12548. var transformFeedback = this.createTransformFeedback();
  12549. this.bindTransformFeedback(transformFeedback);
  12550. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  12551. shaderProgram.transformFeedback = transformFeedback;
  12552. }
  12553. context.linkProgram(shaderProgram);
  12554. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  12555. this.bindTransformFeedback(null);
  12556. }
  12557. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  12558. if (!linked) {
  12559. context.validateProgram(shaderProgram);
  12560. var error = context.getProgramInfoLog(shaderProgram);
  12561. if (error) {
  12562. throw new Error(error);
  12563. }
  12564. }
  12565. context.deleteShader(vertexShader);
  12566. context.deleteShader(fragmentShader);
  12567. return shaderProgram;
  12568. };
  12569. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  12570. var results = new Array();
  12571. for (var index = 0; index < uniformsNames.length; index++) {
  12572. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  12573. }
  12574. return results;
  12575. };
  12576. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  12577. var results = [];
  12578. for (var index = 0; index < attributesNames.length; index++) {
  12579. try {
  12580. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  12581. }
  12582. catch (e) {
  12583. results.push(-1);
  12584. }
  12585. }
  12586. return results;
  12587. };
  12588. Engine.prototype.enableEffect = function (effect) {
  12589. if (!effect) {
  12590. return;
  12591. }
  12592. // Use program
  12593. this.bindSamplers(effect);
  12594. this._currentEffect = effect;
  12595. if (effect.onBind) {
  12596. effect.onBind(effect);
  12597. }
  12598. effect.onBindObservable.notifyObservers(effect);
  12599. };
  12600. Engine.prototype.setIntArray = function (uniform, array) {
  12601. if (!uniform)
  12602. return;
  12603. this._gl.uniform1iv(uniform, array);
  12604. };
  12605. Engine.prototype.setIntArray2 = function (uniform, array) {
  12606. if (!uniform || array.length % 2 !== 0)
  12607. return;
  12608. this._gl.uniform2iv(uniform, array);
  12609. };
  12610. Engine.prototype.setIntArray3 = function (uniform, array) {
  12611. if (!uniform || array.length % 3 !== 0)
  12612. return;
  12613. this._gl.uniform3iv(uniform, array);
  12614. };
  12615. Engine.prototype.setIntArray4 = function (uniform, array) {
  12616. if (!uniform || array.length % 4 !== 0)
  12617. return;
  12618. this._gl.uniform4iv(uniform, array);
  12619. };
  12620. Engine.prototype.setFloatArray = function (uniform, array) {
  12621. if (!uniform)
  12622. return;
  12623. this._gl.uniform1fv(uniform, array);
  12624. };
  12625. Engine.prototype.setFloatArray2 = function (uniform, array) {
  12626. if (!uniform || array.length % 2 !== 0)
  12627. return;
  12628. this._gl.uniform2fv(uniform, array);
  12629. };
  12630. Engine.prototype.setFloatArray3 = function (uniform, array) {
  12631. if (!uniform || array.length % 3 !== 0)
  12632. return;
  12633. this._gl.uniform3fv(uniform, array);
  12634. };
  12635. Engine.prototype.setFloatArray4 = function (uniform, array) {
  12636. if (!uniform || array.length % 4 !== 0)
  12637. return;
  12638. this._gl.uniform4fv(uniform, array);
  12639. };
  12640. Engine.prototype.setArray = function (uniform, array) {
  12641. if (!uniform)
  12642. return;
  12643. this._gl.uniform1fv(uniform, array);
  12644. };
  12645. Engine.prototype.setArray2 = function (uniform, array) {
  12646. if (!uniform || array.length % 2 !== 0)
  12647. return;
  12648. this._gl.uniform2fv(uniform, array);
  12649. };
  12650. Engine.prototype.setArray3 = function (uniform, array) {
  12651. if (!uniform || array.length % 3 !== 0)
  12652. return;
  12653. this._gl.uniform3fv(uniform, array);
  12654. };
  12655. Engine.prototype.setArray4 = function (uniform, array) {
  12656. if (!uniform || array.length % 4 !== 0)
  12657. return;
  12658. this._gl.uniform4fv(uniform, array);
  12659. };
  12660. Engine.prototype.setMatrices = function (uniform, matrices) {
  12661. if (!uniform)
  12662. return;
  12663. this._gl.uniformMatrix4fv(uniform, false, matrices);
  12664. };
  12665. Engine.prototype.setMatrix = function (uniform, matrix) {
  12666. if (!uniform)
  12667. return;
  12668. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  12669. };
  12670. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  12671. if (!uniform)
  12672. return;
  12673. this._gl.uniformMatrix3fv(uniform, false, matrix);
  12674. };
  12675. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  12676. if (!uniform)
  12677. return;
  12678. this._gl.uniformMatrix2fv(uniform, false, matrix);
  12679. };
  12680. Engine.prototype.setInt = function (uniform, value) {
  12681. if (!uniform)
  12682. return;
  12683. this._gl.uniform1i(uniform, value);
  12684. };
  12685. Engine.prototype.setFloat = function (uniform, value) {
  12686. if (!uniform)
  12687. return;
  12688. this._gl.uniform1f(uniform, value);
  12689. };
  12690. Engine.prototype.setFloat2 = function (uniform, x, y) {
  12691. if (!uniform)
  12692. return;
  12693. this._gl.uniform2f(uniform, x, y);
  12694. };
  12695. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  12696. if (!uniform)
  12697. return;
  12698. this._gl.uniform3f(uniform, x, y, z);
  12699. };
  12700. Engine.prototype.setBool = function (uniform, bool) {
  12701. if (!uniform)
  12702. return;
  12703. this._gl.uniform1i(uniform, bool);
  12704. };
  12705. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  12706. if (!uniform)
  12707. return;
  12708. this._gl.uniform4f(uniform, x, y, z, w);
  12709. };
  12710. Engine.prototype.setColor3 = function (uniform, color3) {
  12711. if (!uniform)
  12712. return;
  12713. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  12714. };
  12715. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  12716. if (!uniform)
  12717. return;
  12718. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  12719. };
  12720. /**
  12721. * Sets a Color4 on a uniform variable
  12722. * @param uniform defines the uniform location
  12723. * @param color4 defines the value to be set
  12724. */
  12725. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  12726. if (!uniform)
  12727. return;
  12728. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  12729. };
  12730. // States
  12731. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  12732. if (zOffset === void 0) { zOffset = 0; }
  12733. if (reverseSide === void 0) { reverseSide = false; }
  12734. // Culling
  12735. if (this._depthCullingState.cull !== culling || force) {
  12736. this._depthCullingState.cull = culling;
  12737. }
  12738. // Cull face
  12739. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  12740. if (this._depthCullingState.cullFace !== cullFace || force) {
  12741. this._depthCullingState.cullFace = cullFace;
  12742. }
  12743. // Z offset
  12744. this.setZOffset(zOffset);
  12745. // Front face
  12746. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  12747. if (this._depthCullingState.frontFace !== frontFace || force) {
  12748. this._depthCullingState.frontFace = frontFace;
  12749. }
  12750. };
  12751. Engine.prototype.setZOffset = function (value) {
  12752. this._depthCullingState.zOffset = value;
  12753. };
  12754. Engine.prototype.getZOffset = function () {
  12755. return this._depthCullingState.zOffset;
  12756. };
  12757. Engine.prototype.setDepthBuffer = function (enable) {
  12758. this._depthCullingState.depthTest = enable;
  12759. };
  12760. Engine.prototype.getDepthWrite = function () {
  12761. return this._depthCullingState.depthMask;
  12762. };
  12763. Engine.prototype.setDepthWrite = function (enable) {
  12764. this._depthCullingState.depthMask = enable;
  12765. };
  12766. Engine.prototype.setColorWrite = function (enable) {
  12767. this._gl.colorMask(enable, enable, enable, enable);
  12768. this._colorWrite = enable;
  12769. };
  12770. Engine.prototype.getColorWrite = function () {
  12771. return this._colorWrite;
  12772. };
  12773. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  12774. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  12775. };
  12776. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  12777. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  12778. if (this._alphaMode === mode) {
  12779. return;
  12780. }
  12781. switch (mode) {
  12782. case Engine.ALPHA_DISABLE:
  12783. this._alphaState.alphaBlend = false;
  12784. break;
  12785. case Engine.ALPHA_PREMULTIPLIED:
  12786. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  12787. this._alphaState.alphaBlend = true;
  12788. break;
  12789. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  12790. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  12791. this._alphaState.alphaBlend = true;
  12792. break;
  12793. case Engine.ALPHA_COMBINE:
  12794. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  12795. this._alphaState.alphaBlend = true;
  12796. break;
  12797. case Engine.ALPHA_ONEONE:
  12798. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  12799. this._alphaState.alphaBlend = true;
  12800. break;
  12801. case Engine.ALPHA_ADD:
  12802. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  12803. this._alphaState.alphaBlend = true;
  12804. break;
  12805. case Engine.ALPHA_SUBTRACT:
  12806. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  12807. this._alphaState.alphaBlend = true;
  12808. break;
  12809. case Engine.ALPHA_MULTIPLY:
  12810. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  12811. this._alphaState.alphaBlend = true;
  12812. break;
  12813. case Engine.ALPHA_MAXIMIZED:
  12814. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  12815. this._alphaState.alphaBlend = true;
  12816. break;
  12817. case Engine.ALPHA_INTERPOLATE:
  12818. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  12819. this._alphaState.alphaBlend = true;
  12820. break;
  12821. case Engine.ALPHA_SCREENMODE:
  12822. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  12823. this._alphaState.alphaBlend = true;
  12824. break;
  12825. }
  12826. if (!noDepthWriteChange) {
  12827. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  12828. }
  12829. this._alphaMode = mode;
  12830. };
  12831. Engine.prototype.getAlphaMode = function () {
  12832. return this._alphaMode;
  12833. };
  12834. // Textures
  12835. Engine.prototype.wipeCaches = function (bruteForce) {
  12836. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  12837. return;
  12838. }
  12839. this._currentEffect = null;
  12840. // 6/8/2017: deltakosh: Should not be required anymore.
  12841. // This message is then mostly for the future myself who will scream out loud when seeing that it was actually required :)
  12842. if (bruteForce) {
  12843. this.resetTextureCache();
  12844. this._currentProgram = null;
  12845. this._stencilState.reset();
  12846. this._depthCullingState.reset();
  12847. this.setDepthFunctionToLessOrEqual();
  12848. this._alphaState.reset();
  12849. }
  12850. this._resetVertexBufferBinding();
  12851. this._cachedIndexBuffer = null;
  12852. this._cachedEffectForVertexBuffers = null;
  12853. this._unbindVertexArrayObject();
  12854. this.bindIndexBuffer(null);
  12855. };
  12856. /**
  12857. * Set the compressed texture format to use, based on the formats you have, and the formats
  12858. * supported by the hardware / browser.
  12859. *
  12860. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  12861. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  12862. * to API arguments needed to compressed textures. This puts the burden on the container
  12863. * generator to house the arcane code for determining these for current & future formats.
  12864. *
  12865. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  12866. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  12867. *
  12868. * Note: The result of this call is not taken into account when a texture is base64.
  12869. *
  12870. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  12871. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  12872. *
  12873. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  12874. * @returns The extension selected.
  12875. */
  12876. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  12877. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  12878. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  12879. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  12880. return this._textureFormatInUse = this._texturesSupported[i];
  12881. }
  12882. }
  12883. }
  12884. // actively set format to nothing, to allow this to be called more than once
  12885. // and possibly fail the 2nd time
  12886. this._textureFormatInUse = null;
  12887. return null;
  12888. };
  12889. Engine.prototype._createTexture = function () {
  12890. var texture = this._gl.createTexture();
  12891. if (!texture) {
  12892. throw new Error("Unable to create texture");
  12893. }
  12894. return texture;
  12895. };
  12896. /**
  12897. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  12898. * @param {string} urlArg- This contains one of the following:
  12899. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  12900. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  12901. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  12902. *
  12903. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  12904. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  12905. * @param {Scene} scene- Needed for loading to the correct scene.
  12906. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  12907. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  12908. * @param {callback} onError- Optional callback to be called upon failure.
  12909. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  12910. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  12911. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  12912. *
  12913. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  12914. */
  12915. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  12916. var _this = this;
  12917. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  12918. if (onLoad === void 0) { onLoad = null; }
  12919. if (onError === void 0) { onError = null; }
  12920. if (buffer === void 0) { buffer = null; }
  12921. if (fallBack === void 0) { fallBack = null; }
  12922. if (format === void 0) { format = null; }
  12923. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  12924. var fromData = url.substr(0, 5) === "data:";
  12925. var fromBlob = url.substr(0, 5) === "blob:";
  12926. var isBase64 = fromData && url.indexOf("base64") !== -1;
  12927. var texture = fallBack ? fallBack : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  12928. // establish the file extension, if possible
  12929. var lastDot = url.lastIndexOf('.');
  12930. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  12931. var isDDS = this.getCaps().s3tc && (extension.indexOf(".dds") === 0);
  12932. var isTGA = (extension.indexOf(".tga") === 0);
  12933. // determine if a ktx file should be substituted
  12934. var isKTX = false;
  12935. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  12936. url = url.substring(0, lastDot) + this._textureFormatInUse;
  12937. isKTX = true;
  12938. }
  12939. if (scene) {
  12940. scene._addPendingData(texture);
  12941. }
  12942. texture.url = url;
  12943. texture.generateMipMaps = !noMipmap;
  12944. texture.samplingMode = samplingMode;
  12945. texture.invertY = invertY;
  12946. if (!this._doNotHandleContextLost) {
  12947. // Keep a link to the buffer only if we plan to handle context lost
  12948. texture._buffer = buffer;
  12949. }
  12950. var onLoadObserver = null;
  12951. if (onLoad && !fallBack) {
  12952. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  12953. }
  12954. if (!fallBack)
  12955. this._internalTexturesCache.push(texture);
  12956. var onerror = function (message, exception) {
  12957. if (scene) {
  12958. scene._removePendingData(texture);
  12959. }
  12960. if (onLoadObserver) {
  12961. texture.onLoadedObservable.remove(onLoadObserver);
  12962. }
  12963. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  12964. if (isKTX) {
  12965. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  12966. }
  12967. else if (BABYLON.Tools.UseFallbackTexture) {
  12968. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  12969. }
  12970. if (onError) {
  12971. onError(message || "Unknown error", exception);
  12972. }
  12973. };
  12974. var callback = null;
  12975. // processing for non-image formats
  12976. if (isKTX || isTGA || isDDS) {
  12977. if (isKTX) {
  12978. callback = function (data) {
  12979. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  12980. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  12981. ktx.uploadLevels(_this._gl, !noMipmap);
  12982. return false;
  12983. }, samplingMode);
  12984. };
  12985. }
  12986. else if (isTGA) {
  12987. callback = function (arrayBuffer) {
  12988. var data = new Uint8Array(arrayBuffer);
  12989. var header = BABYLON.TGATools.GetTGAHeader(data);
  12990. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  12991. BABYLON.TGATools.UploadContent(_this._gl, data);
  12992. return false;
  12993. }, samplingMode);
  12994. };
  12995. }
  12996. else if (isDDS) {
  12997. callback = function (data) {
  12998. var info = BABYLON.DDSTools.GetDDSInfo(data);
  12999. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  13000. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  13001. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  13002. return false;
  13003. }, samplingMode);
  13004. };
  13005. }
  13006. if (!buffer) {
  13007. this._loadFile(url, function (data) {
  13008. if (callback) {
  13009. callback(data);
  13010. }
  13011. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  13012. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  13013. });
  13014. }
  13015. else {
  13016. if (callback) {
  13017. callback(buffer);
  13018. }
  13019. }
  13020. // image format processing
  13021. }
  13022. else {
  13023. var onload = function (img) {
  13024. if (fromBlob && !_this._doNotHandleContextLost) {
  13025. // We need to store the image if we need to rebuild the texture
  13026. // in case of a webgl context lost
  13027. texture._buffer = img;
  13028. }
  13029. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  13030. var gl = _this._gl;
  13031. var isPot = (img.width === potWidth && img.height === potHeight);
  13032. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  13033. if (isPot) {
  13034. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  13035. return false;
  13036. }
  13037. // Using shaders to rescale because canvas.drawImage is lossy
  13038. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  13039. _this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  13040. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  13041. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  13042. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  13043. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13044. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13045. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  13046. _this._releaseTexture(source);
  13047. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13048. continuationCallback();
  13049. });
  13050. return true;
  13051. }, samplingMode);
  13052. };
  13053. if (!fromData || isBase64)
  13054. if (buffer instanceof HTMLImageElement) {
  13055. onload(buffer);
  13056. }
  13057. else {
  13058. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  13059. }
  13060. else if (buffer instanceof Array || typeof buffer === "string" || buffer instanceof ArrayBuffer)
  13061. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  13062. else
  13063. onload(buffer);
  13064. }
  13065. return texture;
  13066. };
  13067. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  13068. var _this = this;
  13069. var rtt = this.createRenderTargetTexture({
  13070. width: destination.width,
  13071. height: destination.height,
  13072. }, {
  13073. generateMipMaps: false,
  13074. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  13075. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  13076. generateDepthBuffer: false,
  13077. generateStencilBuffer: false
  13078. });
  13079. if (!this._rescalePostProcess) {
  13080. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  13081. }
  13082. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  13083. _this._rescalePostProcess.onApply = function (effect) {
  13084. effect._bindTexture("textureSampler", source);
  13085. };
  13086. var hostingScene = scene;
  13087. if (!hostingScene) {
  13088. hostingScene = _this.scenes[_this.scenes.length - 1];
  13089. }
  13090. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  13091. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  13092. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  13093. _this.unBindFramebuffer(rtt);
  13094. _this._releaseTexture(rtt);
  13095. if (onComplete) {
  13096. onComplete();
  13097. }
  13098. });
  13099. };
  13100. Engine.prototype._getInternalFormat = function (format) {
  13101. var internalFormat = this._gl.RGBA;
  13102. switch (format) {
  13103. case Engine.TEXTUREFORMAT_ALPHA:
  13104. internalFormat = this._gl.ALPHA;
  13105. break;
  13106. case Engine.TEXTUREFORMAT_LUMINANCE:
  13107. internalFormat = this._gl.LUMINANCE;
  13108. break;
  13109. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  13110. internalFormat = this._gl.LUMINANCE_ALPHA;
  13111. break;
  13112. case Engine.TEXTUREFORMAT_RGB:
  13113. case Engine.TEXTUREFORMAT_RGB32F:
  13114. internalFormat = this._gl.RGB;
  13115. break;
  13116. case Engine.TEXTUREFORMAT_RGBA:
  13117. case Engine.TEXTUREFORMAT_RGBA32F:
  13118. internalFormat = this._gl.RGBA;
  13119. break;
  13120. case Engine.TEXTUREFORMAT_R32F:
  13121. internalFormat = this._gl.RED;
  13122. break;
  13123. case Engine.TEXTUREFORMAT_RG32F:
  13124. internalFormat = this._gl.RG;
  13125. break;
  13126. }
  13127. return internalFormat;
  13128. };
  13129. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  13130. if (compression === void 0) { compression = null; }
  13131. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  13132. if (!texture) {
  13133. return;
  13134. }
  13135. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  13136. var internalFormat = this._getInternalFormat(format);
  13137. var textureType = this._getWebGLTextureType(type);
  13138. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13139. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  13140. if (!this._doNotHandleContextLost) {
  13141. texture._bufferView = data;
  13142. texture.format = format;
  13143. texture.type = type;
  13144. texture.invertY = invertY;
  13145. texture._compression = compression;
  13146. }
  13147. if (texture.width % 4 !== 0) {
  13148. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  13149. }
  13150. if (compression && data) {
  13151. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  13152. }
  13153. else {
  13154. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  13155. }
  13156. if (texture.generateMipMaps) {
  13157. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13158. }
  13159. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13160. // this.resetTextureCache();
  13161. texture.isReady = true;
  13162. };
  13163. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  13164. if (compression === void 0) { compression = null; }
  13165. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  13166. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  13167. texture.baseWidth = width;
  13168. texture.baseHeight = height;
  13169. texture.width = width;
  13170. texture.height = height;
  13171. texture.format = format;
  13172. texture.generateMipMaps = generateMipMaps;
  13173. texture.samplingMode = samplingMode;
  13174. texture.invertY = invertY;
  13175. texture._compression = compression;
  13176. texture.type = type;
  13177. if (!this._doNotHandleContextLost) {
  13178. texture._bufferView = data;
  13179. }
  13180. this.updateRawTexture(texture, data, format, invertY, compression, type);
  13181. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13182. // Filters
  13183. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  13184. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13185. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13186. if (generateMipMaps) {
  13187. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13188. }
  13189. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13190. this._internalTexturesCache.push(texture);
  13191. return texture;
  13192. };
  13193. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  13194. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  13195. texture.baseWidth = width;
  13196. texture.baseHeight = height;
  13197. if (generateMipMaps) {
  13198. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  13199. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  13200. }
  13201. // this.resetTextureCache();
  13202. texture.width = width;
  13203. texture.height = height;
  13204. texture.isReady = false;
  13205. texture.generateMipMaps = generateMipMaps;
  13206. texture.samplingMode = samplingMode;
  13207. this.updateTextureSamplingMode(samplingMode, texture);
  13208. this._internalTexturesCache.push(texture);
  13209. return texture;
  13210. };
  13211. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  13212. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  13213. if (texture.isCube) {
  13214. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  13215. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13216. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13217. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  13218. }
  13219. else if (texture.is3D) {
  13220. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  13221. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13222. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13223. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  13224. }
  13225. else {
  13226. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13227. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13228. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13229. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13230. }
  13231. texture.samplingMode = samplingMode;
  13232. };
  13233. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  13234. if (premulAlpha === void 0) { premulAlpha = false; }
  13235. if (!texture) {
  13236. return;
  13237. }
  13238. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13239. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  13240. if (premulAlpha) {
  13241. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  13242. }
  13243. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  13244. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  13245. if (texture.generateMipMaps) {
  13246. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13247. }
  13248. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13249. if (premulAlpha) {
  13250. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  13251. }
  13252. texture.isReady = true;
  13253. };
  13254. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  13255. if (!texture || texture._isDisabled) {
  13256. return;
  13257. }
  13258. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13259. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  13260. try {
  13261. // Testing video texture support
  13262. if (this._videoTextureSupported === undefined) {
  13263. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  13264. if (this._gl.getError() !== 0) {
  13265. this._videoTextureSupported = false;
  13266. }
  13267. else {
  13268. this._videoTextureSupported = true;
  13269. }
  13270. }
  13271. // Copy video through the current working canvas if video texture is not supported
  13272. if (!this._videoTextureSupported) {
  13273. if (!texture._workingCanvas) {
  13274. texture._workingCanvas = document.createElement("canvas");
  13275. var context = texture._workingCanvas.getContext("2d");
  13276. if (!context) {
  13277. throw new Error("Unable to get 2d context");
  13278. }
  13279. texture._workingContext = context;
  13280. texture._workingCanvas.width = texture.width;
  13281. texture._workingCanvas.height = texture.height;
  13282. }
  13283. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  13284. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  13285. }
  13286. else {
  13287. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  13288. }
  13289. if (texture.generateMipMaps) {
  13290. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13291. }
  13292. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13293. // this.resetTextureCache();
  13294. texture.isReady = true;
  13295. }
  13296. catch (ex) {
  13297. // Something unexpected
  13298. // Let's disable the texture
  13299. texture._isDisabled = true;
  13300. }
  13301. };
  13302. /**
  13303. * Updates a depth texture Comparison Mode and Function.
  13304. * If the comparison Function is equal to 0, the mode will be set to none.
  13305. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  13306. * @param texture The texture to set the comparison function for
  13307. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  13308. */
  13309. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  13310. if (this.webGLVersion === 1) {
  13311. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  13312. return;
  13313. }
  13314. var gl = this._gl;
  13315. if (texture.isCube) {
  13316. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  13317. if (comparisonFunction === 0) {
  13318. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  13319. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  13320. }
  13321. else {
  13322. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  13323. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  13324. }
  13325. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  13326. }
  13327. else {
  13328. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13329. if (comparisonFunction === 0) {
  13330. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  13331. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  13332. }
  13333. else {
  13334. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  13335. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  13336. }
  13337. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13338. }
  13339. texture._comparisonFunction = comparisonFunction;
  13340. };
  13341. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  13342. var width = size.width || size;
  13343. var height = size.height || size;
  13344. internalTexture.baseWidth = width;
  13345. internalTexture.baseHeight = height;
  13346. internalTexture.width = width;
  13347. internalTexture.height = height;
  13348. internalTexture.isReady = true;
  13349. internalTexture.samples = 1;
  13350. internalTexture.generateMipMaps = false;
  13351. internalTexture._generateDepthBuffer = true;
  13352. internalTexture._generateStencilBuffer = generateStencil;
  13353. internalTexture.samplingMode = bilinearFiltering ? BABYLON.Texture.NEAREST_SAMPLINGMODE : BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  13354. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13355. internalTexture._comparisonFunction = comparisonFunction;
  13356. var gl = this._gl;
  13357. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  13358. var samplingParameters = getSamplingParameters(internalTexture.samplingMode, false, gl);
  13359. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  13360. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  13361. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13362. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13363. if (comparisonFunction === 0) {
  13364. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  13365. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  13366. }
  13367. else {
  13368. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  13369. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  13370. }
  13371. };
  13372. /**
  13373. * Creates a depth stencil texture.
  13374. * This is only available in WebGL 2 or with the depth texture extension available.
  13375. * @param size The size of face edge in the texture.
  13376. * @param options The options defining the texture.
  13377. * @returns The texture
  13378. */
  13379. Engine.prototype.createDepthStencilTexture = function (size, options) {
  13380. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  13381. if (!this._caps.depthTextureExtension) {
  13382. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  13383. return internalTexture;
  13384. }
  13385. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  13386. var gl = this._gl;
  13387. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  13388. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  13389. if (this.webGLVersion > 1) {
  13390. if (internalOptions.generateStencil) {
  13391. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  13392. }
  13393. else {
  13394. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  13395. }
  13396. }
  13397. else {
  13398. if (internalOptions.generateStencil) {
  13399. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  13400. }
  13401. else {
  13402. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  13403. }
  13404. }
  13405. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13406. return internalTexture;
  13407. };
  13408. /**
  13409. * Creates a depth stencil cube texture.
  13410. * This is only available in WebGL 2.
  13411. * @param size The size of face edge in the cube texture.
  13412. * @param options The options defining the cube texture.
  13413. * @returns The cube texture
  13414. */
  13415. Engine.prototype.createDepthStencilCubeTexture = function (size, options) {
  13416. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  13417. internalTexture.isCube = true;
  13418. if (this.webGLVersion === 1) {
  13419. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  13420. return internalTexture;
  13421. }
  13422. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  13423. var gl = this._gl;
  13424. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  13425. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  13426. // Create the depth/stencil buffer
  13427. for (var face = 0; face < 6; face++) {
  13428. if (internalOptions.generateStencil) {
  13429. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH24_STENCIL8, size, size, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  13430. }
  13431. else {
  13432. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  13433. }
  13434. }
  13435. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13436. return internalTexture;
  13437. };
  13438. /**
  13439. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  13440. * @param renderTarget The render target to set the frame buffer for
  13441. */
  13442. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  13443. // Create the framebuffer
  13444. var internalTexture = renderTarget.getInternalTexture();
  13445. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  13446. return;
  13447. }
  13448. var gl = this._gl;
  13449. var depthStencilTexture = renderTarget.depthStencilTexture;
  13450. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  13451. if (depthStencilTexture.isCube) {
  13452. if (depthStencilTexture._generateStencilBuffer) {
  13453. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture, 0);
  13454. }
  13455. else {
  13456. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture, 0);
  13457. }
  13458. }
  13459. else {
  13460. if (depthStencilTexture._generateStencilBuffer) {
  13461. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture, 0);
  13462. }
  13463. else {
  13464. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture, 0);
  13465. }
  13466. }
  13467. this.bindUnboundFramebuffer(null);
  13468. };
  13469. Engine.prototype.createRenderTargetTexture = function (size, options) {
  13470. var fullOptions = new RenderTargetCreationOptions();
  13471. if (options !== undefined && typeof options === "object") {
  13472. fullOptions.generateMipMaps = options.generateMipMaps;
  13473. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  13474. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  13475. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  13476. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  13477. }
  13478. else {
  13479. fullOptions.generateMipMaps = options;
  13480. fullOptions.generateDepthBuffer = true;
  13481. fullOptions.generateStencilBuffer = false;
  13482. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13483. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  13484. }
  13485. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13486. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13487. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13488. }
  13489. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13490. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13491. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13492. }
  13493. var gl = this._gl;
  13494. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  13495. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13496. var width = size.width || size;
  13497. var height = size.height || size;
  13498. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  13499. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13500. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13501. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  13502. }
  13503. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  13504. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  13505. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13506. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13507. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type), width, height, 0, gl.RGBA, this._getWebGLTextureType(fullOptions.type), null);
  13508. // Create the framebuffer
  13509. var framebuffer = gl.createFramebuffer();
  13510. this.bindUnboundFramebuffer(framebuffer);
  13511. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  13512. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  13513. if (fullOptions.generateMipMaps) {
  13514. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13515. }
  13516. // Unbind
  13517. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13518. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13519. this.bindUnboundFramebuffer(null);
  13520. texture._framebuffer = framebuffer;
  13521. texture.baseWidth = width;
  13522. texture.baseHeight = height;
  13523. texture.width = width;
  13524. texture.height = height;
  13525. texture.isReady = true;
  13526. texture.samples = 1;
  13527. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  13528. texture.samplingMode = fullOptions.samplingMode;
  13529. texture.type = fullOptions.type;
  13530. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  13531. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  13532. // this.resetTextureCache();
  13533. this._internalTexturesCache.push(texture);
  13534. return texture;
  13535. };
  13536. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  13537. var generateMipMaps = false;
  13538. var generateDepthBuffer = true;
  13539. var generateStencilBuffer = false;
  13540. var generateDepthTexture = false;
  13541. var textureCount = 1;
  13542. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  13543. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  13544. var types = [], samplingModes = [];
  13545. if (options !== undefined) {
  13546. generateMipMaps = options.generateMipMaps;
  13547. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  13548. generateStencilBuffer = options.generateStencilBuffer;
  13549. generateDepthTexture = options.generateDepthTexture;
  13550. textureCount = options.textureCount || 1;
  13551. if (options.types) {
  13552. types = options.types;
  13553. }
  13554. if (options.samplingModes) {
  13555. samplingModes = options.samplingModes;
  13556. }
  13557. }
  13558. var gl = this._gl;
  13559. // Create the framebuffer
  13560. var framebuffer = gl.createFramebuffer();
  13561. this.bindUnboundFramebuffer(framebuffer);
  13562. var width = size.width || size;
  13563. var height = size.height || size;
  13564. var textures = [];
  13565. var attachments = [];
  13566. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  13567. for (var i = 0; i < textureCount; i++) {
  13568. var samplingMode = samplingModes[i] || defaultSamplingMode;
  13569. var type = types[i] || defaultType;
  13570. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13571. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13572. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13573. }
  13574. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13575. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13576. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13577. }
  13578. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  13579. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13580. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13581. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  13582. }
  13583. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  13584. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13585. textures.push(texture);
  13586. attachments.push(attachment);
  13587. gl.activeTexture(gl["TEXTURE" + i]);
  13588. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  13589. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  13590. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  13591. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13592. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13593. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  13594. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  13595. if (generateMipMaps) {
  13596. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13597. }
  13598. // Unbind
  13599. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13600. texture._framebuffer = framebuffer;
  13601. texture._depthStencilBuffer = depthStencilBuffer;
  13602. texture.baseWidth = width;
  13603. texture.baseHeight = height;
  13604. texture.width = width;
  13605. texture.height = height;
  13606. texture.isReady = true;
  13607. texture.samples = 1;
  13608. texture.generateMipMaps = generateMipMaps;
  13609. texture.samplingMode = samplingMode;
  13610. texture.type = type;
  13611. texture._generateDepthBuffer = generateDepthBuffer;
  13612. texture._generateStencilBuffer = generateStencilBuffer;
  13613. texture._attachments = attachments;
  13614. this._internalTexturesCache.push(texture);
  13615. }
  13616. if (generateDepthTexture && this._caps.depthTextureExtension) {
  13617. // Depth texture
  13618. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  13619. gl.activeTexture(gl.TEXTURE0);
  13620. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  13621. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  13622. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  13623. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13624. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13625. 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);
  13626. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  13627. depthTexture._framebuffer = framebuffer;
  13628. depthTexture.baseWidth = width;
  13629. depthTexture.baseHeight = height;
  13630. depthTexture.width = width;
  13631. depthTexture.height = height;
  13632. depthTexture.isReady = true;
  13633. depthTexture.samples = 1;
  13634. depthTexture.generateMipMaps = generateMipMaps;
  13635. depthTexture.samplingMode = gl.NEAREST;
  13636. depthTexture._generateDepthBuffer = generateDepthBuffer;
  13637. depthTexture._generateStencilBuffer = generateStencilBuffer;
  13638. textures.push(depthTexture);
  13639. this._internalTexturesCache.push(depthTexture);
  13640. }
  13641. gl.drawBuffers(attachments);
  13642. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13643. this.bindUnboundFramebuffer(null);
  13644. this.resetTextureCache();
  13645. return textures;
  13646. };
  13647. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  13648. if (samples === void 0) { samples = 1; }
  13649. var depthStencilBuffer = null;
  13650. var gl = this._gl;
  13651. // Create the depth/stencil buffer
  13652. if (generateStencilBuffer) {
  13653. depthStencilBuffer = gl.createRenderbuffer();
  13654. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  13655. if (samples > 1) {
  13656. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  13657. }
  13658. else {
  13659. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  13660. }
  13661. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  13662. }
  13663. else if (generateDepthBuffer) {
  13664. depthStencilBuffer = gl.createRenderbuffer();
  13665. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  13666. if (samples > 1) {
  13667. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  13668. }
  13669. else {
  13670. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  13671. }
  13672. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  13673. }
  13674. return depthStencilBuffer;
  13675. };
  13676. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  13677. if (this.webGLVersion < 2 || !texture) {
  13678. return 1;
  13679. }
  13680. if (texture.samples === samples) {
  13681. return samples;
  13682. }
  13683. var gl = this._gl;
  13684. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  13685. // Dispose previous render buffers
  13686. if (texture._depthStencilBuffer) {
  13687. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  13688. texture._depthStencilBuffer = null;
  13689. }
  13690. if (texture._MSAAFramebuffer) {
  13691. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  13692. texture._MSAAFramebuffer = null;
  13693. }
  13694. if (texture._MSAARenderBuffer) {
  13695. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  13696. texture._MSAARenderBuffer = null;
  13697. }
  13698. if (samples > 1) {
  13699. var framebuffer = gl.createFramebuffer();
  13700. if (!framebuffer) {
  13701. throw new Error("Unable to create multi sampled framebuffer");
  13702. }
  13703. texture._MSAAFramebuffer = framebuffer;
  13704. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  13705. var colorRenderbuffer = gl.createRenderbuffer();
  13706. if (!colorRenderbuffer) {
  13707. throw new Error("Unable to create multi sampled framebuffer");
  13708. }
  13709. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  13710. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  13711. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  13712. texture._MSAARenderBuffer = colorRenderbuffer;
  13713. }
  13714. else {
  13715. this.bindUnboundFramebuffer(texture._framebuffer);
  13716. }
  13717. texture.samples = samples;
  13718. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  13719. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13720. this.bindUnboundFramebuffer(null);
  13721. return samples;
  13722. };
  13723. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  13724. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  13725. return 1;
  13726. }
  13727. if (textures[0].samples === samples) {
  13728. return samples;
  13729. }
  13730. var gl = this._gl;
  13731. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  13732. // Dispose previous render buffers
  13733. if (textures[0]._depthStencilBuffer) {
  13734. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  13735. textures[0]._depthStencilBuffer = null;
  13736. }
  13737. if (textures[0]._MSAAFramebuffer) {
  13738. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  13739. textures[0]._MSAAFramebuffer = null;
  13740. }
  13741. for (var i = 0; i < textures.length; i++) {
  13742. if (textures[i]._MSAARenderBuffer) {
  13743. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  13744. textures[i]._MSAARenderBuffer = null;
  13745. }
  13746. }
  13747. if (samples > 1) {
  13748. var framebuffer = gl.createFramebuffer();
  13749. if (!framebuffer) {
  13750. throw new Error("Unable to create multi sampled framebuffer");
  13751. }
  13752. this.bindUnboundFramebuffer(framebuffer);
  13753. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  13754. var attachments = [];
  13755. for (var i = 0; i < textures.length; i++) {
  13756. var texture = textures[i];
  13757. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13758. var colorRenderbuffer = gl.createRenderbuffer();
  13759. if (!colorRenderbuffer) {
  13760. throw new Error("Unable to create multi sampled framebuffer");
  13761. }
  13762. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  13763. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  13764. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  13765. texture._MSAAFramebuffer = framebuffer;
  13766. texture._MSAARenderBuffer = colorRenderbuffer;
  13767. texture.samples = samples;
  13768. texture._depthStencilBuffer = depthStencilBuffer;
  13769. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13770. attachments.push(attachment);
  13771. }
  13772. gl.drawBuffers(attachments);
  13773. }
  13774. else {
  13775. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  13776. }
  13777. this.bindUnboundFramebuffer(null);
  13778. return samples;
  13779. };
  13780. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  13781. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  13782. };
  13783. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  13784. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  13785. };
  13786. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  13787. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE }, options);
  13788. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  13789. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13790. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13791. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13792. }
  13793. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13794. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13795. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13796. }
  13797. var gl = this._gl;
  13798. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  13799. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13800. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps, gl);
  13801. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13802. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13803. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  13804. }
  13805. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  13806. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  13807. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13808. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13809. for (var face = 0; face < 6; face++) {
  13810. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, this._getRGBABufferInternalSizedFormat(fullOptions.type), size, size, 0, gl.RGBA, this._getWebGLTextureType(fullOptions.type), null);
  13811. }
  13812. // Create the framebuffer
  13813. var framebuffer = gl.createFramebuffer();
  13814. this.bindUnboundFramebuffer(framebuffer);
  13815. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  13816. // MipMaps
  13817. if (fullOptions.generateMipMaps) {
  13818. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13819. }
  13820. // Unbind
  13821. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13822. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13823. this.bindUnboundFramebuffer(null);
  13824. texture._framebuffer = framebuffer;
  13825. texture.width = size;
  13826. texture.height = size;
  13827. texture.isReady = true;
  13828. texture.isCube = true;
  13829. texture.samples = 1;
  13830. texture.generateMipMaps = fullOptions.generateMipMaps;
  13831. texture.samplingMode = fullOptions.samplingMode;
  13832. texture.type = fullOptions.type;
  13833. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  13834. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  13835. this._internalTexturesCache.push(texture);
  13836. return texture;
  13837. };
  13838. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  13839. var _this = this;
  13840. if (onLoad === void 0) { onLoad = null; }
  13841. if (onError === void 0) { onError = null; }
  13842. if (forcedExtension === void 0) { forcedExtension = null; }
  13843. var callback = function (loadData) {
  13844. if (!loadData) {
  13845. if (onLoad) {
  13846. onLoad(null);
  13847. }
  13848. return;
  13849. }
  13850. var texture = loadData.texture;
  13851. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  13852. texture._lodGenerationScale = scale;
  13853. texture._lodGenerationOffset = offset;
  13854. if (_this._caps.textureLOD) {
  13855. // Do not add extra process if texture lod is supported.
  13856. if (onLoad) {
  13857. onLoad(texture);
  13858. }
  13859. return;
  13860. }
  13861. var mipSlices = 3;
  13862. var gl = _this._gl;
  13863. var width = loadData.width;
  13864. if (!width) {
  13865. return;
  13866. }
  13867. var textures = [];
  13868. for (var i = 0; i < mipSlices; i++) {
  13869. //compute LOD from even spacing in smoothness (matching shader calculation)
  13870. var smoothness = i / (mipSlices - 1);
  13871. var roughness = 1 - smoothness;
  13872. var minLODIndex = offset; // roughness = 0
  13873. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  13874. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  13875. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  13876. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  13877. glTextureFromLod.isCube = true;
  13878. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  13879. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  13880. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  13881. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13882. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13883. if (loadData.isDDS) {
  13884. var info = loadData.info;
  13885. var data = loadData.data;
  13886. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  13887. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  13888. }
  13889. else {
  13890. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  13891. }
  13892. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13893. // Wrap in a base texture for easy binding.
  13894. var lodTexture = new BABYLON.BaseTexture(scene);
  13895. lodTexture.isCube = true;
  13896. lodTexture._texture = glTextureFromLod;
  13897. glTextureFromLod.isReady = true;
  13898. textures.push(lodTexture);
  13899. }
  13900. texture._lodTextureHigh = textures[2];
  13901. texture._lodTextureMid = textures[1];
  13902. texture._lodTextureLow = textures[0];
  13903. if (onLoad) {
  13904. onLoad(texture);
  13905. }
  13906. };
  13907. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  13908. };
  13909. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension) {
  13910. var _this = this;
  13911. if (onLoad === void 0) { onLoad = null; }
  13912. if (onError === void 0) { onError = null; }
  13913. if (forcedExtension === void 0) { forcedExtension = null; }
  13914. var gl = this._gl;
  13915. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  13916. texture.isCube = true;
  13917. texture.url = rootUrl;
  13918. texture.generateMipMaps = !noMipmap;
  13919. if (!this._doNotHandleContextLost) {
  13920. texture._extension = forcedExtension;
  13921. texture._files = files;
  13922. }
  13923. var isKTX = false;
  13924. var isDDS = false;
  13925. var lastDot = rootUrl.lastIndexOf('.');
  13926. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  13927. if (this._textureFormatInUse) {
  13928. extension = this._textureFormatInUse;
  13929. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  13930. isKTX = true;
  13931. }
  13932. else {
  13933. isDDS = (extension === ".dds");
  13934. }
  13935. var onerror = function (request, exception) {
  13936. if (onError && request) {
  13937. onError(request.status + " " + request.statusText, exception);
  13938. }
  13939. };
  13940. if (isKTX) {
  13941. this._loadFile(rootUrl, function (data) {
  13942. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  13943. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  13944. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13945. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  13946. ktx.uploadLevels(_this._gl, !noMipmap);
  13947. _this.setCubeMapTextureParams(gl, loadMipmap);
  13948. texture.width = ktx.pixelWidth;
  13949. texture.height = ktx.pixelHeight;
  13950. texture.isReady = true;
  13951. }, undefined, undefined, true, onerror);
  13952. }
  13953. else if (isDDS) {
  13954. if (files && files.length === 6) {
  13955. this._cascadeLoadFiles(scene, function (imgs) {
  13956. var info;
  13957. var loadMipmap = false;
  13958. var width = 0;
  13959. for (var index = 0; index < imgs.length; index++) {
  13960. var data = imgs[index];
  13961. info = BABYLON.DDSTools.GetDDSInfo(data);
  13962. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  13963. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13964. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  13965. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  13966. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  13967. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13968. }
  13969. texture.width = info.width;
  13970. texture.height = info.height;
  13971. texture.type = info.textureType;
  13972. width = info.width;
  13973. }
  13974. _this.setCubeMapTextureParams(gl, loadMipmap);
  13975. texture.isReady = true;
  13976. if (onLoad) {
  13977. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  13978. }
  13979. }, files, onError);
  13980. }
  13981. else {
  13982. this._loadFile(rootUrl, function (data) {
  13983. var info = BABYLON.DDSTools.GetDDSInfo(data);
  13984. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  13985. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13986. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  13987. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  13988. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  13989. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13990. }
  13991. _this.setCubeMapTextureParams(gl, loadMipmap);
  13992. texture.width = info.width;
  13993. texture.height = info.height;
  13994. texture.isReady = true;
  13995. texture.type = info.textureType;
  13996. if (onLoad) {
  13997. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  13998. }
  13999. }, undefined, undefined, true, onerror);
  14000. }
  14001. }
  14002. else {
  14003. if (!files) {
  14004. throw new Error("Cannot load cubemap because files were not defined");
  14005. }
  14006. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  14007. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  14008. var height = width;
  14009. _this._prepareWorkingCanvas();
  14010. if (!_this._workingCanvas || !_this._workingContext) {
  14011. return;
  14012. }
  14013. _this._workingCanvas.width = width;
  14014. _this._workingCanvas.height = height;
  14015. var faces = [
  14016. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  14017. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  14018. ];
  14019. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14020. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  14021. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  14022. for (var index = 0; index < faces.length; index++) {
  14023. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  14024. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  14025. }
  14026. if (!noMipmap) {
  14027. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  14028. }
  14029. _this.setCubeMapTextureParams(gl, !noMipmap);
  14030. texture.width = width;
  14031. texture.height = height;
  14032. texture.isReady = true;
  14033. if (format) {
  14034. texture.format = format;
  14035. }
  14036. texture.onLoadedObservable.notifyObservers(texture);
  14037. texture.onLoadedObservable.clear();
  14038. if (onLoad) {
  14039. onLoad();
  14040. }
  14041. }, files, onError);
  14042. }
  14043. this._internalTexturesCache.push(texture);
  14044. return texture;
  14045. };
  14046. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  14047. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14048. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  14049. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14050. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14051. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14052. // this.resetTextureCache();
  14053. };
  14054. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  14055. if (compression === void 0) { compression = null; }
  14056. if (level === void 0) { level = 0; }
  14057. texture._bufferViewArray = data;
  14058. texture.format = format;
  14059. texture.type = type;
  14060. texture.invertY = invertY;
  14061. texture._compression = compression;
  14062. var gl = this._gl;
  14063. var textureType = this._getWebGLTextureType(type);
  14064. var internalFormat = this._getInternalFormat(format);
  14065. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  14066. var needConversion = false;
  14067. if (internalFormat === gl.RGB) {
  14068. internalFormat = gl.RGBA;
  14069. needConversion = true;
  14070. }
  14071. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14072. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14073. if (texture.width % 4 !== 0) {
  14074. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  14075. }
  14076. // Data are known to be in +X +Y +Z -X -Y -Z
  14077. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  14078. var faceData = data[faceIndex];
  14079. if (compression) {
  14080. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  14081. }
  14082. else {
  14083. if (needConversion) {
  14084. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  14085. }
  14086. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  14087. }
  14088. }
  14089. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  14090. if (isPot && texture.generateMipMaps && level === 0) {
  14091. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  14092. }
  14093. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14094. // this.resetTextureCache();
  14095. texture.isReady = true;
  14096. };
  14097. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  14098. if (compression === void 0) { compression = null; }
  14099. var gl = this._gl;
  14100. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  14101. texture.isCube = true;
  14102. texture.generateMipMaps = generateMipMaps;
  14103. texture.format = format;
  14104. texture.type = type;
  14105. if (!this._doNotHandleContextLost) {
  14106. texture._bufferViewArray = data;
  14107. }
  14108. var textureType = this._getWebGLTextureType(type);
  14109. var internalFormat = this._getInternalFormat(format);
  14110. if (internalFormat === gl.RGB) {
  14111. internalFormat = gl.RGBA;
  14112. }
  14113. var width = size;
  14114. var height = width;
  14115. texture.width = width;
  14116. texture.height = height;
  14117. // Double check on POT to generate Mips.
  14118. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  14119. if (!isPot) {
  14120. generateMipMaps = false;
  14121. }
  14122. // Upload data if needed. The texture won't be ready until then.
  14123. if (data) {
  14124. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  14125. }
  14126. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  14127. // Filters
  14128. if (data && generateMipMaps) {
  14129. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  14130. }
  14131. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  14132. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  14133. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  14134. }
  14135. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  14136. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  14137. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  14138. }
  14139. else {
  14140. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  14141. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  14142. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  14143. }
  14144. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14145. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14146. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14147. return texture;
  14148. };
  14149. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
  14150. var _this = this;
  14151. if (onLoad === void 0) { onLoad = null; }
  14152. if (onError === void 0) { onError = null; }
  14153. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14154. if (invertY === void 0) { invertY = false; }
  14155. var gl = this._gl;
  14156. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  14157. scene._addPendingData(texture);
  14158. texture.url = url;
  14159. this._internalTexturesCache.push(texture);
  14160. var onerror = function (request, exception) {
  14161. scene._removePendingData(texture);
  14162. if (onError && request) {
  14163. onError(request.status + " " + request.statusText, exception);
  14164. }
  14165. };
  14166. var internalCallback = function (data) {
  14167. var width = texture.width;
  14168. var faceDataArrays = callback(data);
  14169. if (!faceDataArrays) {
  14170. return;
  14171. }
  14172. if (mipmmapGenerator) {
  14173. var textureType = _this._getWebGLTextureType(type);
  14174. var internalFormat = _this._getInternalFormat(format);
  14175. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  14176. var needConversion = false;
  14177. if (internalFormat === gl.RGB) {
  14178. internalFormat = gl.RGBA;
  14179. needConversion = true;
  14180. }
  14181. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14182. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  14183. var mipData = mipmmapGenerator(faceDataArrays);
  14184. for (var level = 0; level < mipData.length; level++) {
  14185. var mipSize = width >> level;
  14186. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  14187. var mipFaceData = mipData[level][faceIndex];
  14188. if (needConversion) {
  14189. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  14190. }
  14191. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  14192. }
  14193. }
  14194. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14195. }
  14196. else {
  14197. texture.generateMipMaps = !noMipmap;
  14198. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  14199. }
  14200. texture.isReady = true;
  14201. // this.resetTextureCache();
  14202. scene._removePendingData(texture);
  14203. if (onLoad) {
  14204. onLoad();
  14205. }
  14206. };
  14207. this._loadFile(url, function (data) {
  14208. internalCallback(data);
  14209. }, undefined, scene.database, true, onerror);
  14210. return texture;
  14211. };
  14212. ;
  14213. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression) {
  14214. if (compression === void 0) { compression = null; }
  14215. var internalFormat = this._getInternalFormat(format);
  14216. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  14217. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14218. if (!this._doNotHandleContextLost) {
  14219. texture._bufferView = data;
  14220. texture.format = format;
  14221. texture.invertY = invertY;
  14222. texture._compression = compression;
  14223. }
  14224. if (texture.width % 4 !== 0) {
  14225. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  14226. }
  14227. if (compression && data) {
  14228. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  14229. }
  14230. else {
  14231. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  14232. }
  14233. if (texture.generateMipMaps) {
  14234. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  14235. }
  14236. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14237. // this.resetTextureCache();
  14238. texture.isReady = true;
  14239. };
  14240. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression) {
  14241. if (compression === void 0) { compression = null; }
  14242. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  14243. texture.baseWidth = width;
  14244. texture.baseHeight = height;
  14245. texture.baseDepth = depth;
  14246. texture.width = width;
  14247. texture.height = height;
  14248. texture.depth = depth;
  14249. texture.format = format;
  14250. texture.generateMipMaps = generateMipMaps;
  14251. texture.samplingMode = samplingMode;
  14252. texture.is3D = true;
  14253. if (!this._doNotHandleContextLost) {
  14254. texture._bufferView = data;
  14255. }
  14256. this.updateRawTexture3D(texture, data, format, invertY, compression);
  14257. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  14258. // Filters
  14259. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  14260. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14261. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14262. if (generateMipMaps) {
  14263. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  14264. }
  14265. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14266. this._internalTexturesCache.push(texture);
  14267. return texture;
  14268. };
  14269. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  14270. var gl = this._gl;
  14271. if (!gl) {
  14272. return;
  14273. }
  14274. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  14275. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  14276. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  14277. if (!noMipmap && !isCompressed) {
  14278. gl.generateMipmap(gl.TEXTURE_2D);
  14279. }
  14280. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  14281. // this.resetTextureCache();
  14282. if (scene) {
  14283. scene._removePendingData(texture);
  14284. }
  14285. texture.onLoadedObservable.notifyObservers(texture);
  14286. texture.onLoadedObservable.clear();
  14287. };
  14288. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  14289. var _this = this;
  14290. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14291. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  14292. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  14293. var gl = this._gl;
  14294. if (!gl) {
  14295. return;
  14296. }
  14297. if (!texture._webGLTexture) {
  14298. // this.resetTextureCache();
  14299. if (scene) {
  14300. scene._removePendingData(texture);
  14301. }
  14302. return;
  14303. }
  14304. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14305. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14306. texture.baseWidth = width;
  14307. texture.baseHeight = height;
  14308. texture.width = potWidth;
  14309. texture.height = potHeight;
  14310. texture.isReady = true;
  14311. if (processFunction(potWidth, potHeight, function () {
  14312. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  14313. })) {
  14314. // Returning as texture needs extra async steps
  14315. return;
  14316. }
  14317. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  14318. };
  14319. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  14320. // Create new RGBA data container.
  14321. var rgbaData;
  14322. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  14323. rgbaData = new Float32Array(width * height * 4);
  14324. }
  14325. else {
  14326. rgbaData = new Uint32Array(width * height * 4);
  14327. }
  14328. // Convert each pixel.
  14329. for (var x = 0; x < width; x++) {
  14330. for (var y = 0; y < height; y++) {
  14331. var index = (y * width + x) * 3;
  14332. var newIndex = (y * width + x) * 4;
  14333. // Map Old Value to new value.
  14334. rgbaData[newIndex + 0] = rgbData[index + 0];
  14335. rgbaData[newIndex + 1] = rgbData[index + 1];
  14336. rgbaData[newIndex + 2] = rgbData[index + 2];
  14337. // Add fully opaque alpha channel.
  14338. rgbaData[newIndex + 3] = 1;
  14339. }
  14340. }
  14341. return rgbaData;
  14342. };
  14343. Engine.prototype._releaseFramebufferObjects = function (texture) {
  14344. var gl = this._gl;
  14345. if (texture._framebuffer) {
  14346. gl.deleteFramebuffer(texture._framebuffer);
  14347. texture._framebuffer = null;
  14348. }
  14349. if (texture._depthStencilBuffer) {
  14350. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  14351. texture._depthStencilBuffer = null;
  14352. }
  14353. if (texture._MSAAFramebuffer) {
  14354. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  14355. texture._MSAAFramebuffer = null;
  14356. }
  14357. if (texture._MSAARenderBuffer) {
  14358. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  14359. texture._MSAARenderBuffer = null;
  14360. }
  14361. };
  14362. Engine.prototype._releaseTexture = function (texture) {
  14363. var gl = this._gl;
  14364. this._releaseFramebufferObjects(texture);
  14365. gl.deleteTexture(texture._webGLTexture);
  14366. // Unbind channels
  14367. this.unbindAllTextures();
  14368. var index = this._internalTexturesCache.indexOf(texture);
  14369. if (index !== -1) {
  14370. this._internalTexturesCache.splice(index, 1);
  14371. }
  14372. // Integrated fixed lod samplers.
  14373. if (texture._lodTextureHigh) {
  14374. texture._lodTextureHigh.dispose();
  14375. }
  14376. if (texture._lodTextureMid) {
  14377. texture._lodTextureMid.dispose();
  14378. }
  14379. if (texture._lodTextureLow) {
  14380. texture._lodTextureLow.dispose();
  14381. }
  14382. };
  14383. Engine.prototype.setProgram = function (program) {
  14384. if (this._currentProgram !== program) {
  14385. this._gl.useProgram(program);
  14386. this._currentProgram = program;
  14387. }
  14388. };
  14389. Engine.prototype.bindSamplers = function (effect) {
  14390. this.setProgram(effect.getProgram());
  14391. var samplers = effect.getSamplers();
  14392. for (var index = 0; index < samplers.length; index++) {
  14393. var uniform = effect.getUniform(samplers[index]);
  14394. if (uniform) {
  14395. this._boundUniforms[index] = uniform;
  14396. }
  14397. }
  14398. this._currentEffect = null;
  14399. };
  14400. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  14401. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  14402. return;
  14403. }
  14404. // Remove
  14405. this._linkTrackers(internalTexture.previous, internalTexture.next);
  14406. // Bind last to it
  14407. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  14408. // Bind to dummy
  14409. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  14410. };
  14411. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  14412. if (!internalTexture) {
  14413. return -1;
  14414. }
  14415. internalTexture._initialSlot = channel;
  14416. if (this.disableTextureBindingOptimization) {
  14417. if (channel !== internalTexture._designatedSlot) {
  14418. this._textureCollisions.addCount(1, false);
  14419. }
  14420. }
  14421. else {
  14422. if (channel !== internalTexture._designatedSlot) {
  14423. if (internalTexture._designatedSlot > -1) {
  14424. return internalTexture._designatedSlot;
  14425. }
  14426. else {
  14427. // No slot for this texture, let's pick a new one (if we find a free slot)
  14428. if (this._nextFreeTextureSlots.length) {
  14429. return this._nextFreeTextureSlots[0];
  14430. }
  14431. // We need to recycle the oldest bound texture, sorry.
  14432. this._textureCollisions.addCount(1, false);
  14433. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  14434. }
  14435. }
  14436. }
  14437. return channel;
  14438. };
  14439. Engine.prototype._linkTrackers = function (previous, next) {
  14440. previous.next = next;
  14441. next.previous = previous;
  14442. };
  14443. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  14444. var currentSlot = internalTexture._designatedSlot;
  14445. if (currentSlot === -1) {
  14446. return -1;
  14447. }
  14448. internalTexture._designatedSlot = -1;
  14449. if (this.disableTextureBindingOptimization) {
  14450. return -1;
  14451. }
  14452. // Remove from bound list
  14453. this._linkTrackers(internalTexture.previous, internalTexture.next);
  14454. // Free the slot
  14455. this._boundTexturesCache[currentSlot] = null;
  14456. this._nextFreeTextureSlots.push(currentSlot);
  14457. return currentSlot;
  14458. };
  14459. Engine.prototype._activateCurrentTexture = function () {
  14460. if (this._currentTextureChannel !== this._activeChannel) {
  14461. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  14462. this._currentTextureChannel = this._activeChannel;
  14463. }
  14464. };
  14465. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate) {
  14466. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  14467. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  14468. this._activeChannel = texture._designatedSlot;
  14469. }
  14470. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  14471. var isTextureForRendering = texture && texture._initialSlot > -1;
  14472. if (currentTextureBound !== texture) {
  14473. if (currentTextureBound) {
  14474. this._removeDesignatedSlot(currentTextureBound);
  14475. }
  14476. this._activateCurrentTexture();
  14477. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  14478. this._boundTexturesCache[this._activeChannel] = texture;
  14479. if (texture) {
  14480. if (!this.disableTextureBindingOptimization) {
  14481. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  14482. if (slotIndex > -1) {
  14483. this._nextFreeTextureSlots.splice(slotIndex, 1);
  14484. }
  14485. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  14486. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  14487. }
  14488. texture._designatedSlot = this._activeChannel;
  14489. }
  14490. }
  14491. else if (forTextureDataUpdate) {
  14492. this._activateCurrentTexture();
  14493. }
  14494. if (isTextureForRendering && !forTextureDataUpdate) {
  14495. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  14496. }
  14497. };
  14498. Engine.prototype._bindTexture = function (channel, texture) {
  14499. if (channel < 0) {
  14500. return;
  14501. }
  14502. if (texture) {
  14503. channel = this._getCorrectTextureChannel(channel, texture);
  14504. }
  14505. this._activeChannel = channel;
  14506. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  14507. };
  14508. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  14509. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  14510. };
  14511. Engine.prototype.unbindAllTextures = function () {
  14512. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  14513. this._activeChannel = channel;
  14514. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14515. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14516. if (this.webGLVersion > 1) {
  14517. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14518. }
  14519. }
  14520. };
  14521. Engine.prototype.setTexture = function (channel, uniform, texture) {
  14522. if (channel < 0) {
  14523. return;
  14524. }
  14525. if (uniform) {
  14526. this._boundUniforms[channel] = uniform;
  14527. }
  14528. this._setTexture(channel, texture);
  14529. };
  14530. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  14531. var uniform = this._boundUniforms[sourceSlot];
  14532. if (uniform._currentState === destination) {
  14533. return;
  14534. }
  14535. this._gl.uniform1i(uniform, destination);
  14536. uniform._currentState = destination;
  14537. };
  14538. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray) {
  14539. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  14540. // Not ready?
  14541. if (!texture) {
  14542. if (this._boundTexturesCache[channel] != null) {
  14543. this._activeChannel = channel;
  14544. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14545. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14546. if (this.webGLVersion > 1) {
  14547. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14548. }
  14549. }
  14550. return false;
  14551. }
  14552. // Video
  14553. if (texture.video) {
  14554. this._activeChannel = channel;
  14555. texture.update();
  14556. }
  14557. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  14558. texture.delayLoad();
  14559. return false;
  14560. }
  14561. var internalTexture;
  14562. if (texture.isReady()) {
  14563. internalTexture = texture.getInternalTexture();
  14564. }
  14565. else if (texture.isCube) {
  14566. internalTexture = this.emptyCubeTexture;
  14567. }
  14568. else if (texture.is3D) {
  14569. internalTexture = this.emptyTexture3D;
  14570. }
  14571. else {
  14572. internalTexture = this.emptyTexture;
  14573. }
  14574. if (!isPartOfTextureArray) {
  14575. channel = this._getCorrectTextureChannel(channel, internalTexture);
  14576. }
  14577. if (this._boundTexturesCache[channel] === internalTexture) {
  14578. this._moveBoundTextureOnTop(internalTexture);
  14579. if (!isPartOfTextureArray) {
  14580. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  14581. }
  14582. return false;
  14583. }
  14584. this._activeChannel = channel;
  14585. if (internalTexture && internalTexture.is3D) {
  14586. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  14587. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  14588. internalTexture._cachedWrapU = texture.wrapU;
  14589. switch (texture.wrapU) {
  14590. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14591. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  14592. break;
  14593. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14594. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  14595. break;
  14596. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14597. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  14598. break;
  14599. }
  14600. }
  14601. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  14602. internalTexture._cachedWrapV = texture.wrapV;
  14603. switch (texture.wrapV) {
  14604. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14605. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  14606. break;
  14607. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14608. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  14609. break;
  14610. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14611. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  14612. break;
  14613. }
  14614. }
  14615. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  14616. internalTexture._cachedWrapR = texture.wrapR;
  14617. switch (texture.wrapR) {
  14618. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14619. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.REPEAT);
  14620. break;
  14621. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14622. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.CLAMP_TO_EDGE);
  14623. break;
  14624. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14625. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.MIRRORED_REPEAT);
  14626. break;
  14627. }
  14628. }
  14629. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  14630. }
  14631. else if (internalTexture && internalTexture.isCube) {
  14632. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  14633. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  14634. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  14635. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  14636. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  14637. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  14638. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  14639. }
  14640. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  14641. }
  14642. else {
  14643. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  14644. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  14645. internalTexture._cachedWrapU = texture.wrapU;
  14646. switch (texture.wrapU) {
  14647. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14648. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  14649. break;
  14650. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14651. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  14652. break;
  14653. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14654. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  14655. break;
  14656. }
  14657. }
  14658. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  14659. internalTexture._cachedWrapV = texture.wrapV;
  14660. switch (texture.wrapV) {
  14661. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14662. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  14663. break;
  14664. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14665. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  14666. break;
  14667. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14668. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  14669. break;
  14670. }
  14671. }
  14672. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  14673. }
  14674. return true;
  14675. };
  14676. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  14677. if (channel < 0 || !uniform) {
  14678. return;
  14679. }
  14680. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  14681. this._textureUnits = new Int32Array(textures.length);
  14682. }
  14683. for (var i = 0; i < textures.length; i++) {
  14684. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  14685. }
  14686. this._gl.uniform1iv(uniform, this._textureUnits);
  14687. for (var index = 0; index < textures.length; index++) {
  14688. this._setTexture(this._textureUnits[index], textures[index], true);
  14689. }
  14690. };
  14691. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  14692. var internalTexture = texture.getInternalTexture();
  14693. if (!internalTexture) {
  14694. return;
  14695. }
  14696. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  14697. var value = texture.anisotropicFilteringLevel;
  14698. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  14699. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  14700. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  14701. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  14702. }
  14703. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  14704. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  14705. internalTexture._cachedAnisotropicFilteringLevel = value;
  14706. }
  14707. };
  14708. Engine.prototype.readPixels = function (x, y, width, height) {
  14709. var data = new Uint8Array(height * width * 4);
  14710. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  14711. return data;
  14712. };
  14713. /**
  14714. * Add an externaly attached data from its key.
  14715. * This method call will fail and return false, if such key already exists.
  14716. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  14717. * @param key the unique key that identifies the data
  14718. * @param data the data object to associate to the key for this Engine instance
  14719. * @return true if no such key were already present and the data was added successfully, false otherwise
  14720. */
  14721. Engine.prototype.addExternalData = function (key, data) {
  14722. if (!this._externalData) {
  14723. this._externalData = new BABYLON.StringDictionary();
  14724. }
  14725. return this._externalData.add(key, data);
  14726. };
  14727. /**
  14728. * Get an externaly attached data from its key
  14729. * @param key the unique key that identifies the data
  14730. * @return the associated data, if present (can be null), or undefined if not present
  14731. */
  14732. Engine.prototype.getExternalData = function (key) {
  14733. if (!this._externalData) {
  14734. this._externalData = new BABYLON.StringDictionary();
  14735. }
  14736. return this._externalData.get(key);
  14737. };
  14738. /**
  14739. * Get an externaly attached data from its key, create it using a factory if it's not already present
  14740. * @param key the unique key that identifies the data
  14741. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  14742. * @return the associated data, can be null if the factory returned null.
  14743. */
  14744. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  14745. if (!this._externalData) {
  14746. this._externalData = new BABYLON.StringDictionary();
  14747. }
  14748. return this._externalData.getOrAddWithFactory(key, factory);
  14749. };
  14750. /**
  14751. * Remove an externaly attached data from the Engine instance
  14752. * @param key the unique key that identifies the data
  14753. * @return true if the data was successfully removed, false if it doesn't exist
  14754. */
  14755. Engine.prototype.removeExternalData = function (key) {
  14756. if (!this._externalData) {
  14757. this._externalData = new BABYLON.StringDictionary();
  14758. }
  14759. return this._externalData.remove(key);
  14760. };
  14761. Engine.prototype.unbindAllAttributes = function () {
  14762. if (this._mustWipeVertexAttributes) {
  14763. this._mustWipeVertexAttributes = false;
  14764. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  14765. this._gl.disableVertexAttribArray(i);
  14766. this._vertexAttribArraysEnabled[i] = false;
  14767. this._currentBufferPointers[i].active = false;
  14768. }
  14769. return;
  14770. }
  14771. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  14772. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  14773. continue;
  14774. }
  14775. this._gl.disableVertexAttribArray(i);
  14776. this._vertexAttribArraysEnabled[i] = false;
  14777. this._currentBufferPointers[i].active = false;
  14778. }
  14779. };
  14780. Engine.prototype.releaseEffects = function () {
  14781. for (var name in this._compiledEffects) {
  14782. this._deleteProgram(this._compiledEffects[name]._program);
  14783. }
  14784. this._compiledEffects = {};
  14785. };
  14786. // Dispose
  14787. Engine.prototype.dispose = function () {
  14788. this.hideLoadingUI();
  14789. this.stopRenderLoop();
  14790. // Release postProcesses
  14791. while (this.postProcesses.length) {
  14792. this.postProcesses[0].dispose();
  14793. }
  14794. // Empty texture
  14795. if (this._emptyTexture) {
  14796. this._releaseTexture(this._emptyTexture);
  14797. this._emptyTexture = null;
  14798. }
  14799. if (this._emptyCubeTexture) {
  14800. this._releaseTexture(this._emptyCubeTexture);
  14801. this._emptyCubeTexture = null;
  14802. }
  14803. // Rescale PP
  14804. if (this._rescalePostProcess) {
  14805. this._rescalePostProcess.dispose();
  14806. }
  14807. // Release scenes
  14808. while (this.scenes.length) {
  14809. this.scenes[0].dispose();
  14810. }
  14811. // Release audio engine
  14812. if (Engine.audioEngine) {
  14813. Engine.audioEngine.dispose();
  14814. }
  14815. // Release effects
  14816. this.releaseEffects();
  14817. // Unbind
  14818. this.unbindAllAttributes();
  14819. if (this._dummyFramebuffer) {
  14820. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  14821. }
  14822. //WebVR
  14823. this.disableVR();
  14824. // Events
  14825. if (BABYLON.Tools.IsWindowObjectExist()) {
  14826. window.removeEventListener("blur", this._onBlur);
  14827. window.removeEventListener("focus", this._onFocus);
  14828. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  14829. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  14830. if (this._renderingCanvas) {
  14831. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  14832. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  14833. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasBlur);
  14834. if (!this._doNotHandleContextLost) {
  14835. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  14836. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  14837. }
  14838. }
  14839. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  14840. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  14841. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  14842. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  14843. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  14844. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  14845. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  14846. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  14847. if (this._onVrDisplayConnect) {
  14848. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  14849. if (this._onVrDisplayDisconnect) {
  14850. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  14851. }
  14852. if (this._onVrDisplayPresentChange) {
  14853. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  14854. }
  14855. this._onVrDisplayConnect = null;
  14856. this._onVrDisplayDisconnect = null;
  14857. }
  14858. }
  14859. // Remove from Instances
  14860. var index = Engine.Instances.indexOf(this);
  14861. if (index >= 0) {
  14862. Engine.Instances.splice(index, 1);
  14863. }
  14864. this._workingCanvas = null;
  14865. this._workingContext = null;
  14866. this._currentBufferPointers = [];
  14867. this._renderingCanvas = null;
  14868. this._currentProgram = null;
  14869. this.onResizeObservable.clear();
  14870. this.onCanvasBlurObservable.clear();
  14871. this.onCanvasFocusObservable.clear();
  14872. this.onCanvasPointerOutObservable.clear();
  14873. this.onBeginFrameObservable.clear();
  14874. this.onEndFrameObservable.clear();
  14875. BABYLON.Effect.ResetCache();
  14876. // Abort active requests
  14877. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  14878. var request = _a[_i];
  14879. request.abort();
  14880. }
  14881. };
  14882. // Loading screen
  14883. Engine.prototype.displayLoadingUI = function () {
  14884. if (!BABYLON.Tools.IsWindowObjectExist()) {
  14885. return;
  14886. }
  14887. var loadingScreen = this.loadingScreen;
  14888. if (loadingScreen) {
  14889. loadingScreen.displayLoadingUI();
  14890. }
  14891. };
  14892. Engine.prototype.hideLoadingUI = function () {
  14893. if (!BABYLON.Tools.IsWindowObjectExist()) {
  14894. return;
  14895. }
  14896. var loadingScreen = this.loadingScreen;
  14897. if (loadingScreen) {
  14898. loadingScreen.hideLoadingUI();
  14899. }
  14900. };
  14901. Object.defineProperty(Engine.prototype, "loadingScreen", {
  14902. get: function () {
  14903. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  14904. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  14905. return this._loadingScreen;
  14906. },
  14907. set: function (loadingScreen) {
  14908. this._loadingScreen = loadingScreen;
  14909. },
  14910. enumerable: true,
  14911. configurable: true
  14912. });
  14913. Object.defineProperty(Engine.prototype, "loadingUIText", {
  14914. set: function (text) {
  14915. this.loadingScreen.loadingUIText = text;
  14916. },
  14917. enumerable: true,
  14918. configurable: true
  14919. });
  14920. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  14921. set: function (color) {
  14922. this.loadingScreen.loadingUIBackgroundColor = color;
  14923. },
  14924. enumerable: true,
  14925. configurable: true
  14926. });
  14927. Engine.prototype.attachContextLostEvent = function (callback) {
  14928. if (this._renderingCanvas) {
  14929. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  14930. }
  14931. };
  14932. Engine.prototype.attachContextRestoredEvent = function (callback) {
  14933. if (this._renderingCanvas) {
  14934. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  14935. }
  14936. };
  14937. Engine.prototype.getVertexShaderSource = function (program) {
  14938. var shaders = this._gl.getAttachedShaders(program);
  14939. if (!shaders) {
  14940. return null;
  14941. }
  14942. return this._gl.getShaderSource(shaders[0]);
  14943. };
  14944. Engine.prototype.getFragmentShaderSource = function (program) {
  14945. var shaders = this._gl.getAttachedShaders(program);
  14946. if (!shaders) {
  14947. return null;
  14948. }
  14949. return this._gl.getShaderSource(shaders[1]);
  14950. };
  14951. Engine.prototype.getError = function () {
  14952. return this._gl.getError();
  14953. };
  14954. // FPS
  14955. Engine.prototype.getFps = function () {
  14956. return this._fps;
  14957. };
  14958. Engine.prototype.getDeltaTime = function () {
  14959. return this._deltaTime;
  14960. };
  14961. Engine.prototype._measureFps = function () {
  14962. this._performanceMonitor.sampleFrame();
  14963. this._fps = this._performanceMonitor.averageFPS;
  14964. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  14965. };
  14966. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  14967. if (faceIndex === void 0) { faceIndex = -1; }
  14968. var gl = this._gl;
  14969. if (!this._dummyFramebuffer) {
  14970. var dummy = gl.createFramebuffer();
  14971. if (!dummy) {
  14972. throw new Error("Unable to create dummy framebuffer");
  14973. }
  14974. this._dummyFramebuffer = dummy;
  14975. }
  14976. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  14977. if (faceIndex > -1) {
  14978. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  14979. }
  14980. else {
  14981. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  14982. }
  14983. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  14984. var buffer;
  14985. switch (readType) {
  14986. case gl.UNSIGNED_BYTE:
  14987. buffer = new Uint8Array(4 * width * height);
  14988. readType = gl.UNSIGNED_BYTE;
  14989. break;
  14990. default:
  14991. buffer = new Float32Array(4 * width * height);
  14992. readType = gl.FLOAT;
  14993. break;
  14994. }
  14995. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  14996. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  14997. return buffer;
  14998. };
  14999. Engine.prototype._canRenderToFloatFramebuffer = function () {
  15000. if (this._webGLVersion > 1) {
  15001. return this._caps.colorBufferFloat;
  15002. }
  15003. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  15004. };
  15005. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  15006. if (this._webGLVersion > 1) {
  15007. return this._caps.colorBufferFloat;
  15008. }
  15009. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  15010. };
  15011. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  15012. Engine.prototype._canRenderToFramebuffer = function (type) {
  15013. var gl = this._gl;
  15014. //clear existing errors
  15015. while (gl.getError() !== gl.NO_ERROR) { }
  15016. var successful = true;
  15017. var texture = gl.createTexture();
  15018. gl.bindTexture(gl.TEXTURE_2D, texture);
  15019. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  15020. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15021. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15022. var fb = gl.createFramebuffer();
  15023. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  15024. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  15025. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  15026. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  15027. successful = successful && (gl.getError() === gl.NO_ERROR);
  15028. //try render by clearing frame buffer's color buffer
  15029. if (successful) {
  15030. gl.clear(gl.COLOR_BUFFER_BIT);
  15031. successful = successful && (gl.getError() === gl.NO_ERROR);
  15032. }
  15033. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  15034. if (successful) {
  15035. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  15036. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  15037. var readFormat = gl.RGBA;
  15038. var readType = gl.UNSIGNED_BYTE;
  15039. var buffer = new Uint8Array(4);
  15040. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  15041. successful = successful && (gl.getError() === gl.NO_ERROR);
  15042. }
  15043. //clean up
  15044. gl.deleteTexture(texture);
  15045. gl.deleteFramebuffer(fb);
  15046. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  15047. //clear accumulated errors
  15048. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  15049. return successful;
  15050. };
  15051. Engine.prototype._getWebGLTextureType = function (type) {
  15052. if (type === Engine.TEXTURETYPE_FLOAT) {
  15053. return this._gl.FLOAT;
  15054. }
  15055. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  15056. // Add Half Float Constant.
  15057. return this._gl.HALF_FLOAT_OES;
  15058. }
  15059. return this._gl.UNSIGNED_BYTE;
  15060. };
  15061. ;
  15062. /** @ignore */
  15063. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  15064. if (this._webGLVersion === 1) {
  15065. return this._gl.RGBA;
  15066. }
  15067. if (type === Engine.TEXTURETYPE_FLOAT) {
  15068. if (format) {
  15069. switch (format) {
  15070. case Engine.TEXTUREFORMAT_R32F:
  15071. return this._gl.R32F;
  15072. case Engine.TEXTUREFORMAT_RG32F:
  15073. return this._gl.RG32F;
  15074. case Engine.TEXTUREFORMAT_RGB32F:
  15075. return this._gl.RGB32F;
  15076. }
  15077. }
  15078. return this._gl.RGBA32F;
  15079. }
  15080. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  15081. return this._gl.RGBA16F;
  15082. }
  15083. return this._gl.RGBA;
  15084. };
  15085. ;
  15086. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  15087. if (type === Engine.TEXTURETYPE_FLOAT) {
  15088. return this._gl.RGBA32F;
  15089. }
  15090. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  15091. return this._gl.RGBA16F;
  15092. }
  15093. return this._gl.RGBA8;
  15094. };
  15095. ;
  15096. Engine.prototype.createQuery = function () {
  15097. return this._gl.createQuery();
  15098. };
  15099. Engine.prototype.deleteQuery = function (query) {
  15100. this._gl.deleteQuery(query);
  15101. return this;
  15102. };
  15103. Engine.prototype.isQueryResultAvailable = function (query) {
  15104. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  15105. };
  15106. Engine.prototype.getQueryResult = function (query) {
  15107. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  15108. };
  15109. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  15110. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  15111. this._gl.beginQuery(glAlgorithm, query);
  15112. return this;
  15113. };
  15114. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  15115. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  15116. this._gl.endQuery(glAlgorithm);
  15117. return this;
  15118. };
  15119. /* Time queries */
  15120. Engine.prototype._createTimeQuery = function () {
  15121. var timerQuery = this._caps.timerQuery;
  15122. if (timerQuery.createQueryEXT) {
  15123. return timerQuery.createQueryEXT();
  15124. }
  15125. return this.createQuery();
  15126. };
  15127. Engine.prototype._deleteTimeQuery = function (query) {
  15128. var timerQuery = this._caps.timerQuery;
  15129. if (timerQuery.deleteQueryEXT) {
  15130. timerQuery.deleteQueryEXT(query);
  15131. return;
  15132. }
  15133. this.deleteQuery(query);
  15134. };
  15135. Engine.prototype._getTimeQueryResult = function (query) {
  15136. var timerQuery = this._caps.timerQuery;
  15137. if (timerQuery.getQueryObjectEXT) {
  15138. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  15139. }
  15140. return this.getQueryResult(query);
  15141. };
  15142. Engine.prototype._getTimeQueryAvailability = function (query) {
  15143. var timerQuery = this._caps.timerQuery;
  15144. if (timerQuery.getQueryObjectEXT) {
  15145. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  15146. }
  15147. return this.isQueryResultAvailable(query);
  15148. };
  15149. Engine.prototype.startTimeQuery = function () {
  15150. var timerQuery = this._caps.timerQuery;
  15151. if (!timerQuery) {
  15152. return null;
  15153. }
  15154. var token = new BABYLON._TimeToken();
  15155. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  15156. if (this._caps.canUseTimestampForTimerQuery) {
  15157. token._startTimeQuery = this._createTimeQuery();
  15158. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  15159. }
  15160. else {
  15161. if (this._currentNonTimestampToken) {
  15162. return this._currentNonTimestampToken;
  15163. }
  15164. token._timeElapsedQuery = this._createTimeQuery();
  15165. if (timerQuery.beginQueryEXT) {
  15166. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  15167. }
  15168. else {
  15169. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  15170. }
  15171. this._currentNonTimestampToken = token;
  15172. }
  15173. return token;
  15174. };
  15175. Engine.prototype.endTimeQuery = function (token) {
  15176. var timerQuery = this._caps.timerQuery;
  15177. if (!timerQuery || !token) {
  15178. return -1;
  15179. }
  15180. if (this._caps.canUseTimestampForTimerQuery) {
  15181. if (!token._startTimeQuery) {
  15182. return -1;
  15183. }
  15184. if (!token._endTimeQuery) {
  15185. token._endTimeQuery = this._createTimeQuery();
  15186. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  15187. }
  15188. }
  15189. else if (!token._timeElapsedQueryEnded) {
  15190. if (!token._timeElapsedQuery) {
  15191. return -1;
  15192. }
  15193. if (timerQuery.endQueryEXT) {
  15194. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  15195. }
  15196. else {
  15197. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  15198. }
  15199. token._timeElapsedQueryEnded = true;
  15200. }
  15201. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  15202. var available = false;
  15203. if (token._endTimeQuery) {
  15204. available = this._getTimeQueryAvailability(token._endTimeQuery);
  15205. }
  15206. else if (token._timeElapsedQuery) {
  15207. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  15208. }
  15209. if (available && !disjoint) {
  15210. var result = 0;
  15211. if (this._caps.canUseTimestampForTimerQuery) {
  15212. if (!token._startTimeQuery || !token._endTimeQuery) {
  15213. return -1;
  15214. }
  15215. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  15216. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  15217. result = timeEnd - timeStart;
  15218. this._deleteTimeQuery(token._startTimeQuery);
  15219. this._deleteTimeQuery(token._endTimeQuery);
  15220. token._startTimeQuery = null;
  15221. token._endTimeQuery = null;
  15222. }
  15223. else {
  15224. if (!token._timeElapsedQuery) {
  15225. return -1;
  15226. }
  15227. result = this._getTimeQueryResult(token._timeElapsedQuery);
  15228. this._deleteTimeQuery(token._timeElapsedQuery);
  15229. token._timeElapsedQuery = null;
  15230. token._timeElapsedQueryEnded = false;
  15231. this._currentNonTimestampToken = null;
  15232. }
  15233. return result;
  15234. }
  15235. return -1;
  15236. };
  15237. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  15238. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  15239. };
  15240. // Transform feedback
  15241. Engine.prototype.createTransformFeedback = function () {
  15242. return this._gl.createTransformFeedback();
  15243. };
  15244. Engine.prototype.deleteTransformFeedback = function (value) {
  15245. this._gl.deleteTransformFeedback(value);
  15246. };
  15247. Engine.prototype.bindTransformFeedback = function (value) {
  15248. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  15249. };
  15250. Engine.prototype.beginTransformFeedback = function (usePoints) {
  15251. if (usePoints === void 0) { usePoints = true; }
  15252. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  15253. };
  15254. Engine.prototype.endTransformFeedback = function () {
  15255. this._gl.endTransformFeedback();
  15256. };
  15257. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  15258. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  15259. };
  15260. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  15261. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  15262. };
  15263. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  15264. var _this = this;
  15265. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  15266. this._activeRequests.push(request);
  15267. request.onCompleteObservable.add(function (request) {
  15268. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  15269. });
  15270. return request;
  15271. };
  15272. /** @ignore */
  15273. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  15274. var _this = this;
  15275. return new Promise(function (resolve, reject) {
  15276. _this._loadFile(url, function (data) {
  15277. resolve(data);
  15278. }, undefined, database, useArrayBuffer, function (request, exception) {
  15279. reject(exception);
  15280. });
  15281. });
  15282. };
  15283. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  15284. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  15285. var onload = function (data) {
  15286. loadedFiles[index] = data;
  15287. loadedFiles._internalCount++;
  15288. if (loadedFiles._internalCount === 6) {
  15289. onfinish(loadedFiles);
  15290. }
  15291. };
  15292. var onerror = function (request, exception) {
  15293. if (onErrorCallBack && request) {
  15294. onErrorCallBack(request.status + " " + request.statusText, exception);
  15295. }
  15296. };
  15297. this._loadFile(url, onload, undefined, undefined, true, onerror);
  15298. };
  15299. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  15300. if (onError === void 0) { onError = null; }
  15301. var loadedFiles = [];
  15302. loadedFiles._internalCount = 0;
  15303. for (var index = 0; index < 6; index++) {
  15304. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  15305. }
  15306. };
  15307. // Statics
  15308. Engine.isSupported = function () {
  15309. try {
  15310. var tempcanvas = document.createElement("canvas");
  15311. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  15312. return gl != null && !!window.WebGLRenderingContext;
  15313. }
  15314. catch (e) {
  15315. return false;
  15316. }
  15317. };
  15318. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  15319. Engine.ExceptionList = [
  15320. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  15321. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  15322. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  15323. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  15324. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  15325. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  15326. ];
  15327. Engine.Instances = new Array();
  15328. // Const statics
  15329. Engine._ALPHA_DISABLE = 0;
  15330. Engine._ALPHA_ADD = 1;
  15331. Engine._ALPHA_COMBINE = 2;
  15332. Engine._ALPHA_SUBTRACT = 3;
  15333. Engine._ALPHA_MULTIPLY = 4;
  15334. Engine._ALPHA_MAXIMIZED = 5;
  15335. Engine._ALPHA_ONEONE = 6;
  15336. Engine._ALPHA_PREMULTIPLIED = 7;
  15337. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  15338. Engine._ALPHA_INTERPOLATE = 9;
  15339. Engine._ALPHA_SCREENMODE = 10;
  15340. Engine._DELAYLOADSTATE_NONE = 0;
  15341. Engine._DELAYLOADSTATE_LOADED = 1;
  15342. Engine._DELAYLOADSTATE_LOADING = 2;
  15343. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  15344. Engine._TEXTUREFORMAT_ALPHA = 0;
  15345. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  15346. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  15347. Engine._TEXTUREFORMAT_RGB = 4;
  15348. Engine._TEXTUREFORMAT_RGBA = 5;
  15349. Engine._TEXTUREFORMAT_R32F = 6;
  15350. Engine._TEXTUREFORMAT_RG32F = 7;
  15351. Engine._TEXTUREFORMAT_RGB32F = 8;
  15352. Engine._TEXTUREFORMAT_RGBA32F = 9;
  15353. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  15354. Engine._TEXTURETYPE_FLOAT = 1;
  15355. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  15356. // Depht or Stencil test Constants.
  15357. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  15358. 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.
  15359. 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.
  15360. 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.
  15361. 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.
  15362. 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.
  15363. 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.
  15364. 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.
  15365. // Stencil Actions Constants.
  15366. Engine._KEEP = 0x1E00;
  15367. Engine._REPLACE = 0x1E01;
  15368. Engine._INCR = 0x1E02;
  15369. Engine._DECR = 0x1E03;
  15370. Engine._INVERT = 0x150A;
  15371. Engine._INCR_WRAP = 0x8507;
  15372. Engine._DECR_WRAP = 0x8508;
  15373. // Texture rescaling mode
  15374. Engine._SCALEMODE_FLOOR = 1;
  15375. Engine._SCALEMODE_NEAREST = 2;
  15376. Engine._SCALEMODE_CEILING = 3;
  15377. // Updatable statics so stick with vars here
  15378. Engine.CollisionsEpsilon = 0.001;
  15379. Engine.CodeRepository = "src/";
  15380. Engine.ShadersRepository = "src/Shaders/";
  15381. return Engine;
  15382. }());
  15383. BABYLON.Engine = Engine;
  15384. })(BABYLON || (BABYLON = {}));
  15385. //# sourceMappingURL=babylon.engine.js.map
  15386. var BABYLON;
  15387. (function (BABYLON) {
  15388. /**
  15389. * Node is the basic class for all scene objects (Mesh, Light Camera).
  15390. */
  15391. var Node = /** @class */ (function () {
  15392. /**
  15393. * Creates a new Node
  15394. * @param {string} name - the name and id to be given to this node
  15395. * @param {BABYLON.Scene} the scene this node will be added to
  15396. */
  15397. function Node(name, scene) {
  15398. if (scene === void 0) { scene = null; }
  15399. /**
  15400. * Gets or sets a string used to store user defined state for the node
  15401. */
  15402. this.state = "";
  15403. /**
  15404. * Gets or sets an object used to store user defined information for the node
  15405. */
  15406. this.metadata = null;
  15407. /**
  15408. * Gets or sets a boolean used to define if the node must be serialized
  15409. */
  15410. this.doNotSerialize = false;
  15411. /** @ignore */
  15412. this._isDisposed = false;
  15413. /**
  15414. * Gets a list of {BABYLON.Animation} associated with the node
  15415. */
  15416. this.animations = new Array();
  15417. this._ranges = {};
  15418. this._isEnabled = true;
  15419. this._isReady = true;
  15420. /** @ignore */
  15421. this._currentRenderId = -1;
  15422. this._parentRenderId = -1;
  15423. /**
  15424. * An event triggered when the mesh is disposed
  15425. * @type {BABYLON.Observable}
  15426. */
  15427. this.onDisposeObservable = new BABYLON.Observable();
  15428. // Behaviors
  15429. this._behaviors = new Array();
  15430. this.name = name;
  15431. this.id = name;
  15432. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  15433. this.uniqueId = this._scene.getUniqueId();
  15434. this._initCache();
  15435. }
  15436. /**
  15437. * Gets a boolean indicating if the node has been disposed
  15438. * @returns true if the node was disposed
  15439. */
  15440. Node.prototype.isDisposed = function () {
  15441. return this._isDisposed;
  15442. };
  15443. Object.defineProperty(Node.prototype, "parent", {
  15444. get: function () {
  15445. return this._parentNode;
  15446. },
  15447. /**
  15448. * Gets or sets the parent of the node
  15449. */
  15450. set: function (parent) {
  15451. if (this._parentNode === parent) {
  15452. return;
  15453. }
  15454. // Remove self from list of children of parent
  15455. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  15456. var index = this._parentNode._children.indexOf(this);
  15457. if (index !== -1) {
  15458. this._parentNode._children.splice(index, 1);
  15459. }
  15460. }
  15461. // Store new parent
  15462. this._parentNode = parent;
  15463. // Add as child to new parent
  15464. if (this._parentNode) {
  15465. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  15466. this._parentNode._children = new Array();
  15467. }
  15468. this._parentNode._children.push(this);
  15469. }
  15470. },
  15471. enumerable: true,
  15472. configurable: true
  15473. });
  15474. /**
  15475. * Gets a string idenfifying the name of the class
  15476. * @returns "Node" string
  15477. */
  15478. Node.prototype.getClassName = function () {
  15479. return "Node";
  15480. };
  15481. Object.defineProperty(Node.prototype, "onDispose", {
  15482. /**
  15483. * Sets a callback that will be raised when the node will be disposed
  15484. */
  15485. set: function (callback) {
  15486. if (this._onDisposeObserver) {
  15487. this.onDisposeObservable.remove(this._onDisposeObserver);
  15488. }
  15489. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  15490. },
  15491. enumerable: true,
  15492. configurable: true
  15493. });
  15494. /**
  15495. * Gets the scene of the node
  15496. * @returns a {BABYLON.Scene}
  15497. */
  15498. Node.prototype.getScene = function () {
  15499. return this._scene;
  15500. };
  15501. /**
  15502. * Gets the engine of the node
  15503. * @returns a {BABYLON.Engine}
  15504. */
  15505. Node.prototype.getEngine = function () {
  15506. return this._scene.getEngine();
  15507. };
  15508. /**
  15509. * Attach a behavior to the node
  15510. * @see http://doc.babylonjs.com/features/behaviour
  15511. * @param behavior defines the behavior to attach
  15512. * @returns the current Node
  15513. */
  15514. Node.prototype.addBehavior = function (behavior) {
  15515. var _this = this;
  15516. var index = this._behaviors.indexOf(behavior);
  15517. if (index !== -1) {
  15518. return this;
  15519. }
  15520. behavior.init();
  15521. if (this._scene.isLoading) {
  15522. // We defer the attach when the scene will be loaded
  15523. var observer = this._scene.onDataLoadedObservable.add(function () {
  15524. behavior.attach(_this);
  15525. setTimeout(function () {
  15526. // Need to use a timeout to avoid removing an observer while iterating the list of observers
  15527. _this._scene.onDataLoadedObservable.remove(observer);
  15528. }, 0);
  15529. });
  15530. }
  15531. else {
  15532. behavior.attach(this);
  15533. }
  15534. this._behaviors.push(behavior);
  15535. return this;
  15536. };
  15537. /**
  15538. * Remove an attached behavior
  15539. * @see http://doc.babylonjs.com/features/behaviour
  15540. * @param behavior defines the behavior to attach
  15541. * @returns the current Node
  15542. */
  15543. Node.prototype.removeBehavior = function (behavior) {
  15544. var index = this._behaviors.indexOf(behavior);
  15545. if (index === -1) {
  15546. return this;
  15547. }
  15548. this._behaviors[index].detach();
  15549. this._behaviors.splice(index, 1);
  15550. return this;
  15551. };
  15552. Object.defineProperty(Node.prototype, "behaviors", {
  15553. /**
  15554. * Gets the list of attached behaviors
  15555. * @see http://doc.babylonjs.com/features/behaviour
  15556. */
  15557. get: function () {
  15558. return this._behaviors;
  15559. },
  15560. enumerable: true,
  15561. configurable: true
  15562. });
  15563. /**
  15564. * Gets an attached behavior by name
  15565. * @param name defines the name of the behavior to look for
  15566. * @see http://doc.babylonjs.com/features/behaviour
  15567. * @returns null if behavior was not found else the requested behavior
  15568. */
  15569. Node.prototype.getBehaviorByName = function (name) {
  15570. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  15571. var behavior = _a[_i];
  15572. if (behavior.name === name) {
  15573. return behavior;
  15574. }
  15575. }
  15576. return null;
  15577. };
  15578. /**
  15579. * Returns the world matrix of the node
  15580. * @returns a matrix containing the node's world matrix
  15581. */
  15582. Node.prototype.getWorldMatrix = function () {
  15583. return BABYLON.Matrix.Identity();
  15584. };
  15585. // override it in derived class if you add new variables to the cache
  15586. // and call the parent class method
  15587. /** @ignore */
  15588. Node.prototype._initCache = function () {
  15589. this._cache = {};
  15590. this._cache.parent = undefined;
  15591. };
  15592. /** @ignore */
  15593. Node.prototype.updateCache = function (force) {
  15594. if (!force && this.isSynchronized())
  15595. return;
  15596. this._cache.parent = this.parent;
  15597. this._updateCache();
  15598. };
  15599. // override it in derived class if you add new variables to the cache
  15600. // and call the parent class method if !ignoreParentClass
  15601. /** @ignore */
  15602. Node.prototype._updateCache = function (ignoreParentClass) {
  15603. };
  15604. // override it in derived class if you add new variables to the cache
  15605. /** @ignore */
  15606. Node.prototype._isSynchronized = function () {
  15607. return true;
  15608. };
  15609. /** @ignore */
  15610. Node.prototype._markSyncedWithParent = function () {
  15611. if (this.parent) {
  15612. this._parentRenderId = this.parent._currentRenderId;
  15613. }
  15614. };
  15615. /** @ignore */
  15616. Node.prototype.isSynchronizedWithParent = function () {
  15617. if (!this.parent) {
  15618. return true;
  15619. }
  15620. if (this._parentRenderId !== this.parent._currentRenderId) {
  15621. return false;
  15622. }
  15623. return this.parent.isSynchronized();
  15624. };
  15625. /** @ignore */
  15626. Node.prototype.isSynchronized = function (updateCache) {
  15627. var check = this.hasNewParent();
  15628. check = check || !this.isSynchronizedWithParent();
  15629. check = check || !this._isSynchronized();
  15630. if (updateCache)
  15631. this.updateCache(true);
  15632. return !check;
  15633. };
  15634. /** @ignore */
  15635. Node.prototype.hasNewParent = function (update) {
  15636. if (this._cache.parent === this.parent)
  15637. return false;
  15638. if (update)
  15639. this._cache.parent = this.parent;
  15640. return true;
  15641. };
  15642. /**
  15643. * Is this node ready to be used/rendered
  15644. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  15645. * @return true if the node is ready
  15646. */
  15647. Node.prototype.isReady = function (completeCheck) {
  15648. if (completeCheck === void 0) { completeCheck = false; }
  15649. return this._isReady;
  15650. };
  15651. /**
  15652. * Is this node enabled?
  15653. * If the node has a parent, all ancestors will be checked and false will be returned if any are false (not enabled), otherwise will return true
  15654. * @param checkAncestors indicates if this method should check the ancestors. The default is to check the ancestors. If set to false, the method will return the value of this node without checking ancestors
  15655. * @return whether this node (and its parent) is enabled
  15656. * @see setEnabled
  15657. */
  15658. Node.prototype.isEnabled = function (checkAncestors) {
  15659. if (checkAncestors === void 0) { checkAncestors = true; }
  15660. if (checkAncestors === false) {
  15661. return this._isEnabled;
  15662. }
  15663. if (this._isEnabled === false) {
  15664. return false;
  15665. }
  15666. if (this.parent !== undefined && this.parent !== null) {
  15667. return this.parent.isEnabled(checkAncestors);
  15668. }
  15669. return true;
  15670. };
  15671. /**
  15672. * Set the enabled state of this node
  15673. * @param value defines the new enabled state
  15674. * @see isEnabled
  15675. */
  15676. Node.prototype.setEnabled = function (value) {
  15677. this._isEnabled = value;
  15678. };
  15679. /**
  15680. * Is this node a descendant of the given node?
  15681. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  15682. * @param ancestor defines the parent node to inspect
  15683. * @see parent
  15684. * @returns a boolean indicating if this node is a descendant of the given node
  15685. */
  15686. Node.prototype.isDescendantOf = function (ancestor) {
  15687. if (this.parent) {
  15688. if (this.parent === ancestor) {
  15689. return true;
  15690. }
  15691. return this.parent.isDescendantOf(ancestor);
  15692. }
  15693. return false;
  15694. };
  15695. /** @ignore */
  15696. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  15697. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  15698. if (!this._children) {
  15699. return;
  15700. }
  15701. for (var index = 0; index < this._children.length; index++) {
  15702. var item = this._children[index];
  15703. if (!predicate || predicate(item)) {
  15704. results.push(item);
  15705. }
  15706. if (!directDescendantsOnly) {
  15707. item._getDescendants(results, false, predicate);
  15708. }
  15709. }
  15710. };
  15711. /**
  15712. * Will return all nodes that have this node as ascendant
  15713. * @param directDescendantsOnly defines if true only direct descendants of 'this' will be considered, if false direct and also indirect (children of children, an so on in a recursive manner) descendants of 'this' will be considered
  15714. * @param predicate defines an optional predicate that will be called on every evaluated child, the predicate must return true for a given child to be part of the result, otherwise it will be ignored
  15715. * @return all children nodes of all types
  15716. */
  15717. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  15718. var results = new Array();
  15719. this._getDescendants(results, directDescendantsOnly, predicate);
  15720. return results;
  15721. };
  15722. /**
  15723. * Get all child-meshes of this node
  15724. * @param directDescendantsOnly defines if true only direct descendants of 'this' will be considered, if false direct and also indirect (children of children, an so on in a recursive manner) descendants of 'this' will be considered
  15725. * @param predicate defines an optional predicate that will be called on every evaluated child, the predicate must return true for a given child to be part of the result, otherwise it will be ignored
  15726. * @returns an array of {BABYLON.AbstractMesh}
  15727. */
  15728. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  15729. var results = [];
  15730. this._getDescendants(results, directDescendantsOnly, function (node) {
  15731. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  15732. });
  15733. return results;
  15734. };
  15735. /**
  15736. * Get all child-transformNodes of this node
  15737. * @param directDescendantsOnly defines if true only direct descendants of 'this' will be considered, if false direct and also indirect (children of children, an so on in a recursive manner) descendants of 'this' will be considered
  15738. * @param predicate defines an optional predicate that will be called on every evaluated child, the predicate must return true for a given child to be part of the result, otherwise it will be ignored
  15739. * @returns an array of {BABYLON.TransformNode}
  15740. */
  15741. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  15742. var results = [];
  15743. this._getDescendants(results, directDescendantsOnly, function (node) {
  15744. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  15745. });
  15746. return results;
  15747. };
  15748. /**
  15749. * Get all direct children of this node
  15750. * @param predicate defines an optional predicate that will be called on every evaluated child, the predicate must return true for a given child to be part of the result, otherwise it will be ignored
  15751. * @returns an array of {BABYLON.Node}
  15752. */
  15753. Node.prototype.getChildren = function (predicate) {
  15754. return this.getDescendants(true, predicate);
  15755. };
  15756. /** @ignore */
  15757. Node.prototype._setReady = function (state) {
  15758. if (state === this._isReady) {
  15759. return;
  15760. }
  15761. if (!state) {
  15762. this._isReady = false;
  15763. return;
  15764. }
  15765. this._isReady = true;
  15766. if (this.onReady) {
  15767. this.onReady(this);
  15768. }
  15769. };
  15770. /**
  15771. * Get an animation by name
  15772. * @param name defines the name of the animation to look for
  15773. * @returns null if not found else the requested animation
  15774. */
  15775. Node.prototype.getAnimationByName = function (name) {
  15776. for (var i = 0; i < this.animations.length; i++) {
  15777. var animation = this.animations[i];
  15778. if (animation.name === name) {
  15779. return animation;
  15780. }
  15781. }
  15782. return null;
  15783. };
  15784. /**
  15785. * Creates an animation range for this node
  15786. * @param name defines the name of the range
  15787. * @param from defines the starting key
  15788. * @param to defines the end key
  15789. */
  15790. Node.prototype.createAnimationRange = function (name, from, to) {
  15791. // check name not already in use
  15792. if (!this._ranges[name]) {
  15793. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  15794. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  15795. if (this.animations[i]) {
  15796. this.animations[i].createRange(name, from, to);
  15797. }
  15798. }
  15799. }
  15800. };
  15801. /**
  15802. * Delete a specific animation range
  15803. * @param name defines the name of the range to delete
  15804. * @param deleteFrames defines if animation frames from the range must be deleted as well
  15805. */
  15806. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  15807. if (deleteFrames === void 0) { deleteFrames = true; }
  15808. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  15809. if (this.animations[i]) {
  15810. this.animations[i].deleteRange(name, deleteFrames);
  15811. }
  15812. }
  15813. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  15814. };
  15815. /**
  15816. * Get an animation range by name
  15817. * @param name defines the name of the animation range to look for
  15818. * @returns null if not found else the requested animation range
  15819. */
  15820. Node.prototype.getAnimationRange = function (name) {
  15821. return this._ranges[name];
  15822. };
  15823. /**
  15824. * Will start the animation sequence
  15825. * @param name defines the range frames for animation sequence
  15826. * @param loop defines if the animation should loop (false by default)
  15827. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  15828. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  15829. * @returns the object created for this animation. If range does not exist, it will return null
  15830. */
  15831. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  15832. var range = this.getAnimationRange(name);
  15833. if (!range) {
  15834. return null;
  15835. }
  15836. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  15837. };
  15838. /**
  15839. * Serialize animation ranges into a JSON compatible object
  15840. * @returns serialization object
  15841. */
  15842. Node.prototype.serializeAnimationRanges = function () {
  15843. var serializationRanges = [];
  15844. for (var name in this._ranges) {
  15845. var localRange = this._ranges[name];
  15846. if (!localRange) {
  15847. continue;
  15848. }
  15849. var range = {};
  15850. range.name = name;
  15851. range.from = localRange.from;
  15852. range.to = localRange.to;
  15853. serializationRanges.push(range);
  15854. }
  15855. return serializationRanges;
  15856. };
  15857. /**
  15858. * Computes the world matrix of the node
  15859. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  15860. * @returns the world matrix
  15861. */
  15862. Node.prototype.computeWorldMatrix = function (force) {
  15863. return BABYLON.Matrix.Identity();
  15864. };
  15865. /**
  15866. * Releases all associated resources
  15867. */
  15868. Node.prototype.dispose = function () {
  15869. this.parent = null;
  15870. // Callback
  15871. this.onDisposeObservable.notifyObservers(this);
  15872. this.onDisposeObservable.clear();
  15873. // Behaviors
  15874. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  15875. var behavior = _a[_i];
  15876. behavior.detach();
  15877. }
  15878. this._behaviors = [];
  15879. this._isDisposed = true;
  15880. };
  15881. /**
  15882. * Parse animation range data from a serialization object and store them into a given node
  15883. * @param node defines where to store the animation ranges
  15884. * @param parsedNode defines the serialization object to read data from
  15885. * @param scene defines the hosting scene
  15886. */
  15887. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  15888. if (parsedNode.ranges) {
  15889. for (var index = 0; index < parsedNode.ranges.length; index++) {
  15890. var data = parsedNode.ranges[index];
  15891. node.createAnimationRange(data.name, data.from, data.to);
  15892. }
  15893. }
  15894. };
  15895. __decorate([
  15896. BABYLON.serialize()
  15897. ], Node.prototype, "name", void 0);
  15898. __decorate([
  15899. BABYLON.serialize()
  15900. ], Node.prototype, "id", void 0);
  15901. __decorate([
  15902. BABYLON.serialize()
  15903. ], Node.prototype, "uniqueId", void 0);
  15904. __decorate([
  15905. BABYLON.serialize()
  15906. ], Node.prototype, "state", void 0);
  15907. __decorate([
  15908. BABYLON.serialize()
  15909. ], Node.prototype, "metadata", void 0);
  15910. return Node;
  15911. }());
  15912. BABYLON.Node = Node;
  15913. })(BABYLON || (BABYLON = {}));
  15914. //# sourceMappingURL=babylon.node.js.map
  15915. var BABYLON;
  15916. (function (BABYLON) {
  15917. var BoundingSphere = /** @class */ (function () {
  15918. function BoundingSphere(minimum, maximum) {
  15919. this.minimum = minimum;
  15920. this.maximum = maximum;
  15921. this._tempRadiusVector = BABYLON.Vector3.Zero();
  15922. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  15923. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  15924. this.radius = distance * 0.5;
  15925. this.centerWorld = BABYLON.Vector3.Zero();
  15926. this._update(BABYLON.Matrix.Identity());
  15927. }
  15928. // Methods
  15929. BoundingSphere.prototype._update = function (world) {
  15930. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  15931. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  15932. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  15933. };
  15934. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  15935. for (var i = 0; i < 6; i++) {
  15936. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  15937. return false;
  15938. }
  15939. return true;
  15940. };
  15941. BoundingSphere.prototype.intersectsPoint = function (point) {
  15942. var x = this.centerWorld.x - point.x;
  15943. var y = this.centerWorld.y - point.y;
  15944. var z = this.centerWorld.z - point.z;
  15945. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  15946. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  15947. return false;
  15948. return true;
  15949. };
  15950. // Statics
  15951. BoundingSphere.Intersects = function (sphere0, sphere1) {
  15952. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  15953. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  15954. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  15955. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  15956. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  15957. return false;
  15958. return true;
  15959. };
  15960. return BoundingSphere;
  15961. }());
  15962. BABYLON.BoundingSphere = BoundingSphere;
  15963. })(BABYLON || (BABYLON = {}));
  15964. //# sourceMappingURL=babylon.boundingSphere.js.map
  15965. var BABYLON;
  15966. (function (BABYLON) {
  15967. var BoundingBox = /** @class */ (function () {
  15968. function BoundingBox(minimum, maximum) {
  15969. this.minimum = minimum;
  15970. this.maximum = maximum;
  15971. this.vectors = new Array();
  15972. this.vectorsWorld = new Array();
  15973. // Bounding vectors
  15974. this.vectors.push(this.minimum.clone());
  15975. this.vectors.push(this.maximum.clone());
  15976. this.vectors.push(this.minimum.clone());
  15977. this.vectors[2].x = this.maximum.x;
  15978. this.vectors.push(this.minimum.clone());
  15979. this.vectors[3].y = this.maximum.y;
  15980. this.vectors.push(this.minimum.clone());
  15981. this.vectors[4].z = this.maximum.z;
  15982. this.vectors.push(this.maximum.clone());
  15983. this.vectors[5].z = this.minimum.z;
  15984. this.vectors.push(this.maximum.clone());
  15985. this.vectors[6].x = this.minimum.x;
  15986. this.vectors.push(this.maximum.clone());
  15987. this.vectors[7].y = this.minimum.y;
  15988. // OBB
  15989. this.center = this.maximum.add(this.minimum).scale(0.5);
  15990. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  15991. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  15992. // World
  15993. for (var index = 0; index < this.vectors.length; index++) {
  15994. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  15995. }
  15996. this.minimumWorld = BABYLON.Vector3.Zero();
  15997. this.maximumWorld = BABYLON.Vector3.Zero();
  15998. this.centerWorld = BABYLON.Vector3.Zero();
  15999. this.extendSizeWorld = BABYLON.Vector3.Zero();
  16000. this._update(BABYLON.Matrix.Identity());
  16001. }
  16002. // Methods
  16003. BoundingBox.prototype.getWorldMatrix = function () {
  16004. return this._worldMatrix;
  16005. };
  16006. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  16007. this._worldMatrix.copyFrom(matrix);
  16008. return this;
  16009. };
  16010. BoundingBox.prototype._update = function (world) {
  16011. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  16012. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  16013. for (var index = 0; index < this.vectors.length; index++) {
  16014. var v = this.vectorsWorld[index];
  16015. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  16016. if (v.x < this.minimumWorld.x)
  16017. this.minimumWorld.x = v.x;
  16018. if (v.y < this.minimumWorld.y)
  16019. this.minimumWorld.y = v.y;
  16020. if (v.z < this.minimumWorld.z)
  16021. this.minimumWorld.z = v.z;
  16022. if (v.x > this.maximumWorld.x)
  16023. this.maximumWorld.x = v.x;
  16024. if (v.y > this.maximumWorld.y)
  16025. this.maximumWorld.y = v.y;
  16026. if (v.z > this.maximumWorld.z)
  16027. this.maximumWorld.z = v.z;
  16028. }
  16029. // Extend
  16030. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  16031. this.extendSizeWorld.scaleInPlace(0.5);
  16032. // OBB
  16033. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  16034. this.centerWorld.scaleInPlace(0.5);
  16035. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  16036. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  16037. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  16038. this._worldMatrix = world;
  16039. };
  16040. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  16041. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  16042. };
  16043. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  16044. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  16045. };
  16046. BoundingBox.prototype.intersectsPoint = function (point) {
  16047. var delta = -BABYLON.Epsilon;
  16048. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  16049. return false;
  16050. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  16051. return false;
  16052. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  16053. return false;
  16054. return true;
  16055. };
  16056. BoundingBox.prototype.intersectsSphere = function (sphere) {
  16057. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  16058. };
  16059. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  16060. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  16061. return false;
  16062. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  16063. return false;
  16064. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  16065. return false;
  16066. return true;
  16067. };
  16068. // Statics
  16069. BoundingBox.Intersects = function (box0, box1) {
  16070. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  16071. return false;
  16072. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  16073. return false;
  16074. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  16075. return false;
  16076. return true;
  16077. };
  16078. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  16079. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  16080. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  16081. return (num <= (sphereRadius * sphereRadius));
  16082. };
  16083. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  16084. for (var p = 0; p < 6; p++) {
  16085. for (var i = 0; i < 8; i++) {
  16086. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  16087. return false;
  16088. }
  16089. }
  16090. }
  16091. return true;
  16092. };
  16093. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  16094. for (var p = 0; p < 6; p++) {
  16095. var inCount = 8;
  16096. for (var i = 0; i < 8; i++) {
  16097. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  16098. --inCount;
  16099. }
  16100. else {
  16101. break;
  16102. }
  16103. }
  16104. if (inCount === 0)
  16105. return false;
  16106. }
  16107. return true;
  16108. };
  16109. return BoundingBox;
  16110. }());
  16111. BABYLON.BoundingBox = BoundingBox;
  16112. })(BABYLON || (BABYLON = {}));
  16113. //# sourceMappingURL=babylon.boundingBox.js.map
  16114. var BABYLON;
  16115. (function (BABYLON) {
  16116. var computeBoxExtents = function (axis, box) {
  16117. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  16118. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  16119. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  16120. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  16121. var r = r0 + r1 + r2;
  16122. return {
  16123. min: p - r,
  16124. max: p + r
  16125. };
  16126. };
  16127. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  16128. var axisOverlap = function (axis, box0, box1) {
  16129. var result0 = computeBoxExtents(axis, box0);
  16130. var result1 = computeBoxExtents(axis, box1);
  16131. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  16132. };
  16133. var BoundingInfo = /** @class */ (function () {
  16134. function BoundingInfo(minimum, maximum) {
  16135. this.minimum = minimum;
  16136. this.maximum = maximum;
  16137. this._isLocked = false;
  16138. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  16139. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  16140. }
  16141. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  16142. get: function () {
  16143. return this._isLocked;
  16144. },
  16145. set: function (value) {
  16146. this._isLocked = value;
  16147. },
  16148. enumerable: true,
  16149. configurable: true
  16150. });
  16151. // Methods
  16152. BoundingInfo.prototype.update = function (world) {
  16153. if (this._isLocked) {
  16154. return;
  16155. }
  16156. this.boundingBox._update(world);
  16157. this.boundingSphere._update(world);
  16158. };
  16159. /**
  16160. * Recreate the bounding info to be centered around a specific point given a specific extend.
  16161. * @param center New center of the bounding info
  16162. * @param extend New extend of the bounding info
  16163. */
  16164. BoundingInfo.prototype.centerOn = function (center, extend) {
  16165. this.minimum = center.subtract(extend);
  16166. this.maximum = center.add(extend);
  16167. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  16168. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  16169. return this;
  16170. };
  16171. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  16172. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  16173. return false;
  16174. return this.boundingBox.isInFrustum(frustumPlanes);
  16175. };
  16176. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  16177. /**
  16178. * Gets the world distance between the min and max points of the bounding box
  16179. */
  16180. get: function () {
  16181. var boundingBox = this.boundingBox;
  16182. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  16183. return size.length();
  16184. },
  16185. enumerable: true,
  16186. configurable: true
  16187. });
  16188. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  16189. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  16190. };
  16191. BoundingInfo.prototype._checkCollision = function (collider) {
  16192. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  16193. };
  16194. BoundingInfo.prototype.intersectsPoint = function (point) {
  16195. if (!this.boundingSphere.centerWorld) {
  16196. return false;
  16197. }
  16198. if (!this.boundingSphere.intersectsPoint(point)) {
  16199. return false;
  16200. }
  16201. if (!this.boundingBox.intersectsPoint(point)) {
  16202. return false;
  16203. }
  16204. return true;
  16205. };
  16206. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  16207. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  16208. return false;
  16209. }
  16210. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  16211. return false;
  16212. }
  16213. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  16214. return false;
  16215. }
  16216. if (!precise) {
  16217. return true;
  16218. }
  16219. var box0 = this.boundingBox;
  16220. var box1 = boundingInfo.boundingBox;
  16221. if (!axisOverlap(box0.directions[0], box0, box1))
  16222. return false;
  16223. if (!axisOverlap(box0.directions[1], box0, box1))
  16224. return false;
  16225. if (!axisOverlap(box0.directions[2], box0, box1))
  16226. return false;
  16227. if (!axisOverlap(box1.directions[0], box0, box1))
  16228. return false;
  16229. if (!axisOverlap(box1.directions[1], box0, box1))
  16230. return false;
  16231. if (!axisOverlap(box1.directions[2], box0, box1))
  16232. return false;
  16233. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  16234. return false;
  16235. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  16236. return false;
  16237. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  16238. return false;
  16239. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  16240. return false;
  16241. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  16242. return false;
  16243. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  16244. return false;
  16245. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  16246. return false;
  16247. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  16248. return false;
  16249. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  16250. return false;
  16251. return true;
  16252. };
  16253. return BoundingInfo;
  16254. }());
  16255. BABYLON.BoundingInfo = BoundingInfo;
  16256. })(BABYLON || (BABYLON = {}));
  16257. //# sourceMappingURL=babylon.boundingInfo.js.map
  16258. var BABYLON;
  16259. (function (BABYLON) {
  16260. var TransformNode = /** @class */ (function (_super) {
  16261. __extends(TransformNode, _super);
  16262. function TransformNode(name, scene, isPure) {
  16263. if (scene === void 0) { scene = null; }
  16264. if (isPure === void 0) { isPure = true; }
  16265. var _this = _super.call(this, name, scene) || this;
  16266. // Properties
  16267. _this._rotation = BABYLON.Vector3.Zero();
  16268. _this._scaling = BABYLON.Vector3.One();
  16269. _this._isDirty = false;
  16270. _this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_NONE;
  16271. _this.scalingDeterminant = 1;
  16272. _this.infiniteDistance = false;
  16273. _this.position = BABYLON.Vector3.Zero();
  16274. _this._localWorld = BABYLON.Matrix.Zero();
  16275. _this._worldMatrix = BABYLON.Matrix.Zero();
  16276. _this._worldMatrixDeterminant = 0;
  16277. _this._absolutePosition = BABYLON.Vector3.Zero();
  16278. _this._pivotMatrix = BABYLON.Matrix.Identity();
  16279. _this._postMultiplyPivotMatrix = false;
  16280. _this._isWorldMatrixFrozen = false;
  16281. /**
  16282. * An event triggered after the world matrix is updated
  16283. * @type {BABYLON.Observable}
  16284. */
  16285. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  16286. _this._nonUniformScaling = false;
  16287. if (isPure) {
  16288. _this.getScene().addTransformNode(_this);
  16289. }
  16290. return _this;
  16291. }
  16292. Object.defineProperty(TransformNode.prototype, "rotation", {
  16293. /**
  16294. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  16295. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  16296. * Default : (0.0, 0.0, 0.0)
  16297. */
  16298. get: function () {
  16299. return this._rotation;
  16300. },
  16301. set: function (newRotation) {
  16302. this._rotation = newRotation;
  16303. },
  16304. enumerable: true,
  16305. configurable: true
  16306. });
  16307. Object.defineProperty(TransformNode.prototype, "scaling", {
  16308. /**
  16309. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  16310. * Default : (1.0, 1.0, 1.0)
  16311. */
  16312. get: function () {
  16313. return this._scaling;
  16314. },
  16315. /**
  16316. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  16317. * Default : (1.0, 1.0, 1.0)
  16318. */
  16319. set: function (newScaling) {
  16320. this._scaling = newScaling;
  16321. },
  16322. enumerable: true,
  16323. configurable: true
  16324. });
  16325. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  16326. /**
  16327. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  16328. * It's null by default.
  16329. * 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)
  16330. */
  16331. get: function () {
  16332. return this._rotationQuaternion;
  16333. },
  16334. set: function (quaternion) {
  16335. this._rotationQuaternion = quaternion;
  16336. //reset the rotation vector.
  16337. if (quaternion && this.rotation.length()) {
  16338. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  16339. }
  16340. },
  16341. enumerable: true,
  16342. configurable: true
  16343. });
  16344. /**
  16345. * Returns the latest update of the World matrix
  16346. * Returns a Matrix.
  16347. */
  16348. TransformNode.prototype.getWorldMatrix = function () {
  16349. if (this._currentRenderId !== this.getScene().getRenderId()) {
  16350. this.computeWorldMatrix();
  16351. }
  16352. return this._worldMatrix;
  16353. };
  16354. /**
  16355. * Returns the latest update of the World matrix determinant.
  16356. */
  16357. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  16358. return this._worldMatrixDeterminant;
  16359. };
  16360. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  16361. /**
  16362. * Returns directly the latest state of the mesh World matrix.
  16363. * A Matrix is returned.
  16364. */
  16365. get: function () {
  16366. return this._worldMatrix;
  16367. },
  16368. enumerable: true,
  16369. configurable: true
  16370. });
  16371. /**
  16372. * Copies the paramater passed Matrix into the mesh Pose matrix.
  16373. * Returns the AbstractMesh.
  16374. */
  16375. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  16376. this._poseMatrix.copyFrom(matrix);
  16377. return this;
  16378. };
  16379. /**
  16380. * Returns the mesh Pose matrix.
  16381. * Returned object : Matrix
  16382. */
  16383. TransformNode.prototype.getPoseMatrix = function () {
  16384. return this._poseMatrix;
  16385. };
  16386. TransformNode.prototype._isSynchronized = function () {
  16387. if (this._isDirty) {
  16388. return false;
  16389. }
  16390. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE)
  16391. return false;
  16392. if (this._cache.pivotMatrixUpdated) {
  16393. return false;
  16394. }
  16395. if (this.infiniteDistance) {
  16396. return false;
  16397. }
  16398. if (!this._cache.position.equals(this.position))
  16399. return false;
  16400. if (this.rotationQuaternion) {
  16401. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  16402. return false;
  16403. }
  16404. if (!this._cache.rotation.equals(this.rotation))
  16405. return false;
  16406. if (!this._cache.scaling.equals(this.scaling))
  16407. return false;
  16408. return true;
  16409. };
  16410. TransformNode.prototype._initCache = function () {
  16411. _super.prototype._initCache.call(this);
  16412. this._cache.localMatrixUpdated = false;
  16413. this._cache.position = BABYLON.Vector3.Zero();
  16414. this._cache.scaling = BABYLON.Vector3.Zero();
  16415. this._cache.rotation = BABYLON.Vector3.Zero();
  16416. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  16417. this._cache.billboardMode = -1;
  16418. };
  16419. TransformNode.prototype.markAsDirty = function (property) {
  16420. if (property === "rotation") {
  16421. this.rotationQuaternion = null;
  16422. }
  16423. this._currentRenderId = Number.MAX_VALUE;
  16424. this._isDirty = true;
  16425. return this;
  16426. };
  16427. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  16428. /**
  16429. * Returns the current mesh absolute position.
  16430. * Retuns a Vector3.
  16431. */
  16432. get: function () {
  16433. return this._absolutePosition;
  16434. },
  16435. enumerable: true,
  16436. configurable: true
  16437. });
  16438. /**
  16439. * Sets a new matrix to apply before all other transformation
  16440. * @param matrix defines the transform matrix
  16441. * @returns the current TransformNode
  16442. */
  16443. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  16444. return this.setPivotMatrix(matrix, false);
  16445. };
  16446. /**
  16447. * Sets a new pivot matrix to the current node
  16448. * @param matrix defines the new pivot matrix to use
  16449. * @param postMultiplyPivotMatrix defines if the pivot matrix must be cancelled in the world matrix. When this parameter is set to true (default), the inverse of the pivot matrix is also applied at the end to cancel the transformation effect
  16450. * @returns the current TransformNode
  16451. */
  16452. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  16453. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  16454. this._pivotMatrix = matrix.clone();
  16455. this._cache.pivotMatrixUpdated = true;
  16456. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  16457. if (this._postMultiplyPivotMatrix) {
  16458. if (!this._pivotMatrixInverse) {
  16459. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  16460. }
  16461. else {
  16462. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  16463. }
  16464. }
  16465. return this;
  16466. };
  16467. /**
  16468. * Returns the mesh pivot matrix.
  16469. * Default : Identity.
  16470. * A Matrix is returned.
  16471. */
  16472. TransformNode.prototype.getPivotMatrix = function () {
  16473. return this._pivotMatrix;
  16474. };
  16475. /**
  16476. * Prevents the World matrix to be computed any longer.
  16477. * Returns the AbstractMesh.
  16478. */
  16479. TransformNode.prototype.freezeWorldMatrix = function () {
  16480. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  16481. this.computeWorldMatrix(true);
  16482. this._isWorldMatrixFrozen = true;
  16483. return this;
  16484. };
  16485. /**
  16486. * Allows back the World matrix computation.
  16487. * Returns the AbstractMesh.
  16488. */
  16489. TransformNode.prototype.unfreezeWorldMatrix = function () {
  16490. this._isWorldMatrixFrozen = false;
  16491. this.computeWorldMatrix(true);
  16492. return this;
  16493. };
  16494. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  16495. /**
  16496. * True if the World matrix has been frozen.
  16497. * Returns a boolean.
  16498. */
  16499. get: function () {
  16500. return this._isWorldMatrixFrozen;
  16501. },
  16502. enumerable: true,
  16503. configurable: true
  16504. });
  16505. /**
  16506. * Retuns the mesh absolute position in the World.
  16507. * Returns a Vector3.
  16508. */
  16509. TransformNode.prototype.getAbsolutePosition = function () {
  16510. this.computeWorldMatrix();
  16511. return this._absolutePosition;
  16512. };
  16513. /**
  16514. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  16515. * Returns the AbstractMesh.
  16516. */
  16517. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  16518. if (!absolutePosition) {
  16519. return this;
  16520. }
  16521. var absolutePositionX;
  16522. var absolutePositionY;
  16523. var absolutePositionZ;
  16524. if (absolutePosition.x === undefined) {
  16525. if (arguments.length < 3) {
  16526. return this;
  16527. }
  16528. absolutePositionX = arguments[0];
  16529. absolutePositionY = arguments[1];
  16530. absolutePositionZ = arguments[2];
  16531. }
  16532. else {
  16533. absolutePositionX = absolutePosition.x;
  16534. absolutePositionY = absolutePosition.y;
  16535. absolutePositionZ = absolutePosition.z;
  16536. }
  16537. if (this.parent) {
  16538. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  16539. invertParentWorldMatrix.invert();
  16540. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  16541. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  16542. }
  16543. else {
  16544. this.position.x = absolutePositionX;
  16545. this.position.y = absolutePositionY;
  16546. this.position.z = absolutePositionZ;
  16547. }
  16548. return this;
  16549. };
  16550. /**
  16551. * Sets the mesh position in its local space.
  16552. * Returns the AbstractMesh.
  16553. */
  16554. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  16555. this.computeWorldMatrix();
  16556. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  16557. return this;
  16558. };
  16559. /**
  16560. * Returns the mesh position in the local space from the current World matrix values.
  16561. * Returns a new Vector3.
  16562. */
  16563. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  16564. this.computeWorldMatrix();
  16565. var invLocalWorldMatrix = this._localWorld.clone();
  16566. invLocalWorldMatrix.invert();
  16567. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  16568. };
  16569. /**
  16570. * Translates the mesh along the passed Vector3 in its local space.
  16571. * Returns the AbstractMesh.
  16572. */
  16573. TransformNode.prototype.locallyTranslate = function (vector3) {
  16574. this.computeWorldMatrix(true);
  16575. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  16576. return this;
  16577. };
  16578. /**
  16579. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  16580. * @param targetPoint the position (must be in same space as current mesh) to look at
  16581. * @param yawCor optional yaw (y-axis) correction in radians
  16582. * @param pitchCor optional pitch (x-axis) correction in radians
  16583. * @param rollCor optional roll (z-axis) correction in radians
  16584. * @param space the choosen space of the target
  16585. * @returns the TransformNode.
  16586. */
  16587. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  16588. if (yawCor === void 0) { yawCor = 0; }
  16589. if (pitchCor === void 0) { pitchCor = 0; }
  16590. if (rollCor === void 0) { rollCor = 0; }
  16591. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  16592. var dv = BABYLON.AbstractMesh._lookAtVectorCache;
  16593. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  16594. targetPoint.subtractToRef(pos, dv);
  16595. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  16596. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  16597. var pitch = Math.atan2(dv.y, len);
  16598. if (this.rotationQuaternion) {
  16599. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  16600. }
  16601. else {
  16602. this.rotation.x = pitch + pitchCor;
  16603. this.rotation.y = yaw + yawCor;
  16604. this.rotation.z = rollCor;
  16605. }
  16606. return this;
  16607. };
  16608. /**
  16609. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  16610. * This Vector3 is expressed in the World space.
  16611. */
  16612. TransformNode.prototype.getDirection = function (localAxis) {
  16613. var result = BABYLON.Vector3.Zero();
  16614. this.getDirectionToRef(localAxis, result);
  16615. return result;
  16616. };
  16617. /**
  16618. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  16619. * localAxis is expressed in the mesh local space.
  16620. * result is computed in the Wordl space from the mesh World matrix.
  16621. * Returns the AbstractMesh.
  16622. */
  16623. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  16624. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  16625. return this;
  16626. };
  16627. /**
  16628. * Sets a new pivot point to the current node
  16629. * @param point defines the new pivot point to use
  16630. * @param space defines if the point is in world or local space (local by default)
  16631. * @returns the current TransformNode
  16632. */
  16633. TransformNode.prototype.setPivotPoint = function (point, space) {
  16634. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  16635. if (this.getScene().getRenderId() == 0) {
  16636. this.computeWorldMatrix(true);
  16637. }
  16638. var wm = this.getWorldMatrix();
  16639. if (space == BABYLON.Space.WORLD) {
  16640. var tmat = BABYLON.Tmp.Matrix[0];
  16641. wm.invertToRef(tmat);
  16642. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  16643. }
  16644. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  16645. };
  16646. /**
  16647. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  16648. */
  16649. TransformNode.prototype.getPivotPoint = function () {
  16650. var point = BABYLON.Vector3.Zero();
  16651. this.getPivotPointToRef(point);
  16652. return point;
  16653. };
  16654. /**
  16655. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  16656. * Returns the AbstractMesh.
  16657. */
  16658. TransformNode.prototype.getPivotPointToRef = function (result) {
  16659. result.x = -this._pivotMatrix.m[12];
  16660. result.y = -this._pivotMatrix.m[13];
  16661. result.z = -this._pivotMatrix.m[14];
  16662. return this;
  16663. };
  16664. /**
  16665. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  16666. */
  16667. TransformNode.prototype.getAbsolutePivotPoint = function () {
  16668. var point = BABYLON.Vector3.Zero();
  16669. this.getAbsolutePivotPointToRef(point);
  16670. return point;
  16671. };
  16672. /**
  16673. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  16674. * Returns the AbstractMesh.
  16675. */
  16676. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  16677. result.x = this._pivotMatrix.m[12];
  16678. result.y = this._pivotMatrix.m[13];
  16679. result.z = this._pivotMatrix.m[14];
  16680. this.getPivotPointToRef(result);
  16681. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  16682. return this;
  16683. };
  16684. /**
  16685. * Defines the passed node as the parent of the current node.
  16686. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  16687. * Returns the TransformNode.
  16688. */
  16689. TransformNode.prototype.setParent = function (node) {
  16690. if (node === null) {
  16691. var rotation = BABYLON.Tmp.Quaternion[0];
  16692. var position = BABYLON.Tmp.Vector3[0];
  16693. var scale = BABYLON.Tmp.Vector3[1];
  16694. if (this.parent && this.parent.computeWorldMatrix) {
  16695. this.parent.computeWorldMatrix(true);
  16696. }
  16697. this.computeWorldMatrix(true);
  16698. this.getWorldMatrix().decompose(scale, rotation, position);
  16699. if (this.rotationQuaternion) {
  16700. this.rotationQuaternion.copyFrom(rotation);
  16701. }
  16702. else {
  16703. rotation.toEulerAnglesToRef(this.rotation);
  16704. }
  16705. this.scaling.x = scale.x;
  16706. this.scaling.y = scale.y;
  16707. this.scaling.z = scale.z;
  16708. this.position.x = position.x;
  16709. this.position.y = position.y;
  16710. this.position.z = position.z;
  16711. }
  16712. else {
  16713. var rotation = BABYLON.Tmp.Quaternion[0];
  16714. var position = BABYLON.Tmp.Vector3[0];
  16715. var scale = BABYLON.Tmp.Vector3[1];
  16716. var diffMatrix = BABYLON.Tmp.Matrix[0];
  16717. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  16718. this.computeWorldMatrix(true);
  16719. node.computeWorldMatrix(true);
  16720. node.getWorldMatrix().invertToRef(invParentMatrix);
  16721. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  16722. diffMatrix.decompose(scale, rotation, position);
  16723. if (this.rotationQuaternion) {
  16724. this.rotationQuaternion.copyFrom(rotation);
  16725. }
  16726. else {
  16727. rotation.toEulerAnglesToRef(this.rotation);
  16728. }
  16729. this.position.x = position.x;
  16730. this.position.y = position.y;
  16731. this.position.z = position.z;
  16732. this.scaling.x = scale.x;
  16733. this.scaling.y = scale.y;
  16734. this.scaling.z = scale.z;
  16735. }
  16736. this.parent = node;
  16737. return this;
  16738. };
  16739. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  16740. get: function () {
  16741. return this._nonUniformScaling;
  16742. },
  16743. enumerable: true,
  16744. configurable: true
  16745. });
  16746. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  16747. if (this._nonUniformScaling === value) {
  16748. return false;
  16749. }
  16750. this._nonUniformScaling = true;
  16751. return true;
  16752. };
  16753. /**
  16754. * Attach the current TransformNode to another TransformNode associated with a bone
  16755. * @param bone Bone affecting the TransformNode
  16756. * @param affectedTransformNode TransformNode associated with the bone
  16757. */
  16758. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  16759. this._transformToBoneReferal = affectedTransformNode;
  16760. this.parent = bone;
  16761. if (bone.getWorldMatrix().determinant() < 0) {
  16762. this.scalingDeterminant *= -1;
  16763. }
  16764. return this;
  16765. };
  16766. TransformNode.prototype.detachFromBone = function () {
  16767. if (!this.parent) {
  16768. return this;
  16769. }
  16770. if (this.parent.getWorldMatrix().determinant() < 0) {
  16771. this.scalingDeterminant *= -1;
  16772. }
  16773. this._transformToBoneReferal = null;
  16774. this.parent = null;
  16775. return this;
  16776. };
  16777. /**
  16778. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  16779. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  16780. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  16781. * The passed axis is also normalized.
  16782. * Returns the AbstractMesh.
  16783. */
  16784. TransformNode.prototype.rotate = function (axis, amount, space) {
  16785. axis.normalize();
  16786. if (!this.rotationQuaternion) {
  16787. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  16788. this.rotation = BABYLON.Vector3.Zero();
  16789. }
  16790. var rotationQuaternion;
  16791. if (!space || space === BABYLON.Space.LOCAL) {
  16792. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  16793. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  16794. }
  16795. else {
  16796. if (this.parent) {
  16797. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  16798. invertParentWorldMatrix.invert();
  16799. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  16800. }
  16801. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  16802. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  16803. }
  16804. return this;
  16805. };
  16806. /**
  16807. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  16808. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  16809. * The passed axis is also normalized.
  16810. * Returns the AbstractMesh.
  16811. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  16812. */
  16813. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  16814. axis.normalize();
  16815. if (!this.rotationQuaternion) {
  16816. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  16817. this.rotation.copyFromFloats(0, 0, 0);
  16818. }
  16819. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  16820. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  16821. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  16822. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  16823. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  16824. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  16825. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  16826. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  16827. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  16828. return this;
  16829. };
  16830. /**
  16831. * Translates the mesh along the axis vector for the passed distance in the given space.
  16832. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  16833. * Returns the AbstractMesh.
  16834. */
  16835. TransformNode.prototype.translate = function (axis, distance, space) {
  16836. var displacementVector = axis.scale(distance);
  16837. if (!space || space === BABYLON.Space.LOCAL) {
  16838. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  16839. this.setPositionWithLocalVector(tempV3);
  16840. }
  16841. else {
  16842. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  16843. }
  16844. return this;
  16845. };
  16846. /**
  16847. * Adds a rotation step to the mesh current rotation.
  16848. * x, y, z are Euler angles expressed in radians.
  16849. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  16850. * This means this rotation is made in the mesh local space only.
  16851. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  16852. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  16853. * ```javascript
  16854. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  16855. * ```
  16856. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  16857. * 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.
  16858. * Returns the AbstractMesh.
  16859. */
  16860. TransformNode.prototype.addRotation = function (x, y, z) {
  16861. var rotationQuaternion;
  16862. if (this.rotationQuaternion) {
  16863. rotationQuaternion = this.rotationQuaternion;
  16864. }
  16865. else {
  16866. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  16867. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  16868. }
  16869. var accumulation = BABYLON.Tmp.Quaternion[0];
  16870. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  16871. rotationQuaternion.multiplyInPlace(accumulation);
  16872. if (!this.rotationQuaternion) {
  16873. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  16874. }
  16875. return this;
  16876. };
  16877. /**
  16878. * Computes the mesh World matrix and returns it.
  16879. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  16880. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  16881. * If the parameter `force`is set to `true`, the actual computation is done.
  16882. * Returns the mesh World Matrix.
  16883. */
  16884. TransformNode.prototype.computeWorldMatrix = function (force) {
  16885. if (this._isWorldMatrixFrozen) {
  16886. return this._worldMatrix;
  16887. }
  16888. if (!force && this.isSynchronized(true)) {
  16889. return this._worldMatrix;
  16890. }
  16891. this._cache.position.copyFrom(this.position);
  16892. this._cache.scaling.copyFrom(this.scaling);
  16893. this._cache.pivotMatrixUpdated = false;
  16894. this._cache.billboardMode = this.billboardMode;
  16895. this._currentRenderId = this.getScene().getRenderId();
  16896. this._isDirty = false;
  16897. // Scaling
  16898. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  16899. // Rotation
  16900. //rotate, if quaternion is set and rotation was used
  16901. if (this.rotationQuaternion) {
  16902. var len = this.rotation.length();
  16903. if (len) {
  16904. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  16905. this.rotation.copyFromFloats(0, 0, 0);
  16906. }
  16907. }
  16908. if (this.rotationQuaternion) {
  16909. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  16910. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  16911. }
  16912. else {
  16913. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  16914. this._cache.rotation.copyFrom(this.rotation);
  16915. }
  16916. // Translation
  16917. var camera = this.getScene().activeCamera;
  16918. if (this.infiniteDistance && !this.parent && camera) {
  16919. var cameraWorldMatrix = camera.getWorldMatrix();
  16920. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  16921. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  16922. }
  16923. else {
  16924. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  16925. }
  16926. // Composing transformations
  16927. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  16928. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  16929. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  16930. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE && camera) {
  16931. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_ALL) !== BABYLON.AbstractMesh.BILLBOARDMODE_ALL) {
  16932. // Need to decompose each rotation here
  16933. var currentPosition = BABYLON.Tmp.Vector3[3];
  16934. if (this.parent && this.parent.getWorldMatrix) {
  16935. if (this._transformToBoneReferal) {
  16936. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  16937. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  16938. }
  16939. else {
  16940. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  16941. }
  16942. }
  16943. else {
  16944. currentPosition.copyFrom(this.position);
  16945. }
  16946. currentPosition.subtractInPlace(camera.globalPosition);
  16947. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  16948. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_X) === BABYLON.AbstractMesh.BILLBOARDMODE_X) {
  16949. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  16950. }
  16951. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Y) === BABYLON.AbstractMesh.BILLBOARDMODE_Y) {
  16952. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  16953. }
  16954. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Z) === BABYLON.AbstractMesh.BILLBOARDMODE_Z) {
  16955. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  16956. }
  16957. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  16958. }
  16959. else {
  16960. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  16961. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  16962. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  16963. }
  16964. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  16965. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  16966. }
  16967. // Local world
  16968. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  16969. // Parent
  16970. if (this.parent && this.parent.getWorldMatrix) {
  16971. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE) {
  16972. if (this._transformToBoneReferal) {
  16973. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  16974. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  16975. }
  16976. else {
  16977. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  16978. }
  16979. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  16980. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  16981. this._worldMatrix.copyFrom(this._localWorld);
  16982. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  16983. }
  16984. else {
  16985. if (this._transformToBoneReferal) {
  16986. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  16987. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  16988. }
  16989. else {
  16990. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  16991. }
  16992. }
  16993. this._markSyncedWithParent();
  16994. }
  16995. else {
  16996. this._worldMatrix.copyFrom(this._localWorld);
  16997. }
  16998. // Post multiply inverse of pivotMatrix
  16999. if (this._postMultiplyPivotMatrix) {
  17000. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  17001. }
  17002. // Normal matrix
  17003. if (this.scaling.isNonUniform) {
  17004. this._updateNonUniformScalingState(true);
  17005. }
  17006. else if (this.parent && this.parent._nonUniformScaling) {
  17007. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  17008. }
  17009. else {
  17010. this._updateNonUniformScalingState(false);
  17011. }
  17012. this._afterComputeWorldMatrix();
  17013. // Absolute position
  17014. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  17015. // Callbacks
  17016. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  17017. if (!this._poseMatrix) {
  17018. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  17019. }
  17020. // Cache the determinant
  17021. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  17022. return this._worldMatrix;
  17023. };
  17024. TransformNode.prototype._afterComputeWorldMatrix = function () {
  17025. };
  17026. /**
  17027. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  17028. * @param func: callback function to add
  17029. *
  17030. * Returns the TransformNode.
  17031. */
  17032. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  17033. this.onAfterWorldMatrixUpdateObservable.add(func);
  17034. return this;
  17035. };
  17036. /**
  17037. * Removes a registered callback function.
  17038. * Returns the TransformNode.
  17039. */
  17040. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  17041. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  17042. return this;
  17043. };
  17044. /**
  17045. * Clone the current transform node
  17046. * Returns the new transform node
  17047. * @param name Name of the new clone
  17048. * @param newParent New parent for the clone
  17049. * @param doNotCloneChildren Do not clone children hierarchy
  17050. */
  17051. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  17052. var _this = this;
  17053. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  17054. result.name = name;
  17055. result.id = name;
  17056. if (newParent) {
  17057. result.parent = newParent;
  17058. }
  17059. if (!doNotCloneChildren) {
  17060. // Children
  17061. var directDescendants = this.getDescendants(true);
  17062. for (var index = 0; index < directDescendants.length; index++) {
  17063. var child = directDescendants[index];
  17064. if (child.clone) {
  17065. child.clone(name + "." + child.name, result);
  17066. }
  17067. }
  17068. }
  17069. return result;
  17070. };
  17071. TransformNode.prototype.serialize = function (currentSerializationObject) {
  17072. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  17073. serializationObject.type = this.getClassName();
  17074. // Parent
  17075. if (this.parent) {
  17076. serializationObject.parentId = this.parent.id;
  17077. }
  17078. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  17079. serializationObject.tags = BABYLON.Tags.GetTags(this);
  17080. }
  17081. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  17082. serializationObject.isEnabled = this.isEnabled();
  17083. // Parent
  17084. if (this.parent) {
  17085. serializationObject.parentId = this.parent.id;
  17086. }
  17087. return serializationObject;
  17088. };
  17089. // Statics
  17090. /**
  17091. * Returns a new TransformNode object parsed from the source provided.
  17092. * The parameter `parsedMesh` is the source.
  17093. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  17094. */
  17095. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  17096. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  17097. if (BABYLON.Tags) {
  17098. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  17099. }
  17100. if (parsedTransformNode.localMatrix) {
  17101. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  17102. }
  17103. else if (parsedTransformNode.pivotMatrix) {
  17104. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  17105. }
  17106. transformNode.setEnabled(parsedTransformNode.isEnabled);
  17107. // Parent
  17108. if (parsedTransformNode.parentId) {
  17109. transformNode._waitingParentId = parsedTransformNode.parentId;
  17110. }
  17111. return transformNode;
  17112. };
  17113. /**
  17114. * Disposes the TransformNode.
  17115. * By default, all the children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  17116. * Returns nothing.
  17117. */
  17118. TransformNode.prototype.dispose = function (doNotRecurse) {
  17119. // Animations
  17120. this.getScene().stopAnimation(this);
  17121. // Remove from scene
  17122. this.getScene().removeTransformNode(this);
  17123. if (!doNotRecurse) {
  17124. // Children
  17125. var objects = this.getDescendants(true);
  17126. for (var index = 0; index < objects.length; index++) {
  17127. objects[index].dispose();
  17128. }
  17129. }
  17130. else {
  17131. var childMeshes = this.getChildMeshes(true);
  17132. for (index = 0; index < childMeshes.length; index++) {
  17133. var child = childMeshes[index];
  17134. child.parent = null;
  17135. child.computeWorldMatrix(true);
  17136. }
  17137. }
  17138. this.onAfterWorldMatrixUpdateObservable.clear();
  17139. _super.prototype.dispose.call(this);
  17140. };
  17141. // Statics
  17142. TransformNode.BILLBOARDMODE_NONE = 0;
  17143. TransformNode.BILLBOARDMODE_X = 1;
  17144. TransformNode.BILLBOARDMODE_Y = 2;
  17145. TransformNode.BILLBOARDMODE_Z = 4;
  17146. TransformNode.BILLBOARDMODE_ALL = 7;
  17147. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  17148. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  17149. __decorate([
  17150. BABYLON.serializeAsVector3()
  17151. ], TransformNode.prototype, "_rotation", void 0);
  17152. __decorate([
  17153. BABYLON.serializeAsQuaternion()
  17154. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  17155. __decorate([
  17156. BABYLON.serializeAsVector3()
  17157. ], TransformNode.prototype, "_scaling", void 0);
  17158. __decorate([
  17159. BABYLON.serialize()
  17160. ], TransformNode.prototype, "billboardMode", void 0);
  17161. __decorate([
  17162. BABYLON.serialize()
  17163. ], TransformNode.prototype, "scalingDeterminant", void 0);
  17164. __decorate([
  17165. BABYLON.serialize()
  17166. ], TransformNode.prototype, "infiniteDistance", void 0);
  17167. __decorate([
  17168. BABYLON.serializeAsVector3()
  17169. ], TransformNode.prototype, "position", void 0);
  17170. return TransformNode;
  17171. }(BABYLON.Node));
  17172. BABYLON.TransformNode = TransformNode;
  17173. })(BABYLON || (BABYLON = {}));
  17174. //# sourceMappingURL=babylon.transformNode.js.map
  17175. var BABYLON;
  17176. (function (BABYLON) {
  17177. var AbstractMesh = /** @class */ (function (_super) {
  17178. __extends(AbstractMesh, _super);
  17179. // Constructor
  17180. function AbstractMesh(name, scene) {
  17181. if (scene === void 0) { scene = null; }
  17182. var _this = _super.call(this, name, scene, false) || this;
  17183. _this._facetNb = 0; // facet number
  17184. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  17185. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  17186. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  17187. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  17188. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  17189. _this._subDiv = {
  17190. max: 1,
  17191. X: 1,
  17192. Y: 1,
  17193. Z: 1
  17194. };
  17195. _this._facetDepthSort = false; // is the facet depth sort to be computed
  17196. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  17197. // Events
  17198. /**
  17199. * An event triggered when this mesh collides with another one
  17200. * @type {BABYLON.Observable}
  17201. */
  17202. _this.onCollideObservable = new BABYLON.Observable();
  17203. /**
  17204. * An event triggered when the collision's position changes
  17205. * @type {BABYLON.Observable}
  17206. */
  17207. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  17208. /**
  17209. * An event triggered when material is changed
  17210. * @type {BABYLON.Observable}
  17211. */
  17212. _this.onMaterialChangedObservable = new BABYLON.Observable();
  17213. // Properties
  17214. _this.definedFacingForward = true; // orientation for POV movement & rotation
  17215. /**
  17216. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  17217. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  17218. * or
  17219. * 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.
  17220. * for more info check WebGl documentations
  17221. */
  17222. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  17223. /**
  17224. * 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:
  17225. * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  17226. * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  17227. * 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.
  17228. */
  17229. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  17230. /**
  17231. * 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.
  17232. * The default value is -1 which means don't break the query and wait till the result.
  17233. */
  17234. _this.occlusionRetryCount = -1;
  17235. _this._occlusionInternalRetryCounter = 0;
  17236. _this._isOccluded = false;
  17237. _this._isOcclusionQueryInProgress = false;
  17238. _this._visibility = 1.0;
  17239. _this.alphaIndex = Number.MAX_VALUE;
  17240. _this.isVisible = true;
  17241. _this.isPickable = true;
  17242. _this.showBoundingBox = false;
  17243. _this.showSubMeshesBoundingBox = false;
  17244. _this.isBlocker = false;
  17245. _this.enablePointerMoveEvents = false;
  17246. _this.renderingGroupId = 0;
  17247. _this._receiveShadows = false;
  17248. _this.renderOutline = false;
  17249. _this.outlineColor = BABYLON.Color3.Red();
  17250. _this.outlineWidth = 0.02;
  17251. _this.renderOverlay = false;
  17252. _this.overlayColor = BABYLON.Color3.Red();
  17253. _this.overlayAlpha = 0.5;
  17254. _this._hasVertexAlpha = false;
  17255. _this._useVertexColors = true;
  17256. _this._computeBonesUsingShaders = true;
  17257. _this._numBoneInfluencers = 4;
  17258. _this._applyFog = true;
  17259. _this.useOctreeForRenderingSelection = true;
  17260. _this.useOctreeForPicking = true;
  17261. _this.useOctreeForCollisions = true;
  17262. _this._layerMask = 0x0FFFFFFF;
  17263. /**
  17264. * True if the mesh must be rendered in any case.
  17265. */
  17266. _this.alwaysSelectAsActiveMesh = false;
  17267. /**
  17268. * This scene's action manager
  17269. * @type {BABYLON.ActionManager}
  17270. */
  17271. _this.actionManager = null;
  17272. // Physics
  17273. _this.physicsImpostor = null;
  17274. // Collisions
  17275. _this._checkCollisions = false;
  17276. _this._collisionMask = -1;
  17277. _this._collisionGroup = -1;
  17278. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  17279. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  17280. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  17281. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  17282. // Edges
  17283. _this.edgesWidth = 1;
  17284. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  17285. // Cache
  17286. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  17287. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  17288. _this._renderId = 0;
  17289. _this._intersectionsInProgress = new Array();
  17290. _this._unIndexed = false;
  17291. _this._lightSources = new Array();
  17292. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  17293. if (collidedMesh === void 0) { collidedMesh = null; }
  17294. //TODO move this to the collision coordinator!
  17295. if (_this.getScene().workerCollisions)
  17296. newPosition.multiplyInPlace(_this._collider._radius);
  17297. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  17298. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  17299. _this.position.addInPlace(_this._diffPositionForCollisions);
  17300. }
  17301. if (collidedMesh) {
  17302. _this.onCollideObservable.notifyObservers(collidedMesh);
  17303. }
  17304. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  17305. };
  17306. _this.getScene().addMesh(_this);
  17307. _this._resyncLightSources();
  17308. return _this;
  17309. }
  17310. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  17311. get: function () {
  17312. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  17313. },
  17314. enumerable: true,
  17315. configurable: true
  17316. });
  17317. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  17318. get: function () {
  17319. return BABYLON.TransformNode.BILLBOARDMODE_X;
  17320. },
  17321. enumerable: true,
  17322. configurable: true
  17323. });
  17324. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  17325. get: function () {
  17326. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  17327. },
  17328. enumerable: true,
  17329. configurable: true
  17330. });
  17331. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  17332. get: function () {
  17333. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  17334. },
  17335. enumerable: true,
  17336. configurable: true
  17337. });
  17338. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  17339. get: function () {
  17340. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  17341. },
  17342. enumerable: true,
  17343. configurable: true
  17344. });
  17345. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  17346. /**
  17347. * Read-only : the number of facets in the mesh
  17348. */
  17349. get: function () {
  17350. return this._facetNb;
  17351. },
  17352. enumerable: true,
  17353. configurable: true
  17354. });
  17355. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  17356. /**
  17357. * The number (integer) of subdivisions per axis in the partioning space
  17358. */
  17359. get: function () {
  17360. return this._partitioningSubdivisions;
  17361. },
  17362. set: function (nb) {
  17363. this._partitioningSubdivisions = nb;
  17364. },
  17365. enumerable: true,
  17366. configurable: true
  17367. });
  17368. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  17369. /**
  17370. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  17371. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  17372. */
  17373. get: function () {
  17374. return this._partitioningBBoxRatio;
  17375. },
  17376. set: function (ratio) {
  17377. this._partitioningBBoxRatio = ratio;
  17378. },
  17379. enumerable: true,
  17380. configurable: true
  17381. });
  17382. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  17383. /**
  17384. * Boolean : must the facet be depth sorted on next call to `updateFacetData()` ?
  17385. * Works only for updatable meshes.
  17386. * Doesn't work with multi-materials.
  17387. */
  17388. get: function () {
  17389. return this._facetDepthSort;
  17390. },
  17391. set: function (sort) {
  17392. this._facetDepthSort = sort;
  17393. },
  17394. enumerable: true,
  17395. configurable: true
  17396. });
  17397. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  17398. /**
  17399. * The location (Vector3) where the facet depth sort must be computed from.
  17400. * By default, the active camera position.
  17401. * Used only when facet depth sort is enabled.
  17402. */
  17403. get: function () {
  17404. return this._facetDepthSortFrom;
  17405. },
  17406. set: function (location) {
  17407. this._facetDepthSortFrom = location;
  17408. },
  17409. enumerable: true,
  17410. configurable: true
  17411. });
  17412. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  17413. /**
  17414. * Read-only boolean : is the feature facetData enabled ?
  17415. */
  17416. get: function () {
  17417. return this._facetDataEnabled;
  17418. },
  17419. enumerable: true,
  17420. configurable: true
  17421. });
  17422. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  17423. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  17424. return false;
  17425. }
  17426. this._markSubMeshesAsMiscDirty();
  17427. return true;
  17428. };
  17429. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  17430. set: function (callback) {
  17431. if (this._onCollideObserver) {
  17432. this.onCollideObservable.remove(this._onCollideObserver);
  17433. }
  17434. this._onCollideObserver = this.onCollideObservable.add(callback);
  17435. },
  17436. enumerable: true,
  17437. configurable: true
  17438. });
  17439. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  17440. set: function (callback) {
  17441. if (this._onCollisionPositionChangeObserver) {
  17442. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  17443. }
  17444. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  17445. },
  17446. enumerable: true,
  17447. configurable: true
  17448. });
  17449. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  17450. /**
  17451. * 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.
  17452. */
  17453. get: function () {
  17454. return this._isOccluded;
  17455. },
  17456. set: function (value) {
  17457. this._isOccluded = value;
  17458. },
  17459. enumerable: true,
  17460. configurable: true
  17461. });
  17462. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  17463. /**
  17464. * Flag to check the progress status of the query
  17465. */
  17466. get: function () {
  17467. return this._isOcclusionQueryInProgress;
  17468. },
  17469. enumerable: true,
  17470. configurable: true
  17471. });
  17472. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  17473. /**
  17474. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  17475. */
  17476. get: function () {
  17477. return this._visibility;
  17478. },
  17479. /**
  17480. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  17481. */
  17482. set: function (value) {
  17483. if (this._visibility === value) {
  17484. return;
  17485. }
  17486. this._visibility = value;
  17487. this._markSubMeshesAsMiscDirty();
  17488. },
  17489. enumerable: true,
  17490. configurable: true
  17491. });
  17492. Object.defineProperty(AbstractMesh.prototype, "material", {
  17493. get: function () {
  17494. return this._material;
  17495. },
  17496. set: function (value) {
  17497. if (this._material === value) {
  17498. return;
  17499. }
  17500. this._material = value;
  17501. if (this.onMaterialChangedObservable.hasObservers) {
  17502. this.onMaterialChangedObservable.notifyObservers(this);
  17503. }
  17504. if (!this.subMeshes) {
  17505. return;
  17506. }
  17507. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17508. var subMesh = _a[_i];
  17509. subMesh.setEffect(null);
  17510. }
  17511. },
  17512. enumerable: true,
  17513. configurable: true
  17514. });
  17515. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  17516. get: function () {
  17517. return this._receiveShadows;
  17518. },
  17519. set: function (value) {
  17520. if (this._receiveShadows === value) {
  17521. return;
  17522. }
  17523. this._receiveShadows = value;
  17524. this._markSubMeshesAsLightDirty();
  17525. },
  17526. enumerable: true,
  17527. configurable: true
  17528. });
  17529. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  17530. get: function () {
  17531. return this._hasVertexAlpha;
  17532. },
  17533. set: function (value) {
  17534. if (this._hasVertexAlpha === value) {
  17535. return;
  17536. }
  17537. this._hasVertexAlpha = value;
  17538. this._markSubMeshesAsAttributesDirty();
  17539. this._markSubMeshesAsMiscDirty();
  17540. },
  17541. enumerable: true,
  17542. configurable: true
  17543. });
  17544. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  17545. get: function () {
  17546. return this._useVertexColors;
  17547. },
  17548. set: function (value) {
  17549. if (this._useVertexColors === value) {
  17550. return;
  17551. }
  17552. this._useVertexColors = value;
  17553. this._markSubMeshesAsAttributesDirty();
  17554. },
  17555. enumerable: true,
  17556. configurable: true
  17557. });
  17558. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  17559. get: function () {
  17560. return this._computeBonesUsingShaders;
  17561. },
  17562. set: function (value) {
  17563. if (this._computeBonesUsingShaders === value) {
  17564. return;
  17565. }
  17566. this._computeBonesUsingShaders = value;
  17567. this._markSubMeshesAsAttributesDirty();
  17568. },
  17569. enumerable: true,
  17570. configurable: true
  17571. });
  17572. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  17573. get: function () {
  17574. return this._numBoneInfluencers;
  17575. },
  17576. set: function (value) {
  17577. if (this._numBoneInfluencers === value) {
  17578. return;
  17579. }
  17580. this._numBoneInfluencers = value;
  17581. this._markSubMeshesAsAttributesDirty();
  17582. },
  17583. enumerable: true,
  17584. configurable: true
  17585. });
  17586. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  17587. get: function () {
  17588. return this._applyFog;
  17589. },
  17590. set: function (value) {
  17591. if (this._applyFog === value) {
  17592. return;
  17593. }
  17594. this._applyFog = value;
  17595. this._markSubMeshesAsMiscDirty();
  17596. },
  17597. enumerable: true,
  17598. configurable: true
  17599. });
  17600. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  17601. get: function () {
  17602. return this._layerMask;
  17603. },
  17604. set: function (value) {
  17605. if (value === this._layerMask) {
  17606. return;
  17607. }
  17608. this._layerMask = value;
  17609. this._resyncLightSources();
  17610. },
  17611. enumerable: true,
  17612. configurable: true
  17613. });
  17614. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  17615. get: function () {
  17616. return this._collisionMask;
  17617. },
  17618. set: function (mask) {
  17619. this._collisionMask = !isNaN(mask) ? mask : -1;
  17620. },
  17621. enumerable: true,
  17622. configurable: true
  17623. });
  17624. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  17625. get: function () {
  17626. return this._collisionGroup;
  17627. },
  17628. set: function (mask) {
  17629. this._collisionGroup = !isNaN(mask) ? mask : -1;
  17630. },
  17631. enumerable: true,
  17632. configurable: true
  17633. });
  17634. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  17635. get: function () {
  17636. return null;
  17637. },
  17638. enumerable: true,
  17639. configurable: true
  17640. });
  17641. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  17642. get: function () {
  17643. return this._skeleton;
  17644. },
  17645. set: function (value) {
  17646. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  17647. this._skeleton._unregisterMeshWithPoseMatrix(this);
  17648. }
  17649. if (value && value.needInitialSkinMatrix) {
  17650. value._registerMeshWithPoseMatrix(this);
  17651. }
  17652. this._skeleton = value;
  17653. if (!this._skeleton) {
  17654. this._bonesTransformMatrices = null;
  17655. }
  17656. this._markSubMeshesAsAttributesDirty();
  17657. },
  17658. enumerable: true,
  17659. configurable: true
  17660. });
  17661. /**
  17662. * Returns the string "AbstractMesh"
  17663. */
  17664. AbstractMesh.prototype.getClassName = function () {
  17665. return "AbstractMesh";
  17666. };
  17667. /**
  17668. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  17669. */
  17670. AbstractMesh.prototype.toString = function (fullDetails) {
  17671. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  17672. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  17673. if (this._skeleton) {
  17674. ret += ", skeleton: " + this._skeleton.name;
  17675. }
  17676. if (fullDetails) {
  17677. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  17678. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  17679. }
  17680. return ret;
  17681. };
  17682. AbstractMesh.prototype._rebuild = function () {
  17683. if (this._occlusionQuery) {
  17684. this._occlusionQuery = null;
  17685. }
  17686. if (this._edgesRenderer) {
  17687. this._edgesRenderer._rebuild();
  17688. }
  17689. if (!this.subMeshes) {
  17690. return;
  17691. }
  17692. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17693. var subMesh = _a[_i];
  17694. subMesh._rebuild();
  17695. }
  17696. };
  17697. AbstractMesh.prototype._resyncLightSources = function () {
  17698. this._lightSources.length = 0;
  17699. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  17700. var light = _a[_i];
  17701. if (!light.isEnabled()) {
  17702. continue;
  17703. }
  17704. if (light.canAffectMesh(this)) {
  17705. this._lightSources.push(light);
  17706. }
  17707. }
  17708. this._markSubMeshesAsLightDirty();
  17709. };
  17710. AbstractMesh.prototype._resyncLighSource = function (light) {
  17711. var isIn = light.isEnabled() && light.canAffectMesh(this);
  17712. var index = this._lightSources.indexOf(light);
  17713. if (index === -1) {
  17714. if (!isIn) {
  17715. return;
  17716. }
  17717. this._lightSources.push(light);
  17718. }
  17719. else {
  17720. if (isIn) {
  17721. return;
  17722. }
  17723. this._lightSources.splice(index, 1);
  17724. }
  17725. this._markSubMeshesAsLightDirty();
  17726. };
  17727. AbstractMesh.prototype._removeLightSource = function (light) {
  17728. var index = this._lightSources.indexOf(light);
  17729. if (index === -1) {
  17730. return;
  17731. }
  17732. this._lightSources.splice(index, 1);
  17733. this._markSubMeshesAsLightDirty();
  17734. };
  17735. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  17736. if (!this.subMeshes) {
  17737. return;
  17738. }
  17739. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17740. var subMesh = _a[_i];
  17741. if (subMesh._materialDefines) {
  17742. func(subMesh._materialDefines);
  17743. }
  17744. }
  17745. };
  17746. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  17747. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  17748. };
  17749. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  17750. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  17751. };
  17752. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  17753. if (!this.subMeshes) {
  17754. return;
  17755. }
  17756. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17757. var subMesh = _a[_i];
  17758. var material = subMesh.getMaterial();
  17759. if (material) {
  17760. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  17761. }
  17762. }
  17763. };
  17764. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  17765. /**
  17766. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  17767. * Default : (1.0, 1.0, 1.0)
  17768. */
  17769. get: function () {
  17770. return this._scaling;
  17771. },
  17772. /**
  17773. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  17774. * Default : (1.0, 1.0, 1.0)
  17775. */
  17776. set: function (newScaling) {
  17777. this._scaling = newScaling;
  17778. if (this.physicsImpostor) {
  17779. this.physicsImpostor.forceUpdate();
  17780. }
  17781. },
  17782. enumerable: true,
  17783. configurable: true
  17784. });
  17785. // Methods
  17786. /**
  17787. * Disables the mesh edger rendering mode.
  17788. * Returns the AbstractMesh.
  17789. */
  17790. AbstractMesh.prototype.disableEdgesRendering = function () {
  17791. if (this._edgesRenderer) {
  17792. this._edgesRenderer.dispose();
  17793. this._edgesRenderer = null;
  17794. }
  17795. return this;
  17796. };
  17797. /**
  17798. * Enables the edge rendering mode on the mesh.
  17799. * This mode makes the mesh edges visible.
  17800. * Returns the AbstractMesh.
  17801. */
  17802. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  17803. if (epsilon === void 0) { epsilon = 0.95; }
  17804. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  17805. this.disableEdgesRendering();
  17806. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  17807. return this;
  17808. };
  17809. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  17810. /**
  17811. * Returns true if the mesh is blocked. Used by the class Mesh.
  17812. * Returns the boolean `false` by default.
  17813. */
  17814. get: function () {
  17815. return false;
  17816. },
  17817. enumerable: true,
  17818. configurable: true
  17819. });
  17820. /**
  17821. * Returns the mesh itself by default, used by the class Mesh.
  17822. * Returned type : AbstractMesh
  17823. */
  17824. AbstractMesh.prototype.getLOD = function (camera) {
  17825. return this;
  17826. };
  17827. /**
  17828. * Returns 0 by default, used by the class Mesh.
  17829. * Returns an integer.
  17830. */
  17831. AbstractMesh.prototype.getTotalVertices = function () {
  17832. return 0;
  17833. };
  17834. /**
  17835. * Returns null by default, used by the class Mesh.
  17836. * Returned type : integer array
  17837. */
  17838. AbstractMesh.prototype.getIndices = function () {
  17839. return null;
  17840. };
  17841. /**
  17842. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  17843. * Returned type : float array or Float32Array
  17844. */
  17845. AbstractMesh.prototype.getVerticesData = function (kind) {
  17846. return null;
  17847. };
  17848. /**
  17849. * Sets the vertex data of the mesh geometry for the requested `kind`.
  17850. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  17851. * The `data` are either a numeric array either a Float32Array.
  17852. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  17853. * 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).
  17854. * Note that a new underlying VertexBuffer object is created each call.
  17855. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  17856. *
  17857. * Possible `kind` values :
  17858. * - BABYLON.VertexBuffer.PositionKind
  17859. * - BABYLON.VertexBuffer.UVKind
  17860. * - BABYLON.VertexBuffer.UV2Kind
  17861. * - BABYLON.VertexBuffer.UV3Kind
  17862. * - BABYLON.VertexBuffer.UV4Kind
  17863. * - BABYLON.VertexBuffer.UV5Kind
  17864. * - BABYLON.VertexBuffer.UV6Kind
  17865. * - BABYLON.VertexBuffer.ColorKind
  17866. * - BABYLON.VertexBuffer.MatricesIndicesKind
  17867. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  17868. * - BABYLON.VertexBuffer.MatricesWeightsKind
  17869. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  17870. *
  17871. * Returns the Mesh.
  17872. */
  17873. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  17874. return this;
  17875. };
  17876. /**
  17877. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  17878. * If the mesh has no geometry, it is simply returned as it is.
  17879. * The `data` are either a numeric array either a Float32Array.
  17880. * No new underlying VertexBuffer object is created.
  17881. * 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.
  17882. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  17883. *
  17884. * Possible `kind` values :
  17885. * - BABYLON.VertexBuffer.PositionKind
  17886. * - BABYLON.VertexBuffer.UVKind
  17887. * - BABYLON.VertexBuffer.UV2Kind
  17888. * - BABYLON.VertexBuffer.UV3Kind
  17889. * - BABYLON.VertexBuffer.UV4Kind
  17890. * - BABYLON.VertexBuffer.UV5Kind
  17891. * - BABYLON.VertexBuffer.UV6Kind
  17892. * - BABYLON.VertexBuffer.ColorKind
  17893. * - BABYLON.VertexBuffer.MatricesIndicesKind
  17894. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  17895. * - BABYLON.VertexBuffer.MatricesWeightsKind
  17896. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  17897. *
  17898. * Returns the Mesh.
  17899. */
  17900. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  17901. return this;
  17902. };
  17903. /**
  17904. * Sets the mesh indices.
  17905. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  17906. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  17907. * This method creates a new index buffer each call.
  17908. * Returns the Mesh.
  17909. */
  17910. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  17911. return this;
  17912. };
  17913. /** Returns false by default, used by the class Mesh.
  17914. * Returns a boolean
  17915. */
  17916. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  17917. return false;
  17918. };
  17919. /**
  17920. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  17921. * Returns a BoundingInfo
  17922. */
  17923. AbstractMesh.prototype.getBoundingInfo = function () {
  17924. if (this._masterMesh) {
  17925. return this._masterMesh.getBoundingInfo();
  17926. }
  17927. if (!this._boundingInfo) {
  17928. // this._boundingInfo is being created here
  17929. this._updateBoundingInfo();
  17930. }
  17931. // cannot be null.
  17932. return this._boundingInfo;
  17933. };
  17934. /**
  17935. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units).
  17936. * @param includeDescendants Take the hierarchy's bounding box instead of the mesh's bounding box.
  17937. */
  17938. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  17939. if (includeDescendants === void 0) { includeDescendants = true; }
  17940. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  17941. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  17942. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  17943. if (maxDimension === 0) {
  17944. return this;
  17945. }
  17946. var scale = 1 / maxDimension;
  17947. this.scaling.scaleInPlace(scale);
  17948. return this;
  17949. };
  17950. /**
  17951. * Sets a mesh new object BoundingInfo.
  17952. * Returns the AbstractMesh.
  17953. */
  17954. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  17955. this._boundingInfo = boundingInfo;
  17956. return this;
  17957. };
  17958. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  17959. get: function () {
  17960. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  17961. },
  17962. enumerable: true,
  17963. configurable: true
  17964. });
  17965. AbstractMesh.prototype._preActivate = function () {
  17966. };
  17967. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  17968. };
  17969. AbstractMesh.prototype._activate = function (renderId) {
  17970. this._renderId = renderId;
  17971. };
  17972. /**
  17973. * Returns the latest update of the World matrix
  17974. * Returns a Matrix.
  17975. */
  17976. AbstractMesh.prototype.getWorldMatrix = function () {
  17977. if (this._masterMesh) {
  17978. return this._masterMesh.getWorldMatrix();
  17979. }
  17980. return _super.prototype.getWorldMatrix.call(this);
  17981. };
  17982. /**
  17983. * Returns the latest update of the World matrix determinant.
  17984. */
  17985. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  17986. if (this._masterMesh) {
  17987. return this._masterMesh._getWorldMatrixDeterminant();
  17988. }
  17989. return _super.prototype._getWorldMatrixDeterminant.call(this);
  17990. };
  17991. // ================================== Point of View Movement =================================
  17992. /**
  17993. * Perform relative position change from the point of view of behind the front of the mesh.
  17994. * This is performed taking into account the meshes current rotation, so you do not have to care.
  17995. * Supports definition of mesh facing forward or backward.
  17996. * @param {number} amountRight
  17997. * @param {number} amountUp
  17998. * @param {number} amountForward
  17999. *
  18000. * Returns the AbstractMesh.
  18001. */
  18002. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  18003. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  18004. return this;
  18005. };
  18006. /**
  18007. * Calculate relative position change from the point of view of behind the front of the mesh.
  18008. * This is performed taking into account the meshes current rotation, so you do not have to care.
  18009. * Supports definition of mesh facing forward or backward.
  18010. * @param {number} amountRight
  18011. * @param {number} amountUp
  18012. * @param {number} amountForward
  18013. *
  18014. * Returns a new Vector3.
  18015. */
  18016. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  18017. var rotMatrix = new BABYLON.Matrix();
  18018. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  18019. rotQuaternion.toRotationMatrix(rotMatrix);
  18020. var translationDelta = BABYLON.Vector3.Zero();
  18021. var defForwardMult = this.definedFacingForward ? -1 : 1;
  18022. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  18023. return translationDelta;
  18024. };
  18025. // ================================== Point of View Rotation =================================
  18026. /**
  18027. * Perform relative rotation change from the point of view of behind the front of the mesh.
  18028. * Supports definition of mesh facing forward or backward.
  18029. * @param {number} flipBack
  18030. * @param {number} twirlClockwise
  18031. * @param {number} tiltRight
  18032. *
  18033. * Returns the AbstractMesh.
  18034. */
  18035. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  18036. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  18037. return this;
  18038. };
  18039. /**
  18040. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  18041. * Supports definition of mesh facing forward or backward.
  18042. * @param {number} flipBack
  18043. * @param {number} twirlClockwise
  18044. * @param {number} tiltRight
  18045. *
  18046. * Returns a new Vector3.
  18047. */
  18048. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  18049. var defForwardMult = this.definedFacingForward ? 1 : -1;
  18050. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  18051. };
  18052. /**
  18053. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  18054. * @param includeDescendants Include bounding info from descendants as well (true by default).
  18055. */
  18056. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants) {
  18057. if (includeDescendants === void 0) { includeDescendants = true; }
  18058. this.computeWorldMatrix(true);
  18059. var min;
  18060. var max;
  18061. var boundingInfo = this.getBoundingInfo();
  18062. if (!this.subMeshes) {
  18063. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  18064. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  18065. }
  18066. else {
  18067. min = boundingInfo.boundingBox.minimumWorld;
  18068. max = boundingInfo.boundingBox.maximumWorld;
  18069. }
  18070. if (includeDescendants) {
  18071. var descendants = this.getDescendants(false);
  18072. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  18073. var descendant = descendants_1[_i];
  18074. var childMesh = descendant;
  18075. childMesh.computeWorldMatrix(true);
  18076. //make sure we have the needed params to get mix and max
  18077. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  18078. continue;
  18079. }
  18080. var childBoundingInfo = childMesh.getBoundingInfo();
  18081. var boundingBox = childBoundingInfo.boundingBox;
  18082. var minBox = boundingBox.minimumWorld;
  18083. var maxBox = boundingBox.maximumWorld;
  18084. BABYLON.Tools.CheckExtends(minBox, min, max);
  18085. BABYLON.Tools.CheckExtends(maxBox, min, max);
  18086. }
  18087. }
  18088. return {
  18089. min: min,
  18090. max: max
  18091. };
  18092. };
  18093. /**
  18094. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  18095. * Returns the AbstractMesh.
  18096. */
  18097. AbstractMesh.prototype._updateBoundingInfo = function () {
  18098. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  18099. this._boundingInfo.update(this.worldMatrixFromCache);
  18100. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  18101. return this;
  18102. };
  18103. /**
  18104. * Update a mesh's children BoundingInfo objects only.
  18105. * Returns the AbstractMesh.
  18106. */
  18107. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  18108. if (!this.subMeshes) {
  18109. return this;
  18110. }
  18111. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  18112. var subMesh = this.subMeshes[subIndex];
  18113. if (!subMesh.IsGlobal) {
  18114. subMesh.updateBoundingInfo(matrix);
  18115. }
  18116. }
  18117. return this;
  18118. };
  18119. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  18120. // Bounding info
  18121. this._updateBoundingInfo();
  18122. };
  18123. /**
  18124. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  18125. * A mesh is in the frustum if its bounding box intersects the frustum.
  18126. * Boolean returned.
  18127. */
  18128. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  18129. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  18130. };
  18131. /**
  18132. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  18133. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  18134. * Boolean returned.
  18135. */
  18136. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18137. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  18138. ;
  18139. };
  18140. /**
  18141. * True if the mesh intersects another mesh or a SolidParticle object.
  18142. * 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)
  18143. * includeDescendants can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  18144. * Returns a boolean.
  18145. */
  18146. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  18147. if (precise === void 0) { precise = false; }
  18148. if (!this._boundingInfo || !mesh._boundingInfo) {
  18149. return false;
  18150. }
  18151. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  18152. return true;
  18153. }
  18154. if (includeDescendants) {
  18155. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  18156. var child = _a[_i];
  18157. if (child.intersectsMesh(mesh, precise, true)) {
  18158. return true;
  18159. }
  18160. }
  18161. }
  18162. return false;
  18163. };
  18164. /**
  18165. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  18166. * Returns a boolean.
  18167. */
  18168. AbstractMesh.prototype.intersectsPoint = function (point) {
  18169. if (!this._boundingInfo) {
  18170. return false;
  18171. }
  18172. return this._boundingInfo.intersectsPoint(point);
  18173. };
  18174. AbstractMesh.prototype.getPhysicsImpostor = function () {
  18175. return this.physicsImpostor;
  18176. };
  18177. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  18178. if (camera === void 0) { camera = null; }
  18179. if (!camera) {
  18180. camera = this.getScene().activeCamera;
  18181. }
  18182. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  18183. };
  18184. /**
  18185. * Returns the distance from the mesh to the active camera.
  18186. * Returns a float.
  18187. */
  18188. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  18189. if (camera === void 0) { camera = null; }
  18190. if (!camera) {
  18191. camera = this.getScene().activeCamera;
  18192. }
  18193. return this.absolutePosition.subtract(camera.position).length();
  18194. };
  18195. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  18196. if (!this.physicsImpostor) {
  18197. return this;
  18198. }
  18199. this.physicsImpostor.applyImpulse(force, contactPoint);
  18200. return this;
  18201. };
  18202. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  18203. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  18204. return this;
  18205. }
  18206. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  18207. mainPivot: pivot1,
  18208. connectedPivot: pivot2,
  18209. nativeParams: options
  18210. });
  18211. return this;
  18212. };
  18213. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  18214. // Collisions
  18215. /**
  18216. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  18217. * Default `false`.
  18218. */
  18219. get: function () {
  18220. return this._checkCollisions;
  18221. },
  18222. set: function (collisionEnabled) {
  18223. this._checkCollisions = collisionEnabled;
  18224. if (this.getScene().workerCollisions) {
  18225. this.getScene().collisionCoordinator.onMeshUpdated(this);
  18226. }
  18227. },
  18228. enumerable: true,
  18229. configurable: true
  18230. });
  18231. Object.defineProperty(AbstractMesh.prototype, "collider", {
  18232. /**
  18233. * Gets Collider object used to compute collisions (not physics)
  18234. */
  18235. get: function () {
  18236. return this._collider;
  18237. },
  18238. enumerable: true,
  18239. configurable: true
  18240. });
  18241. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  18242. var globalPosition = this.getAbsolutePosition();
  18243. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  18244. if (!this._collider) {
  18245. this._collider = new BABYLON.Collider();
  18246. }
  18247. this._collider._radius = this.ellipsoid;
  18248. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  18249. return this;
  18250. };
  18251. // Submeshes octree
  18252. /**
  18253. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  18254. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  18255. * Returns an Octree of submeshes.
  18256. */
  18257. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  18258. if (maxCapacity === void 0) { maxCapacity = 64; }
  18259. if (maxDepth === void 0) { maxDepth = 2; }
  18260. if (!this._submeshesOctree) {
  18261. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  18262. }
  18263. this.computeWorldMatrix(true);
  18264. var boundingInfo = this.getBoundingInfo();
  18265. // Update octree
  18266. var bbox = boundingInfo.boundingBox;
  18267. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  18268. return this._submeshesOctree;
  18269. };
  18270. // Collisions
  18271. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  18272. this._generatePointsArray();
  18273. if (!this._positions) {
  18274. return this;
  18275. }
  18276. // Transformation
  18277. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  18278. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  18279. subMesh._lastColliderWorldVertices = [];
  18280. subMesh._trianglePlanes = [];
  18281. var start = subMesh.verticesStart;
  18282. var end = (subMesh.verticesStart + subMesh.verticesCount);
  18283. for (var i = start; i < end; i++) {
  18284. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  18285. }
  18286. }
  18287. // Collide
  18288. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  18289. if (collider.collisionFound) {
  18290. collider.collidedMesh = this;
  18291. }
  18292. return this;
  18293. };
  18294. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  18295. var subMeshes;
  18296. var len;
  18297. // Octrees
  18298. if (this._submeshesOctree && this.useOctreeForCollisions) {
  18299. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  18300. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  18301. len = intersections.length;
  18302. subMeshes = intersections.data;
  18303. }
  18304. else {
  18305. subMeshes = this.subMeshes;
  18306. len = subMeshes.length;
  18307. }
  18308. for (var index = 0; index < len; index++) {
  18309. var subMesh = subMeshes[index];
  18310. // Bounding test
  18311. if (len > 1 && !subMesh._checkCollision(collider))
  18312. continue;
  18313. this._collideForSubMesh(subMesh, transformMatrix, collider);
  18314. }
  18315. return this;
  18316. };
  18317. AbstractMesh.prototype._checkCollision = function (collider) {
  18318. // Bounding box test
  18319. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  18320. return this;
  18321. // Transformation matrix
  18322. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  18323. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  18324. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  18325. return this;
  18326. };
  18327. // Picking
  18328. AbstractMesh.prototype._generatePointsArray = function () {
  18329. return false;
  18330. };
  18331. /**
  18332. * Checks if the passed Ray intersects with the mesh.
  18333. * Returns an object PickingInfo.
  18334. */
  18335. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  18336. var pickingInfo = new BABYLON.PickingInfo();
  18337. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  18338. return pickingInfo;
  18339. }
  18340. if (!this._generatePointsArray()) {
  18341. return pickingInfo;
  18342. }
  18343. var intersectInfo = null;
  18344. // Octrees
  18345. var subMeshes;
  18346. var len;
  18347. if (this._submeshesOctree && this.useOctreeForPicking) {
  18348. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  18349. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  18350. len = intersections.length;
  18351. subMeshes = intersections.data;
  18352. }
  18353. else {
  18354. subMeshes = this.subMeshes;
  18355. len = subMeshes.length;
  18356. }
  18357. for (var index = 0; index < len; index++) {
  18358. var subMesh = subMeshes[index];
  18359. // Bounding test
  18360. if (len > 1 && !subMesh.canIntersects(ray))
  18361. continue;
  18362. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  18363. if (currentIntersectInfo) {
  18364. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  18365. intersectInfo = currentIntersectInfo;
  18366. intersectInfo.subMeshId = index;
  18367. if (fastCheck) {
  18368. break;
  18369. }
  18370. }
  18371. }
  18372. }
  18373. if (intersectInfo) {
  18374. // Get picked point
  18375. var world = this.getWorldMatrix();
  18376. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  18377. var direction = ray.direction.clone();
  18378. direction = direction.scale(intersectInfo.distance);
  18379. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  18380. var pickedPoint = worldOrigin.add(worldDirection);
  18381. // Return result
  18382. pickingInfo.hit = true;
  18383. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  18384. pickingInfo.pickedPoint = pickedPoint;
  18385. pickingInfo.pickedMesh = this;
  18386. pickingInfo.bu = intersectInfo.bu || 0;
  18387. pickingInfo.bv = intersectInfo.bv || 0;
  18388. pickingInfo.faceId = intersectInfo.faceId;
  18389. pickingInfo.subMeshId = intersectInfo.subMeshId;
  18390. return pickingInfo;
  18391. }
  18392. return pickingInfo;
  18393. };
  18394. /**
  18395. * Clones the mesh, used by the class Mesh.
  18396. * Just returns `null` for an AbstractMesh.
  18397. */
  18398. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  18399. return null;
  18400. };
  18401. /**
  18402. * Disposes all the mesh submeshes.
  18403. * Returns the AbstractMesh.
  18404. */
  18405. AbstractMesh.prototype.releaseSubMeshes = function () {
  18406. if (this.subMeshes) {
  18407. while (this.subMeshes.length) {
  18408. this.subMeshes[0].dispose();
  18409. }
  18410. }
  18411. else {
  18412. this.subMeshes = new Array();
  18413. }
  18414. return this;
  18415. };
  18416. /**
  18417. * Disposes the AbstractMesh.
  18418. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  18419. * Returns nothing.
  18420. */
  18421. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  18422. var _this = this;
  18423. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  18424. var index;
  18425. // Action manager
  18426. if (this.actionManager !== undefined && this.actionManager !== null) {
  18427. this.actionManager.dispose();
  18428. this.actionManager = null;
  18429. }
  18430. // Skeleton
  18431. this.skeleton = null;
  18432. // Physics
  18433. if (this.physicsImpostor) {
  18434. this.physicsImpostor.dispose();
  18435. }
  18436. // Intersections in progress
  18437. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  18438. var other = this._intersectionsInProgress[index];
  18439. var pos = other._intersectionsInProgress.indexOf(this);
  18440. other._intersectionsInProgress.splice(pos, 1);
  18441. }
  18442. this._intersectionsInProgress = [];
  18443. // Lights
  18444. var lights = this.getScene().lights;
  18445. lights.forEach(function (light) {
  18446. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  18447. if (meshIndex !== -1) {
  18448. light.includedOnlyMeshes.splice(meshIndex, 1);
  18449. }
  18450. meshIndex = light.excludedMeshes.indexOf(_this);
  18451. if (meshIndex !== -1) {
  18452. light.excludedMeshes.splice(meshIndex, 1);
  18453. }
  18454. // Shadow generators
  18455. var generator = light.getShadowGenerator();
  18456. if (generator) {
  18457. var shadowMap = generator.getShadowMap();
  18458. if (shadowMap && shadowMap.renderList) {
  18459. meshIndex = shadowMap.renderList.indexOf(_this);
  18460. if (meshIndex !== -1) {
  18461. shadowMap.renderList.splice(meshIndex, 1);
  18462. }
  18463. }
  18464. }
  18465. });
  18466. // Edges
  18467. if (this._edgesRenderer) {
  18468. this._edgesRenderer.dispose();
  18469. this._edgesRenderer = null;
  18470. }
  18471. // SubMeshes
  18472. if (this.getClassName() !== "InstancedMesh") {
  18473. this.releaseSubMeshes();
  18474. }
  18475. // Octree
  18476. var sceneOctree = this.getScene().selectionOctree;
  18477. if (sceneOctree !== undefined && sceneOctree !== null) {
  18478. var index = sceneOctree.dynamicContent.indexOf(this);
  18479. if (index !== -1) {
  18480. sceneOctree.dynamicContent.splice(index, 1);
  18481. }
  18482. }
  18483. // Query
  18484. var engine = this.getScene().getEngine();
  18485. if (this._occlusionQuery) {
  18486. this._isOcclusionQueryInProgress = false;
  18487. engine.deleteQuery(this._occlusionQuery);
  18488. this._occlusionQuery = null;
  18489. }
  18490. // Engine
  18491. engine.wipeCaches();
  18492. // Remove from scene
  18493. this.getScene().removeMesh(this);
  18494. if (disposeMaterialAndTextures) {
  18495. if (this.material) {
  18496. this.material.dispose(false, true);
  18497. }
  18498. }
  18499. if (!doNotRecurse) {
  18500. // Particles
  18501. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  18502. if (this.getScene().particleSystems[index].emitter === this) {
  18503. this.getScene().particleSystems[index].dispose();
  18504. index--;
  18505. }
  18506. }
  18507. }
  18508. // facet data
  18509. if (this._facetDataEnabled) {
  18510. this.disableFacetData();
  18511. }
  18512. this.onAfterWorldMatrixUpdateObservable.clear();
  18513. this.onCollideObservable.clear();
  18514. this.onCollisionPositionChangeObservable.clear();
  18515. _super.prototype.dispose.call(this, doNotRecurse);
  18516. };
  18517. /**
  18518. * Adds the passed mesh as a child to the current mesh.
  18519. * Returns the AbstractMesh.
  18520. */
  18521. AbstractMesh.prototype.addChild = function (mesh) {
  18522. mesh.setParent(this);
  18523. return this;
  18524. };
  18525. /**
  18526. * Removes the passed mesh from the current mesh children list.
  18527. * Returns the AbstractMesh.
  18528. */
  18529. AbstractMesh.prototype.removeChild = function (mesh) {
  18530. mesh.setParent(null);
  18531. return this;
  18532. };
  18533. // Facet data
  18534. /**
  18535. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  18536. * Returns the AbstractMesh.
  18537. */
  18538. AbstractMesh.prototype._initFacetData = function () {
  18539. if (!this._facetNormals) {
  18540. this._facetNormals = new Array();
  18541. }
  18542. if (!this._facetPositions) {
  18543. this._facetPositions = new Array();
  18544. }
  18545. if (!this._facetPartitioning) {
  18546. this._facetPartitioning = new Array();
  18547. }
  18548. this._facetNb = (this.getIndices().length / 3) | 0;
  18549. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  18550. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  18551. for (var f = 0; f < this._facetNb; f++) {
  18552. this._facetNormals[f] = BABYLON.Vector3.Zero();
  18553. this._facetPositions[f] = BABYLON.Vector3.Zero();
  18554. }
  18555. this._facetDataEnabled = true;
  18556. return this;
  18557. };
  18558. /**
  18559. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  18560. * This method can be called within the render loop.
  18561. * 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.
  18562. * Returns the AbstractMesh.
  18563. */
  18564. AbstractMesh.prototype.updateFacetData = function () {
  18565. if (!this._facetDataEnabled) {
  18566. this._initFacetData();
  18567. }
  18568. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18569. var indices = this.getIndices();
  18570. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18571. var bInfo = this.getBoundingInfo();
  18572. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  18573. // init arrays, matrix and sort function on first call
  18574. this._facetDepthSortEnabled = true;
  18575. if (indices instanceof Uint16Array) {
  18576. this._depthSortedIndices = new Uint16Array(indices);
  18577. }
  18578. else if (indices instanceof Uint32Array) {
  18579. this._depthSortedIndices = new Uint32Array(indices);
  18580. }
  18581. else {
  18582. var needs32bits = false;
  18583. for (var i = 0; i < indices.length; i++) {
  18584. if (indices[i] > 65535) {
  18585. needs32bits = true;
  18586. break;
  18587. }
  18588. }
  18589. if (needs32bits) {
  18590. this._depthSortedIndices = new Uint32Array(indices);
  18591. }
  18592. else {
  18593. this._depthSortedIndices = new Uint16Array(indices);
  18594. }
  18595. }
  18596. this._facetDepthSortFunction = function (f1, f2) {
  18597. return (f2.sqDistance - f1.sqDistance);
  18598. };
  18599. if (!this._facetDepthSortFrom) {
  18600. var camera = this.getScene().activeCamera;
  18601. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  18602. }
  18603. this._depthSortedFacets = [];
  18604. for (var f = 0; f < this._facetNb; f++) {
  18605. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  18606. this._depthSortedFacets.push(depthSortedFacet);
  18607. }
  18608. this._invertedMatrix = BABYLON.Matrix.Identity();
  18609. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  18610. }
  18611. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  18612. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  18613. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  18614. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  18615. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  18616. this._subDiv.max = this._partitioningSubdivisions;
  18617. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  18618. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  18619. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  18620. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  18621. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  18622. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  18623. // set the parameters for ComputeNormals()
  18624. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  18625. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  18626. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  18627. this._facetParameters.bInfo = bInfo;
  18628. this._facetParameters.bbSize = this._bbSize;
  18629. this._facetParameters.subDiv = this._subDiv;
  18630. this._facetParameters.ratio = this.partitioningBBoxRatio;
  18631. this._facetParameters.depthSort = this._facetDepthSort;
  18632. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  18633. this.computeWorldMatrix(true);
  18634. this._worldMatrix.invertToRef(this._invertedMatrix);
  18635. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  18636. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  18637. }
  18638. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  18639. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  18640. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  18641. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  18642. var l = (this._depthSortedIndices.length / 3) | 0;
  18643. for (var f = 0; f < l; f++) {
  18644. var sind = this._depthSortedFacets[f].ind;
  18645. this._depthSortedIndices[f * 3] = indices[sind];
  18646. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  18647. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  18648. }
  18649. this.updateIndices(this._depthSortedIndices);
  18650. }
  18651. return this;
  18652. };
  18653. /**
  18654. * Returns the facetLocalNormals array.
  18655. * The normals are expressed in the mesh local space.
  18656. */
  18657. AbstractMesh.prototype.getFacetLocalNormals = function () {
  18658. if (!this._facetNormals) {
  18659. this.updateFacetData();
  18660. }
  18661. return this._facetNormals;
  18662. };
  18663. /**
  18664. * Returns the facetLocalPositions array.
  18665. * The facet positions are expressed in the mesh local space.
  18666. */
  18667. AbstractMesh.prototype.getFacetLocalPositions = function () {
  18668. if (!this._facetPositions) {
  18669. this.updateFacetData();
  18670. }
  18671. return this._facetPositions;
  18672. };
  18673. /**
  18674. * Returns the facetLocalPartioning array.
  18675. */
  18676. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  18677. if (!this._facetPartitioning) {
  18678. this.updateFacetData();
  18679. }
  18680. return this._facetPartitioning;
  18681. };
  18682. /**
  18683. * Returns the i-th facet position in the world system.
  18684. * This method allocates a new Vector3 per call.
  18685. */
  18686. AbstractMesh.prototype.getFacetPosition = function (i) {
  18687. var pos = BABYLON.Vector3.Zero();
  18688. this.getFacetPositionToRef(i, pos);
  18689. return pos;
  18690. };
  18691. /**
  18692. * Sets the reference Vector3 with the i-th facet position in the world system.
  18693. * Returns the AbstractMesh.
  18694. */
  18695. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  18696. var localPos = (this.getFacetLocalPositions())[i];
  18697. var world = this.getWorldMatrix();
  18698. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  18699. return this;
  18700. };
  18701. /**
  18702. * Returns the i-th facet normal in the world system.
  18703. * This method allocates a new Vector3 per call.
  18704. */
  18705. AbstractMesh.prototype.getFacetNormal = function (i) {
  18706. var norm = BABYLON.Vector3.Zero();
  18707. this.getFacetNormalToRef(i, norm);
  18708. return norm;
  18709. };
  18710. /**
  18711. * Sets the reference Vector3 with the i-th facet normal in the world system.
  18712. * Returns the AbstractMesh.
  18713. */
  18714. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  18715. var localNorm = (this.getFacetLocalNormals())[i];
  18716. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  18717. return this;
  18718. };
  18719. /**
  18720. * 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).
  18721. */
  18722. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  18723. var bInfo = this.getBoundingInfo();
  18724. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  18725. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  18726. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  18727. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  18728. return null;
  18729. }
  18730. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  18731. };
  18732. /**
  18733. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  18734. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  18735. * 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.
  18736. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  18737. * 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.
  18738. */
  18739. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  18740. if (checkFace === void 0) { checkFace = false; }
  18741. if (facing === void 0) { facing = true; }
  18742. var world = this.getWorldMatrix();
  18743. var invMat = BABYLON.Tmp.Matrix[5];
  18744. world.invertToRef(invMat);
  18745. var invVect = BABYLON.Tmp.Vector3[8];
  18746. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  18747. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  18748. if (projected) {
  18749. // tranform the local computed projected vector to world coordinates
  18750. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  18751. }
  18752. return closest;
  18753. };
  18754. /**
  18755. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  18756. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  18757. * 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.
  18758. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  18759. * 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.
  18760. */
  18761. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  18762. if (checkFace === void 0) { checkFace = false; }
  18763. if (facing === void 0) { facing = true; }
  18764. var closest = null;
  18765. var tmpx = 0.0;
  18766. var tmpy = 0.0;
  18767. var tmpz = 0.0;
  18768. var d = 0.0; // tmp dot facet normal * facet position
  18769. var t0 = 0.0;
  18770. var projx = 0.0;
  18771. var projy = 0.0;
  18772. var projz = 0.0;
  18773. // Get all the facets in the same partitioning block than (x, y, z)
  18774. var facetPositions = this.getFacetLocalPositions();
  18775. var facetNormals = this.getFacetLocalNormals();
  18776. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  18777. if (!facetsInBlock) {
  18778. return null;
  18779. }
  18780. // Get the closest facet to (x, y, z)
  18781. var shortest = Number.MAX_VALUE; // init distance vars
  18782. var tmpDistance = shortest;
  18783. var fib; // current facet in the block
  18784. var norm; // current facet normal
  18785. var p0; // current facet barycenter position
  18786. // loop on all the facets in the current partitioning block
  18787. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  18788. fib = facetsInBlock[idx];
  18789. norm = facetNormals[fib];
  18790. p0 = facetPositions[fib];
  18791. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  18792. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  18793. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  18794. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  18795. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  18796. projx = x + norm.x * t0;
  18797. projy = y + norm.y * t0;
  18798. projz = z + norm.z * t0;
  18799. tmpx = projx - x;
  18800. tmpy = projy - y;
  18801. tmpz = projz - z;
  18802. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  18803. if (tmpDistance < shortest) {
  18804. shortest = tmpDistance;
  18805. closest = fib;
  18806. if (projected) {
  18807. projected.x = projx;
  18808. projected.y = projy;
  18809. projected.z = projz;
  18810. }
  18811. }
  18812. }
  18813. }
  18814. return closest;
  18815. };
  18816. /**
  18817. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  18818. */
  18819. AbstractMesh.prototype.getFacetDataParameters = function () {
  18820. return this._facetParameters;
  18821. };
  18822. /**
  18823. * Disables the feature FacetData and frees the related memory.
  18824. * Returns the AbstractMesh.
  18825. */
  18826. AbstractMesh.prototype.disableFacetData = function () {
  18827. if (this._facetDataEnabled) {
  18828. this._facetDataEnabled = false;
  18829. this._facetPositions = new Array();
  18830. this._facetNormals = new Array();
  18831. this._facetPartitioning = new Array();
  18832. this._facetParameters = null;
  18833. this._depthSortedIndices = new Uint32Array(0);
  18834. }
  18835. return this;
  18836. };
  18837. /**
  18838. * Updates the AbstractMesh indices array. Actually, used by the Mesh object.
  18839. * Returns the mesh.
  18840. */
  18841. AbstractMesh.prototype.updateIndices = function (indices) {
  18842. return this;
  18843. };
  18844. /**
  18845. * The mesh Geometry. Actually used by the Mesh object.
  18846. * Returns a blank geometry object.
  18847. */
  18848. /**
  18849. * Creates new normals data for the mesh.
  18850. * @param updatable.
  18851. */
  18852. AbstractMesh.prototype.createNormals = function (updatable) {
  18853. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18854. var indices = this.getIndices();
  18855. var normals;
  18856. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  18857. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18858. }
  18859. else {
  18860. normals = [];
  18861. }
  18862. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  18863. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  18864. };
  18865. /**
  18866. * Align the mesh with a normal.
  18867. * Returns the mesh.
  18868. */
  18869. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  18870. if (!upDirection) {
  18871. upDirection = BABYLON.Axis.Y;
  18872. }
  18873. var axisX = BABYLON.Tmp.Vector3[0];
  18874. var axisZ = BABYLON.Tmp.Vector3[1];
  18875. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  18876. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  18877. if (this.rotationQuaternion) {
  18878. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  18879. }
  18880. else {
  18881. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  18882. }
  18883. return this;
  18884. };
  18885. AbstractMesh.prototype.checkOcclusionQuery = function () {
  18886. var engine = this.getEngine();
  18887. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  18888. this._isOccluded = false;
  18889. return;
  18890. }
  18891. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  18892. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  18893. if (isOcclusionQueryAvailable) {
  18894. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  18895. this._isOcclusionQueryInProgress = false;
  18896. this._occlusionInternalRetryCounter = 0;
  18897. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  18898. }
  18899. else {
  18900. this._occlusionInternalRetryCounter++;
  18901. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  18902. this._isOcclusionQueryInProgress = false;
  18903. this._occlusionInternalRetryCounter = 0;
  18904. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  18905. // if strict continue the last state of the object.
  18906. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  18907. }
  18908. else {
  18909. return;
  18910. }
  18911. }
  18912. }
  18913. var scene = this.getScene();
  18914. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  18915. if (!this._occlusionQuery) {
  18916. this._occlusionQuery = engine.createQuery();
  18917. }
  18918. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  18919. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  18920. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  18921. this._isOcclusionQueryInProgress = true;
  18922. };
  18923. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  18924. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  18925. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  18926. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  18927. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  18928. return AbstractMesh;
  18929. }(BABYLON.TransformNode));
  18930. BABYLON.AbstractMesh = AbstractMesh;
  18931. })(BABYLON || (BABYLON = {}));
  18932. //# sourceMappingURL=babylon.abstractMesh.js.map
  18933. var BABYLON;
  18934. (function (BABYLON) {
  18935. /**
  18936. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  18937. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  18938. * All meshes allow light to pass through them unless shadow generation is activated. The default number of lights allowed is four but this can be increased.
  18939. */
  18940. var Light = /** @class */ (function (_super) {
  18941. __extends(Light, _super);
  18942. /**
  18943. * Creates a Light object in the scene.
  18944. * Documentation : http://doc.babylonjs.com/tutorials/lights
  18945. * @param name The firendly name of the light
  18946. * @param scene The scene the light belongs too
  18947. */
  18948. function Light(name, scene) {
  18949. var _this = _super.call(this, name, scene) || this;
  18950. /**
  18951. * Diffuse gives the basic color to an object.
  18952. */
  18953. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  18954. /**
  18955. * Specular produces a highlight color on an object.
  18956. * Note: This is note affecting PBR materials.
  18957. */
  18958. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  18959. /**
  18960. * Strength of the light.
  18961. * Note: By default it is define in the framework own unit.
  18962. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  18963. */
  18964. _this.intensity = 1.0;
  18965. /**
  18966. * Defines how far from the source the light is impacting in scene units.
  18967. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  18968. */
  18969. _this.range = Number.MAX_VALUE;
  18970. /**
  18971. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  18972. * of light.
  18973. */
  18974. _this._photometricScale = 1.0;
  18975. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  18976. _this._radius = 0.00001;
  18977. /**
  18978. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  18979. * exceeding the number allowed of the materials.
  18980. */
  18981. _this.renderPriority = 0;
  18982. /**
  18983. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  18984. * the current shadow generator.
  18985. */
  18986. _this.shadowEnabled = true;
  18987. _this._excludeWithLayerMask = 0;
  18988. _this._includeOnlyWithLayerMask = 0;
  18989. _this._lightmapMode = 0;
  18990. /**
  18991. * @ignore Internal use only.
  18992. */
  18993. _this._excludedMeshesIds = new Array();
  18994. /**
  18995. * @ignore Internal use only.
  18996. */
  18997. _this._includedOnlyMeshesIds = new Array();
  18998. _this.getScene().addLight(_this);
  18999. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  19000. _this._buildUniformLayout();
  19001. _this.includedOnlyMeshes = new Array();
  19002. _this.excludedMeshes = new Array();
  19003. _this._resyncMeshes();
  19004. return _this;
  19005. }
  19006. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  19007. /**
  19008. * If every light affecting the material is in this lightmapMode,
  19009. * material.lightmapTexture adds or multiplies
  19010. * (depends on material.useLightmapAsShadowmap)
  19011. * after every other light calculations.
  19012. */
  19013. get: function () {
  19014. return Light._LIGHTMAP_DEFAULT;
  19015. },
  19016. enumerable: true,
  19017. configurable: true
  19018. });
  19019. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  19020. /**
  19021. * material.lightmapTexture as only diffuse lighting from this light
  19022. * adds only specular lighting from this light
  19023. * adds dynamic shadows
  19024. */
  19025. get: function () {
  19026. return Light._LIGHTMAP_SPECULAR;
  19027. },
  19028. enumerable: true,
  19029. configurable: true
  19030. });
  19031. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  19032. /**
  19033. * material.lightmapTexture as only lighting
  19034. * no light calculation from this light
  19035. * only adds dynamic shadows from this light
  19036. */
  19037. get: function () {
  19038. return Light._LIGHTMAP_SHADOWSONLY;
  19039. },
  19040. enumerable: true,
  19041. configurable: true
  19042. });
  19043. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  19044. /**
  19045. * Each light type uses the default quantity according to its type:
  19046. * point/spot lights use luminous intensity
  19047. * directional lights use illuminance
  19048. */
  19049. get: function () {
  19050. return Light._INTENSITYMODE_AUTOMATIC;
  19051. },
  19052. enumerable: true,
  19053. configurable: true
  19054. });
  19055. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  19056. /**
  19057. * lumen (lm)
  19058. */
  19059. get: function () {
  19060. return Light._INTENSITYMODE_LUMINOUSPOWER;
  19061. },
  19062. enumerable: true,
  19063. configurable: true
  19064. });
  19065. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  19066. /**
  19067. * candela (lm/sr)
  19068. */
  19069. get: function () {
  19070. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  19071. },
  19072. enumerable: true,
  19073. configurable: true
  19074. });
  19075. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  19076. /**
  19077. * lux (lm/m^2)
  19078. */
  19079. get: function () {
  19080. return Light._INTENSITYMODE_ILLUMINANCE;
  19081. },
  19082. enumerable: true,
  19083. configurable: true
  19084. });
  19085. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  19086. /**
  19087. * nit (cd/m^2)
  19088. */
  19089. get: function () {
  19090. return Light._INTENSITYMODE_LUMINANCE;
  19091. },
  19092. enumerable: true,
  19093. configurable: true
  19094. });
  19095. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  19096. /**
  19097. * Light type const id of the point light.
  19098. */
  19099. get: function () {
  19100. return Light._LIGHTTYPEID_POINTLIGHT;
  19101. },
  19102. enumerable: true,
  19103. configurable: true
  19104. });
  19105. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  19106. /**
  19107. * Light type const id of the directional light.
  19108. */
  19109. get: function () {
  19110. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  19111. },
  19112. enumerable: true,
  19113. configurable: true
  19114. });
  19115. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  19116. /**
  19117. * Light type const id of the spot light.
  19118. */
  19119. get: function () {
  19120. return Light._LIGHTTYPEID_SPOTLIGHT;
  19121. },
  19122. enumerable: true,
  19123. configurable: true
  19124. });
  19125. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  19126. /**
  19127. * Light type const id of the hemispheric light.
  19128. */
  19129. get: function () {
  19130. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  19131. },
  19132. enumerable: true,
  19133. configurable: true
  19134. });
  19135. Object.defineProperty(Light.prototype, "intensityMode", {
  19136. /**
  19137. * Gets the photometric scale used to interpret the intensity.
  19138. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  19139. */
  19140. get: function () {
  19141. return this._intensityMode;
  19142. },
  19143. /**
  19144. * Sets the photometric scale used to interpret the intensity.
  19145. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  19146. */
  19147. set: function (value) {
  19148. this._intensityMode = value;
  19149. this._computePhotometricScale();
  19150. },
  19151. enumerable: true,
  19152. configurable: true
  19153. });
  19154. ;
  19155. ;
  19156. Object.defineProperty(Light.prototype, "radius", {
  19157. /**
  19158. * Gets the light radius used by PBR Materials to simulate soft area lights.
  19159. */
  19160. get: function () {
  19161. return this._radius;
  19162. },
  19163. /**
  19164. * sets the light radius used by PBR Materials to simulate soft area lights.
  19165. */
  19166. set: function (value) {
  19167. this._radius = value;
  19168. this._computePhotometricScale();
  19169. },
  19170. enumerable: true,
  19171. configurable: true
  19172. });
  19173. ;
  19174. ;
  19175. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  19176. /**
  19177. * Gets the only meshes impacted by this light.
  19178. */
  19179. get: function () {
  19180. return this._includedOnlyMeshes;
  19181. },
  19182. /**
  19183. * Sets the only meshes impacted by this light.
  19184. */
  19185. set: function (value) {
  19186. this._includedOnlyMeshes = value;
  19187. this._hookArrayForIncludedOnly(value);
  19188. },
  19189. enumerable: true,
  19190. configurable: true
  19191. });
  19192. Object.defineProperty(Light.prototype, "excludedMeshes", {
  19193. /**
  19194. * Gets the meshes not impacted by this light.
  19195. */
  19196. get: function () {
  19197. return this._excludedMeshes;
  19198. },
  19199. /**
  19200. * Sets the meshes not impacted by this light.
  19201. */
  19202. set: function (value) {
  19203. this._excludedMeshes = value;
  19204. this._hookArrayForExcluded(value);
  19205. },
  19206. enumerable: true,
  19207. configurable: true
  19208. });
  19209. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  19210. /**
  19211. * Gets the layer id use to find what meshes are not impacted by the light.
  19212. * Inactive if 0
  19213. */
  19214. get: function () {
  19215. return this._excludeWithLayerMask;
  19216. },
  19217. /**
  19218. * Sets the layer id use to find what meshes are not impacted by the light.
  19219. * Inactive if 0
  19220. */
  19221. set: function (value) {
  19222. this._excludeWithLayerMask = value;
  19223. this._resyncMeshes();
  19224. },
  19225. enumerable: true,
  19226. configurable: true
  19227. });
  19228. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  19229. /**
  19230. * Gets the layer id use to find what meshes are impacted by the light.
  19231. * Inactive if 0
  19232. */
  19233. get: function () {
  19234. return this._includeOnlyWithLayerMask;
  19235. },
  19236. /**
  19237. * Sets the layer id use to find what meshes are impacted by the light.
  19238. * Inactive if 0
  19239. */
  19240. set: function (value) {
  19241. this._includeOnlyWithLayerMask = value;
  19242. this._resyncMeshes();
  19243. },
  19244. enumerable: true,
  19245. configurable: true
  19246. });
  19247. Object.defineProperty(Light.prototype, "lightmapMode", {
  19248. /**
  19249. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  19250. */
  19251. get: function () {
  19252. return this._lightmapMode;
  19253. },
  19254. /**
  19255. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  19256. */
  19257. set: function (value) {
  19258. if (this._lightmapMode === value) {
  19259. return;
  19260. }
  19261. this._lightmapMode = value;
  19262. this._markMeshesAsLightDirty();
  19263. },
  19264. enumerable: true,
  19265. configurable: true
  19266. });
  19267. /**
  19268. * Returns the string "Light".
  19269. * @returns the class name
  19270. */
  19271. Light.prototype.getClassName = function () {
  19272. return "Light";
  19273. };
  19274. /**
  19275. * Converts the light information to a readable string for debug purpose.
  19276. * @param fullDetails Supports for multiple levels of logging within scene loading
  19277. * @returns the human readable light info
  19278. */
  19279. Light.prototype.toString = function (fullDetails) {
  19280. var ret = "Name: " + this.name;
  19281. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  19282. if (this.animations) {
  19283. for (var i = 0; i < this.animations.length; i++) {
  19284. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  19285. }
  19286. }
  19287. if (fullDetails) {
  19288. }
  19289. return ret;
  19290. };
  19291. /**
  19292. * Set the enabled state of this node.
  19293. * @param value - the new enabled state
  19294. * @see isEnabled
  19295. */
  19296. Light.prototype.setEnabled = function (value) {
  19297. _super.prototype.setEnabled.call(this, value);
  19298. this._resyncMeshes();
  19299. };
  19300. /**
  19301. * Returns the Light associated shadow generator if any.
  19302. * @return the associated shadow generator.
  19303. */
  19304. Light.prototype.getShadowGenerator = function () {
  19305. return this._shadowGenerator;
  19306. };
  19307. /**
  19308. * Returns a Vector3, the absolute light position in the World.
  19309. * @returns the world space position of the light
  19310. */
  19311. Light.prototype.getAbsolutePosition = function () {
  19312. return BABYLON.Vector3.Zero();
  19313. };
  19314. /**
  19315. * Specifies if the light will affect the passed mesh.
  19316. * @param mesh The mesh to test against the light
  19317. * @return true the mesh is affected otherwise, false.
  19318. */
  19319. Light.prototype.canAffectMesh = function (mesh) {
  19320. if (!mesh) {
  19321. return true;
  19322. }
  19323. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  19324. return false;
  19325. }
  19326. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  19327. return false;
  19328. }
  19329. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  19330. return false;
  19331. }
  19332. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  19333. return false;
  19334. }
  19335. return true;
  19336. };
  19337. /**
  19338. * Computes and Returns the light World matrix.
  19339. * @returns the world matrix
  19340. */
  19341. Light.prototype.getWorldMatrix = function () {
  19342. this._currentRenderId = this.getScene().getRenderId();
  19343. var worldMatrix = this._getWorldMatrix();
  19344. if (this.parent && this.parent.getWorldMatrix) {
  19345. if (!this._parentedWorldMatrix) {
  19346. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  19347. }
  19348. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  19349. this._markSyncedWithParent();
  19350. return this._parentedWorldMatrix;
  19351. }
  19352. return worldMatrix;
  19353. };
  19354. /**
  19355. * Sort function to order lights for rendering.
  19356. * @param a First Light object to compare to second.
  19357. * @param b Second Light object to compare first.
  19358. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  19359. */
  19360. Light.CompareLightsPriority = function (a, b) {
  19361. //shadow-casting lights have priority over non-shadow-casting lights
  19362. //the renderPrioirty is a secondary sort criterion
  19363. if (a.shadowEnabled !== b.shadowEnabled) {
  19364. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  19365. }
  19366. return b.renderPriority - a.renderPriority;
  19367. };
  19368. /**
  19369. * Disposes the light.
  19370. */
  19371. Light.prototype.dispose = function () {
  19372. if (this._shadowGenerator) {
  19373. this._shadowGenerator.dispose();
  19374. this._shadowGenerator = null;
  19375. }
  19376. // Animations
  19377. this.getScene().stopAnimation(this);
  19378. // Remove from meshes
  19379. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19380. var mesh = _a[_i];
  19381. mesh._removeLightSource(this);
  19382. }
  19383. this._uniformBuffer.dispose();
  19384. // Remove from scene
  19385. this.getScene().removeLight(this);
  19386. _super.prototype.dispose.call(this);
  19387. };
  19388. /**
  19389. * Returns the light type ID (integer).
  19390. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  19391. */
  19392. Light.prototype.getTypeID = function () {
  19393. return 0;
  19394. };
  19395. /**
  19396. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  19397. * @returns the scaled intensity in intensity mode unit
  19398. */
  19399. Light.prototype.getScaledIntensity = function () {
  19400. return this._photometricScale * this.intensity;
  19401. };
  19402. /**
  19403. * Returns a new Light object, named "name", from the current one.
  19404. * @param name The name of the cloned light
  19405. * @returns the new created light
  19406. */
  19407. Light.prototype.clone = function (name) {
  19408. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  19409. if (!constructor) {
  19410. return null;
  19411. }
  19412. return BABYLON.SerializationHelper.Clone(constructor, this);
  19413. };
  19414. /**
  19415. * Serializes the current light into a Serialization object.
  19416. * @returns the serialized object.
  19417. */
  19418. Light.prototype.serialize = function () {
  19419. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  19420. // Type
  19421. serializationObject.type = this.getTypeID();
  19422. // Parent
  19423. if (this.parent) {
  19424. serializationObject.parentId = this.parent.id;
  19425. }
  19426. // Inclusion / exclusions
  19427. if (this.excludedMeshes.length > 0) {
  19428. serializationObject.excludedMeshesIds = [];
  19429. this.excludedMeshes.forEach(function (mesh) {
  19430. serializationObject.excludedMeshesIds.push(mesh.id);
  19431. });
  19432. }
  19433. if (this.includedOnlyMeshes.length > 0) {
  19434. serializationObject.includedOnlyMeshesIds = [];
  19435. this.includedOnlyMeshes.forEach(function (mesh) {
  19436. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  19437. });
  19438. }
  19439. // Animations
  19440. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  19441. serializationObject.ranges = this.serializeAnimationRanges();
  19442. return serializationObject;
  19443. };
  19444. /**
  19445. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  19446. * This new light is named "name" and added to the passed scene.
  19447. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  19448. * @param name The friendly name of the light
  19449. * @param scene The scene the new light will belong to
  19450. * @returns the constructor function
  19451. */
  19452. Light.GetConstructorFromName = function (type, name, scene) {
  19453. switch (type) {
  19454. case 0:
  19455. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  19456. case 1:
  19457. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  19458. case 2:
  19459. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  19460. case 3:
  19461. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  19462. }
  19463. return null;
  19464. };
  19465. /**
  19466. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  19467. * @param parsedLight The JSON representation of the light
  19468. * @param scene The scene to create the parsed light in
  19469. * @returns the created light after parsing
  19470. */
  19471. Light.Parse = function (parsedLight, scene) {
  19472. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  19473. if (!constructor) {
  19474. return null;
  19475. }
  19476. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  19477. // Inclusion / exclusions
  19478. if (parsedLight.excludedMeshesIds) {
  19479. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  19480. }
  19481. if (parsedLight.includedOnlyMeshesIds) {
  19482. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  19483. }
  19484. // Parent
  19485. if (parsedLight.parentId) {
  19486. light._waitingParentId = parsedLight.parentId;
  19487. }
  19488. // Animations
  19489. if (parsedLight.animations) {
  19490. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  19491. var parsedAnimation = parsedLight.animations[animationIndex];
  19492. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  19493. }
  19494. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  19495. }
  19496. if (parsedLight.autoAnimate) {
  19497. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  19498. }
  19499. return light;
  19500. };
  19501. Light.prototype._hookArrayForExcluded = function (array) {
  19502. var _this = this;
  19503. var oldPush = array.push;
  19504. array.push = function () {
  19505. var items = [];
  19506. for (var _i = 0; _i < arguments.length; _i++) {
  19507. items[_i] = arguments[_i];
  19508. }
  19509. var result = oldPush.apply(array, items);
  19510. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  19511. var item = items_1[_a];
  19512. item._resyncLighSource(_this);
  19513. }
  19514. return result;
  19515. };
  19516. var oldSplice = array.splice;
  19517. array.splice = function (index, deleteCount) {
  19518. var deleted = oldSplice.apply(array, [index, deleteCount]);
  19519. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  19520. var item = deleted_1[_i];
  19521. item._resyncLighSource(_this);
  19522. }
  19523. return deleted;
  19524. };
  19525. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  19526. var item = array_1[_i];
  19527. item._resyncLighSource(this);
  19528. }
  19529. };
  19530. Light.prototype._hookArrayForIncludedOnly = function (array) {
  19531. var _this = this;
  19532. var oldPush = array.push;
  19533. array.push = function () {
  19534. var items = [];
  19535. for (var _i = 0; _i < arguments.length; _i++) {
  19536. items[_i] = arguments[_i];
  19537. }
  19538. var result = oldPush.apply(array, items);
  19539. _this._resyncMeshes();
  19540. return result;
  19541. };
  19542. var oldSplice = array.splice;
  19543. array.splice = function (index, deleteCount) {
  19544. var deleted = oldSplice.apply(array, [index, deleteCount]);
  19545. _this._resyncMeshes();
  19546. return deleted;
  19547. };
  19548. this._resyncMeshes();
  19549. };
  19550. Light.prototype._resyncMeshes = function () {
  19551. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19552. var mesh = _a[_i];
  19553. mesh._resyncLighSource(this);
  19554. }
  19555. };
  19556. /**
  19557. * Forces the meshes to update their light related information in their rendering used effects
  19558. * @ignore Internal Use Only
  19559. */
  19560. Light.prototype._markMeshesAsLightDirty = function () {
  19561. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19562. var mesh = _a[_i];
  19563. if (mesh._lightSources.indexOf(this) !== -1) {
  19564. mesh._markSubMeshesAsLightDirty();
  19565. }
  19566. }
  19567. };
  19568. /**
  19569. * Recomputes the cached photometric scale if needed.
  19570. */
  19571. Light.prototype._computePhotometricScale = function () {
  19572. this._photometricScale = this._getPhotometricScale();
  19573. this.getScene().resetCachedMaterial();
  19574. };
  19575. /**
  19576. * Returns the Photometric Scale according to the light type and intensity mode.
  19577. */
  19578. Light.prototype._getPhotometricScale = function () {
  19579. var photometricScale = 0.0;
  19580. var lightTypeID = this.getTypeID();
  19581. //get photometric mode
  19582. var photometricMode = this.intensityMode;
  19583. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  19584. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  19585. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  19586. }
  19587. else {
  19588. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  19589. }
  19590. }
  19591. //compute photometric scale
  19592. switch (lightTypeID) {
  19593. case Light.LIGHTTYPEID_POINTLIGHT:
  19594. case Light.LIGHTTYPEID_SPOTLIGHT:
  19595. switch (photometricMode) {
  19596. case Light.INTENSITYMODE_LUMINOUSPOWER:
  19597. photometricScale = 1.0 / (4.0 * Math.PI);
  19598. break;
  19599. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  19600. photometricScale = 1.0;
  19601. break;
  19602. case Light.INTENSITYMODE_LUMINANCE:
  19603. photometricScale = this.radius * this.radius;
  19604. break;
  19605. }
  19606. break;
  19607. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  19608. switch (photometricMode) {
  19609. case Light.INTENSITYMODE_ILLUMINANCE:
  19610. photometricScale = 1.0;
  19611. break;
  19612. case Light.INTENSITYMODE_LUMINANCE:
  19613. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  19614. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  19615. var apexAngleRadians = this.radius;
  19616. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  19617. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  19618. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  19619. photometricScale = solidAngle;
  19620. break;
  19621. }
  19622. break;
  19623. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  19624. // No fall off in hemisperic light.
  19625. photometricScale = 1.0;
  19626. break;
  19627. }
  19628. return photometricScale;
  19629. };
  19630. /**
  19631. * Reorder the light in the scene according to their defined priority.
  19632. * @ignore Internal Use Only
  19633. */
  19634. Light.prototype._reorderLightsInScene = function () {
  19635. var scene = this.getScene();
  19636. if (this._renderPriority != 0) {
  19637. scene.requireLightSorting = true;
  19638. }
  19639. this.getScene().sortLightsByPriority();
  19640. };
  19641. //lightmapMode Consts
  19642. Light._LIGHTMAP_DEFAULT = 0;
  19643. Light._LIGHTMAP_SPECULAR = 1;
  19644. Light._LIGHTMAP_SHADOWSONLY = 2;
  19645. // Intensity Mode Consts
  19646. Light._INTENSITYMODE_AUTOMATIC = 0;
  19647. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  19648. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  19649. Light._INTENSITYMODE_ILLUMINANCE = 3;
  19650. Light._INTENSITYMODE_LUMINANCE = 4;
  19651. // Light types ids const.
  19652. Light._LIGHTTYPEID_POINTLIGHT = 0;
  19653. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  19654. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  19655. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  19656. __decorate([
  19657. BABYLON.serializeAsColor3()
  19658. ], Light.prototype, "diffuse", void 0);
  19659. __decorate([
  19660. BABYLON.serializeAsColor3()
  19661. ], Light.prototype, "specular", void 0);
  19662. __decorate([
  19663. BABYLON.serialize()
  19664. ], Light.prototype, "intensity", void 0);
  19665. __decorate([
  19666. BABYLON.serialize()
  19667. ], Light.prototype, "range", void 0);
  19668. __decorate([
  19669. BABYLON.serialize()
  19670. ], Light.prototype, "intensityMode", null);
  19671. __decorate([
  19672. BABYLON.serialize()
  19673. ], Light.prototype, "radius", null);
  19674. __decorate([
  19675. BABYLON.serialize()
  19676. ], Light.prototype, "_renderPriority", void 0);
  19677. __decorate([
  19678. BABYLON.expandToProperty("_reorderLightsInScene")
  19679. ], Light.prototype, "renderPriority", void 0);
  19680. __decorate([
  19681. BABYLON.serialize()
  19682. ], Light.prototype, "shadowEnabled", void 0);
  19683. __decorate([
  19684. BABYLON.serialize("excludeWithLayerMask")
  19685. ], Light.prototype, "_excludeWithLayerMask", void 0);
  19686. __decorate([
  19687. BABYLON.serialize("includeOnlyWithLayerMask")
  19688. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  19689. __decorate([
  19690. BABYLON.serialize("lightmapMode")
  19691. ], Light.prototype, "_lightmapMode", void 0);
  19692. return Light;
  19693. }(BABYLON.Node));
  19694. BABYLON.Light = Light;
  19695. })(BABYLON || (BABYLON = {}));
  19696. //# sourceMappingURL=babylon.light.js.map
  19697. var BABYLON;
  19698. (function (BABYLON) {
  19699. var Camera = /** @class */ (function (_super) {
  19700. __extends(Camera, _super);
  19701. function Camera(name, position, scene) {
  19702. var _this = _super.call(this, name, scene) || this;
  19703. /**
  19704. * The vector the camera should consider as up.
  19705. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  19706. */
  19707. _this.upVector = BABYLON.Vector3.Up();
  19708. _this.orthoLeft = null;
  19709. _this.orthoRight = null;
  19710. _this.orthoBottom = null;
  19711. _this.orthoTop = null;
  19712. /**
  19713. * FOV is set in Radians. (default is 0.8)
  19714. */
  19715. _this.fov = 0.8;
  19716. _this.minZ = 1;
  19717. _this.maxZ = 10000.0;
  19718. _this.inertia = 0.9;
  19719. _this.mode = Camera.PERSPECTIVE_CAMERA;
  19720. _this.isIntermediate = false;
  19721. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  19722. /**
  19723. * Restricts the camera to viewing objects with the same layerMask.
  19724. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  19725. */
  19726. _this.layerMask = 0x0FFFFFFF;
  19727. /**
  19728. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  19729. */
  19730. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  19731. // Camera rig members
  19732. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  19733. _this._rigCameras = new Array();
  19734. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  19735. _this._skipRendering = false;
  19736. _this.customRenderTargets = new Array();
  19737. // Observables
  19738. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  19739. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  19740. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  19741. _this.onRestoreStateObservable = new BABYLON.Observable();
  19742. // Cache
  19743. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  19744. _this._projectionMatrix = new BABYLON.Matrix();
  19745. _this._doNotComputeProjectionMatrix = false;
  19746. _this._postProcesses = new Array();
  19747. _this._transformMatrix = BABYLON.Matrix.Zero();
  19748. _this._activeMeshes = new BABYLON.SmartArray(256);
  19749. _this._globalPosition = BABYLON.Vector3.Zero();
  19750. _this._refreshFrustumPlanes = true;
  19751. _this.getScene().addCamera(_this);
  19752. if (!_this.getScene().activeCamera) {
  19753. _this.getScene().activeCamera = _this;
  19754. }
  19755. _this.position = position;
  19756. return _this;
  19757. }
  19758. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  19759. get: function () {
  19760. return Camera._PERSPECTIVE_CAMERA;
  19761. },
  19762. enumerable: true,
  19763. configurable: true
  19764. });
  19765. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  19766. get: function () {
  19767. return Camera._ORTHOGRAPHIC_CAMERA;
  19768. },
  19769. enumerable: true,
  19770. configurable: true
  19771. });
  19772. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  19773. /**
  19774. * This is the default FOV mode for perspective cameras.
  19775. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  19776. *
  19777. */
  19778. get: function () {
  19779. return Camera._FOVMODE_VERTICAL_FIXED;
  19780. },
  19781. enumerable: true,
  19782. configurable: true
  19783. });
  19784. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  19785. /**
  19786. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  19787. *
  19788. */
  19789. get: function () {
  19790. return Camera._FOVMODE_HORIZONTAL_FIXED;
  19791. },
  19792. enumerable: true,
  19793. configurable: true
  19794. });
  19795. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  19796. get: function () {
  19797. return Camera._RIG_MODE_NONE;
  19798. },
  19799. enumerable: true,
  19800. configurable: true
  19801. });
  19802. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  19803. get: function () {
  19804. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  19805. },
  19806. enumerable: true,
  19807. configurable: true
  19808. });
  19809. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  19810. get: function () {
  19811. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  19812. },
  19813. enumerable: true,
  19814. configurable: true
  19815. });
  19816. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  19817. get: function () {
  19818. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  19819. },
  19820. enumerable: true,
  19821. configurable: true
  19822. });
  19823. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  19824. get: function () {
  19825. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  19826. },
  19827. enumerable: true,
  19828. configurable: true
  19829. });
  19830. Object.defineProperty(Camera, "RIG_MODE_VR", {
  19831. get: function () {
  19832. return Camera._RIG_MODE_VR;
  19833. },
  19834. enumerable: true,
  19835. configurable: true
  19836. });
  19837. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  19838. get: function () {
  19839. return Camera._RIG_MODE_WEBVR;
  19840. },
  19841. enumerable: true,
  19842. configurable: true
  19843. });
  19844. /**
  19845. * Store current camera state (fov, position, etc..)
  19846. */
  19847. Camera.prototype.storeState = function () {
  19848. this._stateStored = true;
  19849. this._storedFov = this.fov;
  19850. return this;
  19851. };
  19852. /**
  19853. * Restores the camera state values if it has been stored. You must call storeState() first
  19854. */
  19855. Camera.prototype._restoreStateValues = function () {
  19856. if (!this._stateStored) {
  19857. return false;
  19858. }
  19859. this.fov = this._storedFov;
  19860. return true;
  19861. };
  19862. /**
  19863. * Restored camera state. You must call storeState() first
  19864. */
  19865. Camera.prototype.restoreState = function () {
  19866. if (this._restoreStateValues()) {
  19867. this.onRestoreStateObservable.notifyObservers(this);
  19868. return true;
  19869. }
  19870. return false;
  19871. };
  19872. Camera.prototype.getClassName = function () {
  19873. return "Camera";
  19874. };
  19875. /**
  19876. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  19877. */
  19878. Camera.prototype.toString = function (fullDetails) {
  19879. var ret = "Name: " + this.name;
  19880. ret += ", type: " + this.getClassName();
  19881. if (this.animations) {
  19882. for (var i = 0; i < this.animations.length; i++) {
  19883. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  19884. }
  19885. }
  19886. if (fullDetails) {
  19887. }
  19888. return ret;
  19889. };
  19890. Object.defineProperty(Camera.prototype, "globalPosition", {
  19891. get: function () {
  19892. return this._globalPosition;
  19893. },
  19894. enumerable: true,
  19895. configurable: true
  19896. });
  19897. Camera.prototype.getActiveMeshes = function () {
  19898. return this._activeMeshes;
  19899. };
  19900. Camera.prototype.isActiveMesh = function (mesh) {
  19901. return (this._activeMeshes.indexOf(mesh) !== -1);
  19902. };
  19903. //Cache
  19904. Camera.prototype._initCache = function () {
  19905. _super.prototype._initCache.call(this);
  19906. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  19907. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  19908. this._cache.mode = undefined;
  19909. this._cache.minZ = undefined;
  19910. this._cache.maxZ = undefined;
  19911. this._cache.fov = undefined;
  19912. this._cache.fovMode = undefined;
  19913. this._cache.aspectRatio = undefined;
  19914. this._cache.orthoLeft = undefined;
  19915. this._cache.orthoRight = undefined;
  19916. this._cache.orthoBottom = undefined;
  19917. this._cache.orthoTop = undefined;
  19918. this._cache.renderWidth = undefined;
  19919. this._cache.renderHeight = undefined;
  19920. };
  19921. Camera.prototype._updateCache = function (ignoreParentClass) {
  19922. if (!ignoreParentClass) {
  19923. _super.prototype._updateCache.call(this);
  19924. }
  19925. this._cache.position.copyFrom(this.position);
  19926. this._cache.upVector.copyFrom(this.upVector);
  19927. };
  19928. // Synchronized
  19929. Camera.prototype._isSynchronized = function () {
  19930. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  19931. };
  19932. Camera.prototype._isSynchronizedViewMatrix = function () {
  19933. if (!_super.prototype._isSynchronized.call(this))
  19934. return false;
  19935. return this._cache.position.equals(this.position)
  19936. && this._cache.upVector.equals(this.upVector)
  19937. && this.isSynchronizedWithParent();
  19938. };
  19939. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  19940. var check = this._cache.mode === this.mode
  19941. && this._cache.minZ === this.minZ
  19942. && this._cache.maxZ === this.maxZ;
  19943. if (!check) {
  19944. return false;
  19945. }
  19946. var engine = this.getEngine();
  19947. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  19948. check = this._cache.fov === this.fov
  19949. && this._cache.fovMode === this.fovMode
  19950. && this._cache.aspectRatio === engine.getAspectRatio(this);
  19951. }
  19952. else {
  19953. check = this._cache.orthoLeft === this.orthoLeft
  19954. && this._cache.orthoRight === this.orthoRight
  19955. && this._cache.orthoBottom === this.orthoBottom
  19956. && this._cache.orthoTop === this.orthoTop
  19957. && this._cache.renderWidth === engine.getRenderWidth()
  19958. && this._cache.renderHeight === engine.getRenderHeight();
  19959. }
  19960. return check;
  19961. };
  19962. // Controls
  19963. Camera.prototype.attachControl = function (element, noPreventDefault) {
  19964. };
  19965. Camera.prototype.detachControl = function (element) {
  19966. };
  19967. Camera.prototype.update = function () {
  19968. this._checkInputs();
  19969. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  19970. this._updateRigCameras();
  19971. }
  19972. };
  19973. Camera.prototype._checkInputs = function () {
  19974. this.onAfterCheckInputsObservable.notifyObservers(this);
  19975. };
  19976. Object.defineProperty(Camera.prototype, "rigCameras", {
  19977. get: function () {
  19978. return this._rigCameras;
  19979. },
  19980. enumerable: true,
  19981. configurable: true
  19982. });
  19983. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  19984. get: function () {
  19985. return this._rigPostProcess;
  19986. },
  19987. enumerable: true,
  19988. configurable: true
  19989. });
  19990. Camera.prototype._cascadePostProcessesToRigCams = function () {
  19991. // invalidate framebuffer
  19992. if (this._postProcesses.length > 0) {
  19993. this._postProcesses[0].markTextureDirty();
  19994. }
  19995. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  19996. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  19997. var cam = this._rigCameras[i];
  19998. var rigPostProcess = cam._rigPostProcess;
  19999. // for VR rig, there does not have to be a post process
  20000. if (rigPostProcess) {
  20001. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  20002. if (isPass) {
  20003. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  20004. cam.isIntermediate = this._postProcesses.length === 0;
  20005. }
  20006. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  20007. rigPostProcess.markTextureDirty();
  20008. }
  20009. else {
  20010. cam._postProcesses = this._postProcesses.slice(0);
  20011. }
  20012. }
  20013. };
  20014. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  20015. if (insertAt === void 0) { insertAt = null; }
  20016. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  20017. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  20018. return 0;
  20019. }
  20020. if (insertAt == null || insertAt < 0) {
  20021. this._postProcesses.push(postProcess);
  20022. }
  20023. else {
  20024. this._postProcesses.splice(insertAt, 0, postProcess);
  20025. }
  20026. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  20027. return this._postProcesses.indexOf(postProcess);
  20028. };
  20029. Camera.prototype.detachPostProcess = function (postProcess) {
  20030. var idx = this._postProcesses.indexOf(postProcess);
  20031. if (idx !== -1) {
  20032. this._postProcesses.splice(idx, 1);
  20033. }
  20034. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  20035. };
  20036. Camera.prototype.getWorldMatrix = function () {
  20037. if (!this._worldMatrix) {
  20038. this._worldMatrix = BABYLON.Matrix.Identity();
  20039. }
  20040. var viewMatrix = this.getViewMatrix();
  20041. viewMatrix.invertToRef(this._worldMatrix);
  20042. return this._worldMatrix;
  20043. };
  20044. Camera.prototype._getViewMatrix = function () {
  20045. return BABYLON.Matrix.Identity();
  20046. };
  20047. Camera.prototype.getViewMatrix = function (force) {
  20048. if (!force && this._isSynchronizedViewMatrix()) {
  20049. return this._computedViewMatrix;
  20050. }
  20051. this.updateCache();
  20052. this._computedViewMatrix = this._getViewMatrix();
  20053. this._currentRenderId = this.getScene().getRenderId();
  20054. this._refreshFrustumPlanes = true;
  20055. if (!this.parent || !this.parent.getWorldMatrix) {
  20056. this._globalPosition.copyFrom(this.position);
  20057. }
  20058. else {
  20059. if (!this._worldMatrix) {
  20060. this._worldMatrix = BABYLON.Matrix.Identity();
  20061. }
  20062. this._computedViewMatrix.invertToRef(this._worldMatrix);
  20063. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  20064. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  20065. this._computedViewMatrix.invert();
  20066. this._markSyncedWithParent();
  20067. }
  20068. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  20069. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  20070. }
  20071. this.onViewMatrixChangedObservable.notifyObservers(this);
  20072. return this._computedViewMatrix;
  20073. };
  20074. Camera.prototype.freezeProjectionMatrix = function (projection) {
  20075. this._doNotComputeProjectionMatrix = true;
  20076. if (projection !== undefined) {
  20077. this._projectionMatrix = projection;
  20078. }
  20079. };
  20080. ;
  20081. Camera.prototype.unfreezeProjectionMatrix = function () {
  20082. this._doNotComputeProjectionMatrix = false;
  20083. };
  20084. ;
  20085. Camera.prototype.getProjectionMatrix = function (force) {
  20086. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  20087. return this._projectionMatrix;
  20088. }
  20089. // Cache
  20090. this._cache.mode = this.mode;
  20091. this._cache.minZ = this.minZ;
  20092. this._cache.maxZ = this.maxZ;
  20093. // Matrix
  20094. this._refreshFrustumPlanes = true;
  20095. var engine = this.getEngine();
  20096. var scene = this.getScene();
  20097. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  20098. this._cache.fov = this.fov;
  20099. this._cache.fovMode = this.fovMode;
  20100. this._cache.aspectRatio = engine.getAspectRatio(this);
  20101. if (this.minZ <= 0) {
  20102. this.minZ = 0.1;
  20103. }
  20104. if (scene.useRightHandedSystem) {
  20105. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  20106. }
  20107. else {
  20108. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  20109. }
  20110. }
  20111. else {
  20112. var halfWidth = engine.getRenderWidth() / 2.0;
  20113. var halfHeight = engine.getRenderHeight() / 2.0;
  20114. if (scene.useRightHandedSystem) {
  20115. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  20116. }
  20117. else {
  20118. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  20119. }
  20120. this._cache.orthoLeft = this.orthoLeft;
  20121. this._cache.orthoRight = this.orthoRight;
  20122. this._cache.orthoBottom = this.orthoBottom;
  20123. this._cache.orthoTop = this.orthoTop;
  20124. this._cache.renderWidth = engine.getRenderWidth();
  20125. this._cache.renderHeight = engine.getRenderHeight();
  20126. }
  20127. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  20128. return this._projectionMatrix;
  20129. };
  20130. Camera.prototype.getTranformationMatrix = function () {
  20131. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  20132. return this._transformMatrix;
  20133. };
  20134. Camera.prototype.updateFrustumPlanes = function () {
  20135. if (!this._refreshFrustumPlanes) {
  20136. return;
  20137. }
  20138. this.getTranformationMatrix();
  20139. if (!this._frustumPlanes) {
  20140. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  20141. }
  20142. else {
  20143. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  20144. }
  20145. this._refreshFrustumPlanes = false;
  20146. };
  20147. Camera.prototype.isInFrustum = function (target) {
  20148. this.updateFrustumPlanes();
  20149. return target.isInFrustum(this._frustumPlanes);
  20150. };
  20151. Camera.prototype.isCompletelyInFrustum = function (target) {
  20152. this.updateFrustumPlanes();
  20153. return target.isCompletelyInFrustum(this._frustumPlanes);
  20154. };
  20155. Camera.prototype.getForwardRay = function (length, transform, origin) {
  20156. if (length === void 0) { length = 100; }
  20157. if (!transform) {
  20158. transform = this.getWorldMatrix();
  20159. }
  20160. if (!origin) {
  20161. origin = this.position;
  20162. }
  20163. var forward = new BABYLON.Vector3(0, 0, 1);
  20164. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  20165. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  20166. return new BABYLON.Ray(origin, direction, length);
  20167. };
  20168. Camera.prototype.dispose = function () {
  20169. // Observables
  20170. this.onViewMatrixChangedObservable.clear();
  20171. this.onProjectionMatrixChangedObservable.clear();
  20172. this.onAfterCheckInputsObservable.clear();
  20173. this.onRestoreStateObservable.clear();
  20174. // Inputs
  20175. if (this.inputs) {
  20176. this.inputs.clear();
  20177. }
  20178. // Animations
  20179. this.getScene().stopAnimation(this);
  20180. // Remove from scene
  20181. this.getScene().removeCamera(this);
  20182. while (this._rigCameras.length > 0) {
  20183. var camera = this._rigCameras.pop();
  20184. if (camera) {
  20185. camera.dispose();
  20186. }
  20187. }
  20188. // Postprocesses
  20189. if (this._rigPostProcess) {
  20190. this._rigPostProcess.dispose(this);
  20191. this._rigPostProcess = null;
  20192. this._postProcesses = [];
  20193. }
  20194. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  20195. this._rigPostProcess = null;
  20196. this._postProcesses = [];
  20197. }
  20198. else {
  20199. var i = this._postProcesses.length;
  20200. while (--i >= 0) {
  20201. this._postProcesses[i].dispose(this);
  20202. }
  20203. }
  20204. // Render targets
  20205. var i = this.customRenderTargets.length;
  20206. while (--i >= 0) {
  20207. this.customRenderTargets[i].dispose();
  20208. }
  20209. this.customRenderTargets = [];
  20210. // Active Meshes
  20211. this._activeMeshes.dispose();
  20212. _super.prototype.dispose.call(this);
  20213. };
  20214. Object.defineProperty(Camera.prototype, "leftCamera", {
  20215. // ---- Camera rigs section ----
  20216. get: function () {
  20217. if (this._rigCameras.length < 1) {
  20218. return null;
  20219. }
  20220. return this._rigCameras[0];
  20221. },
  20222. enumerable: true,
  20223. configurable: true
  20224. });
  20225. Object.defineProperty(Camera.prototype, "rightCamera", {
  20226. get: function () {
  20227. if (this._rigCameras.length < 2) {
  20228. return null;
  20229. }
  20230. return this._rigCameras[1];
  20231. },
  20232. enumerable: true,
  20233. configurable: true
  20234. });
  20235. Camera.prototype.getLeftTarget = function () {
  20236. if (this._rigCameras.length < 1) {
  20237. return null;
  20238. }
  20239. return this._rigCameras[0].getTarget();
  20240. };
  20241. Camera.prototype.getRightTarget = function () {
  20242. if (this._rigCameras.length < 2) {
  20243. return null;
  20244. }
  20245. return this._rigCameras[1].getTarget();
  20246. };
  20247. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  20248. if (this.cameraRigMode === mode) {
  20249. return;
  20250. }
  20251. while (this._rigCameras.length > 0) {
  20252. var camera = this._rigCameras.pop();
  20253. if (camera) {
  20254. camera.dispose();
  20255. }
  20256. }
  20257. this.cameraRigMode = mode;
  20258. this._cameraRigParams = {};
  20259. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  20260. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  20261. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  20262. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  20263. // create the rig cameras, unless none
  20264. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  20265. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  20266. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  20267. if (leftCamera && rightCamera) {
  20268. this._rigCameras.push(leftCamera);
  20269. this._rigCameras.push(rightCamera);
  20270. }
  20271. }
  20272. switch (this.cameraRigMode) {
  20273. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  20274. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  20275. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  20276. break;
  20277. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  20278. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  20279. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  20280. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  20281. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  20282. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  20283. break;
  20284. case Camera.RIG_MODE_VR:
  20285. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  20286. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  20287. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  20288. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20289. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  20290. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  20291. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  20292. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  20293. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  20294. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20295. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  20296. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  20297. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  20298. if (metrics.compensateDistortion) {
  20299. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  20300. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  20301. }
  20302. break;
  20303. case Camera.RIG_MODE_WEBVR:
  20304. if (rigParams.vrDisplay) {
  20305. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  20306. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  20307. //Left eye
  20308. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  20309. this._rigCameras[0].setCameraRigParameter("left", true);
  20310. //leaving this for future reference
  20311. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  20312. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  20313. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  20314. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  20315. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20316. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  20317. this._rigCameras[0].parent = this;
  20318. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  20319. //Right eye
  20320. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  20321. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  20322. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  20323. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  20324. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  20325. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20326. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  20327. this._rigCameras[1].parent = this;
  20328. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  20329. if (Camera.UseAlternateWebVRRendering) {
  20330. this._rigCameras[1]._skipRendering = true;
  20331. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  20332. }
  20333. }
  20334. break;
  20335. }
  20336. this._cascadePostProcessesToRigCams();
  20337. this.update();
  20338. };
  20339. Camera.prototype._getVRProjectionMatrix = function () {
  20340. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  20341. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  20342. return this._projectionMatrix;
  20343. };
  20344. Camera.prototype._updateCameraRotationMatrix = function () {
  20345. //Here for WebVR
  20346. };
  20347. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  20348. //Here for WebVR
  20349. };
  20350. /**
  20351. * This function MUST be overwritten by the different WebVR cameras available.
  20352. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  20353. */
  20354. Camera.prototype._getWebVRProjectionMatrix = function () {
  20355. return BABYLON.Matrix.Identity();
  20356. };
  20357. /**
  20358. * This function MUST be overwritten by the different WebVR cameras available.
  20359. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  20360. */
  20361. Camera.prototype._getWebVRViewMatrix = function () {
  20362. return BABYLON.Matrix.Identity();
  20363. };
  20364. Camera.prototype.setCameraRigParameter = function (name, value) {
  20365. if (!this._cameraRigParams) {
  20366. this._cameraRigParams = {};
  20367. }
  20368. this._cameraRigParams[name] = value;
  20369. //provisionnally:
  20370. if (name === "interaxialDistance") {
  20371. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  20372. }
  20373. };
  20374. /**
  20375. * needs to be overridden by children so sub has required properties to be copied
  20376. */
  20377. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  20378. return null;
  20379. };
  20380. /**
  20381. * May need to be overridden by children
  20382. */
  20383. Camera.prototype._updateRigCameras = function () {
  20384. for (var i = 0; i < this._rigCameras.length; i++) {
  20385. this._rigCameras[i].minZ = this.minZ;
  20386. this._rigCameras[i].maxZ = this.maxZ;
  20387. this._rigCameras[i].fov = this.fov;
  20388. }
  20389. // only update viewport when ANAGLYPH
  20390. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  20391. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  20392. }
  20393. };
  20394. Camera.prototype._setupInputs = function () {
  20395. };
  20396. Camera.prototype.serialize = function () {
  20397. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  20398. // Type
  20399. serializationObject.type = this.getClassName();
  20400. // Parent
  20401. if (this.parent) {
  20402. serializationObject.parentId = this.parent.id;
  20403. }
  20404. if (this.inputs) {
  20405. this.inputs.serialize(serializationObject);
  20406. }
  20407. // Animations
  20408. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  20409. serializationObject.ranges = this.serializeAnimationRanges();
  20410. return serializationObject;
  20411. };
  20412. Camera.prototype.clone = function (name) {
  20413. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  20414. };
  20415. Camera.prototype.getDirection = function (localAxis) {
  20416. var result = BABYLON.Vector3.Zero();
  20417. this.getDirectionToRef(localAxis, result);
  20418. return result;
  20419. };
  20420. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  20421. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  20422. };
  20423. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  20424. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  20425. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  20426. switch (type) {
  20427. case "ArcRotateCamera":
  20428. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  20429. case "DeviceOrientationCamera":
  20430. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  20431. case "FollowCamera":
  20432. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  20433. case "ArcFollowCamera":
  20434. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  20435. case "GamepadCamera":
  20436. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  20437. case "TouchCamera":
  20438. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  20439. case "VirtualJoysticksCamera":
  20440. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  20441. case "WebVRFreeCamera":
  20442. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20443. case "WebVRGamepadCamera":
  20444. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20445. case "VRDeviceOrientationFreeCamera":
  20446. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20447. case "VRDeviceOrientationGamepadCamera":
  20448. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  20449. case "AnaglyphArcRotateCamera":
  20450. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20451. case "AnaglyphFreeCamera":
  20452. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20453. case "AnaglyphGamepadCamera":
  20454. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20455. case "AnaglyphUniversalCamera":
  20456. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20457. case "StereoscopicArcRotateCamera":
  20458. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20459. case "StereoscopicFreeCamera":
  20460. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20461. case "StereoscopicGamepadCamera":
  20462. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20463. case "StereoscopicUniversalCamera":
  20464. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20465. case "FreeCamera":// Forcing Universal here
  20466. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  20467. default:// Universal Camera is the default value
  20468. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  20469. }
  20470. };
  20471. Camera.prototype.computeWorldMatrix = function () {
  20472. return this.getWorldMatrix();
  20473. };
  20474. Camera.Parse = function (parsedCamera, scene) {
  20475. var type = parsedCamera.type;
  20476. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  20477. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  20478. // Parent
  20479. if (parsedCamera.parentId) {
  20480. camera._waitingParentId = parsedCamera.parentId;
  20481. }
  20482. //If camera has an input manager, let it parse inputs settings
  20483. if (camera.inputs) {
  20484. camera.inputs.parse(parsedCamera);
  20485. camera._setupInputs();
  20486. }
  20487. if (camera.setPosition) {
  20488. camera.position.copyFromFloats(0, 0, 0);
  20489. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  20490. }
  20491. // Target
  20492. if (parsedCamera.target) {
  20493. if (camera.setTarget) {
  20494. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  20495. }
  20496. }
  20497. // Apply 3d rig, when found
  20498. if (parsedCamera.cameraRigMode) {
  20499. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  20500. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  20501. }
  20502. // Animations
  20503. if (parsedCamera.animations) {
  20504. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  20505. var parsedAnimation = parsedCamera.animations[animationIndex];
  20506. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  20507. }
  20508. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  20509. }
  20510. if (parsedCamera.autoAnimate) {
  20511. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  20512. }
  20513. return camera;
  20514. };
  20515. // Statics
  20516. Camera._PERSPECTIVE_CAMERA = 0;
  20517. Camera._ORTHOGRAPHIC_CAMERA = 1;
  20518. Camera._FOVMODE_VERTICAL_FIXED = 0;
  20519. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  20520. Camera._RIG_MODE_NONE = 0;
  20521. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  20522. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  20523. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  20524. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  20525. Camera._RIG_MODE_VR = 20;
  20526. Camera._RIG_MODE_WEBVR = 21;
  20527. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  20528. Camera.UseAlternateWebVRRendering = false;
  20529. __decorate([
  20530. BABYLON.serializeAsVector3()
  20531. ], Camera.prototype, "position", void 0);
  20532. __decorate([
  20533. BABYLON.serializeAsVector3()
  20534. ], Camera.prototype, "upVector", void 0);
  20535. __decorate([
  20536. BABYLON.serialize()
  20537. ], Camera.prototype, "orthoLeft", void 0);
  20538. __decorate([
  20539. BABYLON.serialize()
  20540. ], Camera.prototype, "orthoRight", void 0);
  20541. __decorate([
  20542. BABYLON.serialize()
  20543. ], Camera.prototype, "orthoBottom", void 0);
  20544. __decorate([
  20545. BABYLON.serialize()
  20546. ], Camera.prototype, "orthoTop", void 0);
  20547. __decorate([
  20548. BABYLON.serialize()
  20549. ], Camera.prototype, "fov", void 0);
  20550. __decorate([
  20551. BABYLON.serialize()
  20552. ], Camera.prototype, "minZ", void 0);
  20553. __decorate([
  20554. BABYLON.serialize()
  20555. ], Camera.prototype, "maxZ", void 0);
  20556. __decorate([
  20557. BABYLON.serialize()
  20558. ], Camera.prototype, "inertia", void 0);
  20559. __decorate([
  20560. BABYLON.serialize()
  20561. ], Camera.prototype, "mode", void 0);
  20562. __decorate([
  20563. BABYLON.serialize()
  20564. ], Camera.prototype, "layerMask", void 0);
  20565. __decorate([
  20566. BABYLON.serialize()
  20567. ], Camera.prototype, "fovMode", void 0);
  20568. __decorate([
  20569. BABYLON.serialize()
  20570. ], Camera.prototype, "cameraRigMode", void 0);
  20571. __decorate([
  20572. BABYLON.serialize()
  20573. ], Camera.prototype, "interaxialDistance", void 0);
  20574. __decorate([
  20575. BABYLON.serialize()
  20576. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  20577. return Camera;
  20578. }(BABYLON.Node));
  20579. BABYLON.Camera = Camera;
  20580. })(BABYLON || (BABYLON = {}));
  20581. //# sourceMappingURL=babylon.camera.js.map
  20582. var BABYLON;
  20583. (function (BABYLON) {
  20584. var RenderingManager = /** @class */ (function () {
  20585. function RenderingManager(scene) {
  20586. this._renderingGroups = new Array();
  20587. this._autoClearDepthStencil = {};
  20588. this._customOpaqueSortCompareFn = {};
  20589. this._customAlphaTestSortCompareFn = {};
  20590. this._customTransparentSortCompareFn = {};
  20591. this._renderinGroupInfo = null;
  20592. this._scene = scene;
  20593. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  20594. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  20595. }
  20596. }
  20597. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  20598. if (depth === void 0) { depth = true; }
  20599. if (stencil === void 0) { stencil = true; }
  20600. if (this._depthStencilBufferAlreadyCleaned) {
  20601. return;
  20602. }
  20603. this._scene.getEngine().clear(null, false, depth, stencil);
  20604. this._depthStencilBufferAlreadyCleaned = true;
  20605. };
  20606. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  20607. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  20608. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  20609. var info = null;
  20610. if (observable) {
  20611. if (!this._renderinGroupInfo) {
  20612. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  20613. }
  20614. info = this._renderinGroupInfo;
  20615. info.scene = this._scene;
  20616. info.camera = this._scene.activeCamera;
  20617. }
  20618. // Dispatch sprites
  20619. if (renderSprites) {
  20620. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  20621. var manager = this._scene.spriteManagers[index];
  20622. this.dispatchSprites(manager);
  20623. }
  20624. }
  20625. // Render
  20626. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  20627. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  20628. var renderingGroup = this._renderingGroups[index];
  20629. if (!renderingGroup && !observable)
  20630. continue;
  20631. var renderingGroupMask = 0;
  20632. // Fire PRECLEAR stage
  20633. if (observable && info) {
  20634. renderingGroupMask = Math.pow(2, index);
  20635. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  20636. info.renderingGroupId = index;
  20637. observable.notifyObservers(info, renderingGroupMask);
  20638. }
  20639. // Clear depth/stencil if needed
  20640. if (RenderingManager.AUTOCLEAR) {
  20641. var autoClear = this._autoClearDepthStencil[index];
  20642. if (autoClear && autoClear.autoClear) {
  20643. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  20644. }
  20645. }
  20646. if (observable && info) {
  20647. // Fire PREOPAQUE stage
  20648. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  20649. observable.notifyObservers(info, renderingGroupMask);
  20650. // Fire PRETRANSPARENT stage
  20651. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  20652. observable.notifyObservers(info, renderingGroupMask);
  20653. }
  20654. if (renderingGroup)
  20655. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  20656. // Fire POSTTRANSPARENT stage
  20657. if (observable && info) {
  20658. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  20659. observable.notifyObservers(info, renderingGroupMask);
  20660. }
  20661. }
  20662. };
  20663. RenderingManager.prototype.reset = function () {
  20664. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  20665. var renderingGroup = this._renderingGroups[index];
  20666. if (renderingGroup) {
  20667. renderingGroup.prepare();
  20668. }
  20669. }
  20670. };
  20671. RenderingManager.prototype.dispose = function () {
  20672. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  20673. var renderingGroup = this._renderingGroups[index];
  20674. if (renderingGroup) {
  20675. renderingGroup.dispose();
  20676. }
  20677. }
  20678. this._renderingGroups.length = 0;
  20679. };
  20680. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  20681. if (this._renderingGroups[renderingGroupId] === undefined) {
  20682. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  20683. }
  20684. };
  20685. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  20686. var renderingGroupId = spriteManager.renderingGroupId || 0;
  20687. this._prepareRenderingGroup(renderingGroupId);
  20688. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  20689. };
  20690. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  20691. var renderingGroupId = particleSystem.renderingGroupId || 0;
  20692. this._prepareRenderingGroup(renderingGroupId);
  20693. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  20694. };
  20695. /**
  20696. * @param subMesh The submesh to dispatch
  20697. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  20698. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  20699. */
  20700. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  20701. if (mesh === undefined) {
  20702. mesh = subMesh.getMesh();
  20703. }
  20704. var renderingGroupId = mesh.renderingGroupId || 0;
  20705. this._prepareRenderingGroup(renderingGroupId);
  20706. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  20707. };
  20708. /**
  20709. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  20710. * This allowed control for front to back rendering or reversly depending of the special needs.
  20711. *
  20712. * @param renderingGroupId The rendering group id corresponding to its index
  20713. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  20714. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  20715. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  20716. */
  20717. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  20718. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  20719. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  20720. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  20721. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  20722. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  20723. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  20724. if (this._renderingGroups[renderingGroupId]) {
  20725. var group = this._renderingGroups[renderingGroupId];
  20726. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  20727. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  20728. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  20729. }
  20730. };
  20731. /**
  20732. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  20733. *
  20734. * @param renderingGroupId The rendering group id corresponding to its index
  20735. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  20736. * @param depth Automatically clears depth between groups if true and autoClear is true.
  20737. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  20738. */
  20739. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  20740. if (depth === void 0) { depth = true; }
  20741. if (stencil === void 0) { stencil = true; }
  20742. this._autoClearDepthStencil[renderingGroupId] = {
  20743. autoClear: autoClearDepthStencil,
  20744. depth: depth,
  20745. stencil: stencil
  20746. };
  20747. };
  20748. /**
  20749. * The max id used for rendering groups (not included)
  20750. */
  20751. RenderingManager.MAX_RENDERINGGROUPS = 4;
  20752. /**
  20753. * The min id used for rendering groups (included)
  20754. */
  20755. RenderingManager.MIN_RENDERINGGROUPS = 0;
  20756. /**
  20757. * Used to globally prevent autoclearing scenes.
  20758. */
  20759. RenderingManager.AUTOCLEAR = true;
  20760. return RenderingManager;
  20761. }());
  20762. BABYLON.RenderingManager = RenderingManager;
  20763. })(BABYLON || (BABYLON = {}));
  20764. //# sourceMappingURL=babylon.renderingManager.js.map
  20765. var BABYLON;
  20766. (function (BABYLON) {
  20767. var RenderingGroup = /** @class */ (function () {
  20768. /**
  20769. * Creates a new rendering group.
  20770. * @param index The rendering group index
  20771. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  20772. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  20773. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  20774. */
  20775. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  20776. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  20777. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  20778. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  20779. this.index = index;
  20780. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  20781. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  20782. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  20783. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  20784. this._particleSystems = new BABYLON.SmartArray(256);
  20785. this._spriteManagers = new BABYLON.SmartArray(256);
  20786. this._edgesRenderers = new BABYLON.SmartArray(16);
  20787. this._scene = scene;
  20788. this.opaqueSortCompareFn = opaqueSortCompareFn;
  20789. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  20790. this.transparentSortCompareFn = transparentSortCompareFn;
  20791. }
  20792. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  20793. /**
  20794. * Set the opaque sort comparison function.
  20795. * If null the sub meshes will be render in the order they were created
  20796. */
  20797. set: function (value) {
  20798. this._opaqueSortCompareFn = value;
  20799. if (value) {
  20800. this._renderOpaque = this.renderOpaqueSorted;
  20801. }
  20802. else {
  20803. this._renderOpaque = RenderingGroup.renderUnsorted;
  20804. }
  20805. },
  20806. enumerable: true,
  20807. configurable: true
  20808. });
  20809. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  20810. /**
  20811. * Set the alpha test sort comparison function.
  20812. * If null the sub meshes will be render in the order they were created
  20813. */
  20814. set: function (value) {
  20815. this._alphaTestSortCompareFn = value;
  20816. if (value) {
  20817. this._renderAlphaTest = this.renderAlphaTestSorted;
  20818. }
  20819. else {
  20820. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  20821. }
  20822. },
  20823. enumerable: true,
  20824. configurable: true
  20825. });
  20826. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  20827. /**
  20828. * Set the transparent sort comparison function.
  20829. * If null the sub meshes will be render in the order they were created
  20830. */
  20831. set: function (value) {
  20832. if (value) {
  20833. this._transparentSortCompareFn = value;
  20834. }
  20835. else {
  20836. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  20837. }
  20838. this._renderTransparent = this.renderTransparentSorted;
  20839. },
  20840. enumerable: true,
  20841. configurable: true
  20842. });
  20843. /**
  20844. * Render all the sub meshes contained in the group.
  20845. * @param customRenderFunction Used to override the default render behaviour of the group.
  20846. * @returns true if rendered some submeshes.
  20847. */
  20848. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  20849. if (customRenderFunction) {
  20850. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  20851. return;
  20852. }
  20853. var engine = this._scene.getEngine();
  20854. // Depth only
  20855. if (this._depthOnlySubMeshes.length !== 0) {
  20856. engine.setColorWrite(false);
  20857. this._renderAlphaTest(this._depthOnlySubMeshes);
  20858. engine.setColorWrite(true);
  20859. }
  20860. // Opaque
  20861. if (this._opaqueSubMeshes.length !== 0) {
  20862. this._renderOpaque(this._opaqueSubMeshes);
  20863. }
  20864. // Alpha test
  20865. if (this._alphaTestSubMeshes.length !== 0) {
  20866. this._renderAlphaTest(this._alphaTestSubMeshes);
  20867. }
  20868. var stencilState = engine.getStencilBuffer();
  20869. engine.setStencilBuffer(false);
  20870. // Sprites
  20871. if (renderSprites) {
  20872. this._renderSprites();
  20873. }
  20874. // Particles
  20875. if (renderParticles) {
  20876. this._renderParticles(activeMeshes);
  20877. }
  20878. if (this.onBeforeTransparentRendering) {
  20879. this.onBeforeTransparentRendering();
  20880. }
  20881. // Transparent
  20882. if (this._transparentSubMeshes.length !== 0) {
  20883. this._renderTransparent(this._transparentSubMeshes);
  20884. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  20885. }
  20886. // Set back stencil to false in case it changes before the edge renderer.
  20887. engine.setStencilBuffer(false);
  20888. // Edges
  20889. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  20890. this._edgesRenderers.data[edgesRendererIndex].render();
  20891. }
  20892. // Restore Stencil state.
  20893. engine.setStencilBuffer(stencilState);
  20894. };
  20895. /**
  20896. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  20897. * @param subMeshes The submeshes to render
  20898. */
  20899. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  20900. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  20901. };
  20902. /**
  20903. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  20904. * @param subMeshes The submeshes to render
  20905. */
  20906. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  20907. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  20908. };
  20909. /**
  20910. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  20911. * @param subMeshes The submeshes to render
  20912. */
  20913. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  20914. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  20915. };
  20916. /**
  20917. * Renders the submeshes in a specified order.
  20918. * @param subMeshes The submeshes to sort before render
  20919. * @param sortCompareFn The comparison function use to sort
  20920. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  20921. * @param transparent Specifies to activate blending if true
  20922. */
  20923. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  20924. var subIndex = 0;
  20925. var subMesh;
  20926. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  20927. for (; subIndex < subMeshes.length; subIndex++) {
  20928. subMesh = subMeshes.data[subIndex];
  20929. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  20930. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  20931. }
  20932. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  20933. if (sortCompareFn) {
  20934. sortedArray.sort(sortCompareFn);
  20935. }
  20936. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  20937. subMesh = sortedArray[subIndex];
  20938. if (transparent) {
  20939. var material = subMesh.getMaterial();
  20940. if (material && material.needDepthPrePass) {
  20941. var engine = material.getScene().getEngine();
  20942. engine.setColorWrite(false);
  20943. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  20944. subMesh.render(false);
  20945. engine.setColorWrite(true);
  20946. }
  20947. }
  20948. subMesh.render(transparent);
  20949. }
  20950. };
  20951. /**
  20952. * Renders the submeshes in the order they were dispatched (no sort applied).
  20953. * @param subMeshes The submeshes to render
  20954. */
  20955. RenderingGroup.renderUnsorted = function (subMeshes) {
  20956. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  20957. var submesh = subMeshes.data[subIndex];
  20958. submesh.render(false);
  20959. }
  20960. };
  20961. /**
  20962. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  20963. * are rendered back to front if in the same alpha index.
  20964. *
  20965. * @param a The first submesh
  20966. * @param b The second submesh
  20967. * @returns The result of the comparison
  20968. */
  20969. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  20970. // Alpha index first
  20971. if (a._alphaIndex > b._alphaIndex) {
  20972. return 1;
  20973. }
  20974. if (a._alphaIndex < b._alphaIndex) {
  20975. return -1;
  20976. }
  20977. // Then distance to camera
  20978. return RenderingGroup.backToFrontSortCompare(a, b);
  20979. };
  20980. /**
  20981. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  20982. * are rendered back to front.
  20983. *
  20984. * @param a The first submesh
  20985. * @param b The second submesh
  20986. * @returns The result of the comparison
  20987. */
  20988. RenderingGroup.backToFrontSortCompare = function (a, b) {
  20989. // Then distance to camera
  20990. if (a._distanceToCamera < b._distanceToCamera) {
  20991. return 1;
  20992. }
  20993. if (a._distanceToCamera > b._distanceToCamera) {
  20994. return -1;
  20995. }
  20996. return 0;
  20997. };
  20998. /**
  20999. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  21000. * are rendered front to back (prevent overdraw).
  21001. *
  21002. * @param a The first submesh
  21003. * @param b The second submesh
  21004. * @returns The result of the comparison
  21005. */
  21006. RenderingGroup.frontToBackSortCompare = function (a, b) {
  21007. // Then distance to camera
  21008. if (a._distanceToCamera < b._distanceToCamera) {
  21009. return -1;
  21010. }
  21011. if (a._distanceToCamera > b._distanceToCamera) {
  21012. return 1;
  21013. }
  21014. return 0;
  21015. };
  21016. /**
  21017. * Resets the different lists of submeshes to prepare a new frame.
  21018. */
  21019. RenderingGroup.prototype.prepare = function () {
  21020. this._opaqueSubMeshes.reset();
  21021. this._transparentSubMeshes.reset();
  21022. this._alphaTestSubMeshes.reset();
  21023. this._depthOnlySubMeshes.reset();
  21024. this._particleSystems.reset();
  21025. this._spriteManagers.reset();
  21026. this._edgesRenderers.reset();
  21027. };
  21028. RenderingGroup.prototype.dispose = function () {
  21029. this._opaqueSubMeshes.dispose();
  21030. this._transparentSubMeshes.dispose();
  21031. this._alphaTestSubMeshes.dispose();
  21032. this._depthOnlySubMeshes.dispose();
  21033. this._particleSystems.dispose();
  21034. this._spriteManagers.dispose();
  21035. this._edgesRenderers.dispose();
  21036. };
  21037. /**
  21038. * Inserts the submesh in its correct queue depending on its material.
  21039. * @param subMesh The submesh to dispatch
  21040. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  21041. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  21042. */
  21043. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  21044. // Get mesh and materials if not provided
  21045. if (mesh === undefined) {
  21046. mesh = subMesh.getMesh();
  21047. }
  21048. if (material === undefined) {
  21049. material = subMesh.getMaterial();
  21050. }
  21051. if (material === null || material === undefined) {
  21052. return;
  21053. }
  21054. if (material.needAlphaBlendingForMesh(mesh)) {
  21055. this._transparentSubMeshes.push(subMesh);
  21056. }
  21057. else if (material.needAlphaTesting()) {
  21058. if (material.needDepthPrePass) {
  21059. this._depthOnlySubMeshes.push(subMesh);
  21060. }
  21061. this._alphaTestSubMeshes.push(subMesh);
  21062. }
  21063. else {
  21064. if (material.needDepthPrePass) {
  21065. this._depthOnlySubMeshes.push(subMesh);
  21066. }
  21067. this._opaqueSubMeshes.push(subMesh); // Opaque
  21068. }
  21069. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined) {
  21070. this._edgesRenderers.push(mesh._edgesRenderer);
  21071. }
  21072. };
  21073. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  21074. this._spriteManagers.push(spriteManager);
  21075. };
  21076. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  21077. this._particleSystems.push(particleSystem);
  21078. };
  21079. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  21080. if (this._particleSystems.length === 0) {
  21081. return;
  21082. }
  21083. // Particles
  21084. var activeCamera = this._scene.activeCamera;
  21085. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  21086. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  21087. var particleSystem = this._particleSystems.data[particleIndex];
  21088. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  21089. continue;
  21090. }
  21091. var emitter = particleSystem.emitter;
  21092. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  21093. this._scene._activeParticles.addCount(particleSystem.render(), false);
  21094. }
  21095. }
  21096. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  21097. };
  21098. RenderingGroup.prototype._renderSprites = function () {
  21099. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  21100. return;
  21101. }
  21102. // Sprites
  21103. var activeCamera = this._scene.activeCamera;
  21104. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  21105. for (var id = 0; id < this._spriteManagers.length; id++) {
  21106. var spriteManager = this._spriteManagers.data[id];
  21107. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  21108. spriteManager.render();
  21109. }
  21110. }
  21111. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  21112. };
  21113. return RenderingGroup;
  21114. }());
  21115. BABYLON.RenderingGroup = RenderingGroup;
  21116. })(BABYLON || (BABYLON = {}));
  21117. //# sourceMappingURL=babylon.renderingGroup.js.map
  21118. var BABYLON;
  21119. (function (BABYLON) {
  21120. var ClickInfo = /** @class */ (function () {
  21121. function ClickInfo() {
  21122. this._singleClick = false;
  21123. this._doubleClick = false;
  21124. this._hasSwiped = false;
  21125. this._ignore = false;
  21126. }
  21127. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  21128. get: function () {
  21129. return this._singleClick;
  21130. },
  21131. set: function (b) {
  21132. this._singleClick = b;
  21133. },
  21134. enumerable: true,
  21135. configurable: true
  21136. });
  21137. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  21138. get: function () {
  21139. return this._doubleClick;
  21140. },
  21141. set: function (b) {
  21142. this._doubleClick = b;
  21143. },
  21144. enumerable: true,
  21145. configurable: true
  21146. });
  21147. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  21148. get: function () {
  21149. return this._hasSwiped;
  21150. },
  21151. set: function (b) {
  21152. this._hasSwiped = b;
  21153. },
  21154. enumerable: true,
  21155. configurable: true
  21156. });
  21157. Object.defineProperty(ClickInfo.prototype, "ignore", {
  21158. get: function () {
  21159. return this._ignore;
  21160. },
  21161. set: function (b) {
  21162. this._ignore = b;
  21163. },
  21164. enumerable: true,
  21165. configurable: true
  21166. });
  21167. return ClickInfo;
  21168. }());
  21169. /**
  21170. * This class is used by the onRenderingGroupObservable
  21171. */
  21172. var RenderingGroupInfo = /** @class */ (function () {
  21173. function RenderingGroupInfo() {
  21174. }
  21175. /**
  21176. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  21177. * This stage will be fired no matter what
  21178. */
  21179. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  21180. /**
  21181. * Called before opaque object are rendered.
  21182. * This stage will be fired only if there's 3D Opaque content to render
  21183. */
  21184. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  21185. /**
  21186. * Called after the opaque objects are rendered and before the transparent ones
  21187. * This stage will be fired only if there's 3D transparent content to render
  21188. */
  21189. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  21190. /**
  21191. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  21192. * This stage will be fired no matter what
  21193. */
  21194. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  21195. return RenderingGroupInfo;
  21196. }());
  21197. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  21198. /**
  21199. * Represents a scene to be rendered by the engine.
  21200. * @see http://doc.babylonjs.com/page.php?p=21911
  21201. */
  21202. var Scene = /** @class */ (function () {
  21203. /**
  21204. * @constructor
  21205. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  21206. */
  21207. function Scene(engine) {
  21208. // Members
  21209. this.autoClear = true;
  21210. this.autoClearDepthAndStencil = true;
  21211. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  21212. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  21213. this.forceWireframe = false;
  21214. this._forcePointsCloud = false;
  21215. this.forceShowBoundingBoxes = false;
  21216. this.animationsEnabled = true;
  21217. this.useConstantAnimationDeltaTime = false;
  21218. this.constantlyUpdateMeshUnderPointer = false;
  21219. this.hoverCursor = "pointer";
  21220. this.defaultCursor = "";
  21221. /**
  21222. * This is used to call preventDefault() on pointer down
  21223. * in order to block unwanted artifacts like system double clicks
  21224. */
  21225. this.preventDefaultOnPointerDown = true;
  21226. // Metadata
  21227. this.metadata = null;
  21228. /**
  21229. * An event triggered when the scene is disposed.
  21230. * @type {BABYLON.Observable}
  21231. */
  21232. this.onDisposeObservable = new BABYLON.Observable();
  21233. /**
  21234. * An event triggered before rendering the scene (right after animations and physics)
  21235. * @type {BABYLON.Observable}
  21236. */
  21237. this.onBeforeRenderObservable = new BABYLON.Observable();
  21238. /**
  21239. * An event triggered after rendering the scene
  21240. * @type {BABYLON.Observable}
  21241. */
  21242. this.onAfterRenderObservable = new BABYLON.Observable();
  21243. /**
  21244. * An event triggered before animating the scene
  21245. * @type {BABYLON.Observable}
  21246. */
  21247. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  21248. /**
  21249. * An event triggered after animations processing
  21250. * @type {BABYLON.Observable}
  21251. */
  21252. this.onAfterAnimationsObservable = new BABYLON.Observable();
  21253. /**
  21254. * An event triggered before draw calls are ready to be sent
  21255. * @type {BABYLON.Observable}
  21256. */
  21257. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  21258. /**
  21259. * An event triggered after draw calls have been sent
  21260. * @type {BABYLON.Observable}
  21261. */
  21262. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  21263. /**
  21264. * An event triggered when physic simulation is about to be run
  21265. * @type {BABYLON.Observable}
  21266. */
  21267. this.onBeforePhysicsObservable = new BABYLON.Observable();
  21268. /**
  21269. * An event triggered when physic simulation has been done
  21270. * @type {BABYLON.Observable}
  21271. */
  21272. this.onAfterPhysicsObservable = new BABYLON.Observable();
  21273. /**
  21274. * An event triggered when the scene is ready
  21275. * @type {BABYLON.Observable}
  21276. */
  21277. this.onReadyObservable = new BABYLON.Observable();
  21278. /**
  21279. * An event triggered before rendering a camera
  21280. * @type {BABYLON.Observable}
  21281. */
  21282. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  21283. /**
  21284. * An event triggered after rendering a camera
  21285. * @type {BABYLON.Observable}
  21286. */
  21287. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  21288. /**
  21289. * An event triggered when active meshes evaluation is about to start
  21290. * @type {BABYLON.Observable}
  21291. */
  21292. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  21293. /**
  21294. * An event triggered when active meshes evaluation is done
  21295. * @type {BABYLON.Observable}
  21296. */
  21297. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  21298. /**
  21299. * An event triggered when particles rendering is about to start
  21300. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  21301. * @type {BABYLON.Observable}
  21302. */
  21303. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  21304. /**
  21305. * An event triggered when particles rendering is done
  21306. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  21307. * @type {BABYLON.Observable}
  21308. */
  21309. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  21310. /**
  21311. * An event triggered when sprites rendering is about to start
  21312. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  21313. * @type {BABYLON.Observable}
  21314. */
  21315. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  21316. /**
  21317. * An event triggered when sprites rendering is done
  21318. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  21319. * @type {BABYLON.Observable}
  21320. */
  21321. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  21322. /**
  21323. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  21324. * @type {BABYLON.Observable}
  21325. */
  21326. this.onDataLoadedObservable = new BABYLON.Observable();
  21327. /**
  21328. * An event triggered when a camera is created
  21329. * @type {BABYLON.Observable}
  21330. */
  21331. this.onNewCameraAddedObservable = new BABYLON.Observable();
  21332. /**
  21333. * An event triggered when a camera is removed
  21334. * @type {BABYLON.Observable}
  21335. */
  21336. this.onCameraRemovedObservable = new BABYLON.Observable();
  21337. /**
  21338. * An event triggered when a light is created
  21339. * @type {BABYLON.Observable}
  21340. */
  21341. this.onNewLightAddedObservable = new BABYLON.Observable();
  21342. /**
  21343. * An event triggered when a light is removed
  21344. * @type {BABYLON.Observable}
  21345. */
  21346. this.onLightRemovedObservable = new BABYLON.Observable();
  21347. /**
  21348. * An event triggered when a geometry is created
  21349. * @type {BABYLON.Observable}
  21350. */
  21351. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  21352. /**
  21353. * An event triggered when a geometry is removed
  21354. * @type {BABYLON.Observable}
  21355. */
  21356. this.onGeometryRemovedObservable = new BABYLON.Observable();
  21357. /**
  21358. * An event triggered when a transform node is created
  21359. * @type {BABYLON.Observable}
  21360. */
  21361. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  21362. /**
  21363. * An event triggered when a transform node is removed
  21364. * @type {BABYLON.Observable}
  21365. */
  21366. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  21367. /**
  21368. * An event triggered when a mesh is created
  21369. * @type {BABYLON.Observable}
  21370. */
  21371. this.onNewMeshAddedObservable = new BABYLON.Observable();
  21372. /**
  21373. * An event triggered when a mesh is removed
  21374. * @type {BABYLON.Observable}
  21375. */
  21376. this.onMeshRemovedObservable = new BABYLON.Observable();
  21377. /**
  21378. * An event triggered when render targets are about to be rendered
  21379. * Can happen multiple times per frame.
  21380. * @type {BABYLON.Observable}
  21381. */
  21382. this.OnBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  21383. /**
  21384. * An event triggered when render targets were rendered.
  21385. * Can happen multiple times per frame.
  21386. * @type {BABYLON.Observable}
  21387. */
  21388. this.OnAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  21389. /**
  21390. * An event triggered before calculating deterministic simulation step
  21391. * @type {BABYLON.Observable}
  21392. */
  21393. this.onBeforeStepObservable = new BABYLON.Observable();
  21394. /**
  21395. * An event triggered after calculating deterministic simulation step
  21396. * @type {BABYLON.Observable}
  21397. */
  21398. this.onAfterStepObservable = new BABYLON.Observable();
  21399. /**
  21400. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  21401. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  21402. * 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)
  21403. */
  21404. this.onRenderingGroupObservable = new BABYLON.Observable();
  21405. // Animations
  21406. this.animations = [];
  21407. /**
  21408. * 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).
  21409. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  21410. */
  21411. this.onPrePointerObservable = new BABYLON.Observable();
  21412. /**
  21413. * Observable event triggered each time an input event is received from the rendering canvas
  21414. */
  21415. this.onPointerObservable = new BABYLON.Observable();
  21416. this._meshPickProceed = false;
  21417. this._currentPickResult = null;
  21418. this._previousPickResult = null;
  21419. this._totalPointersPressed = 0;
  21420. this._doubleClickOccured = false;
  21421. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  21422. this.cameraToUseForPointers = null;
  21423. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  21424. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  21425. this._startingPointerTime = 0;
  21426. this._previousStartingPointerTime = 0;
  21427. // Deterministic lockstep
  21428. this._timeAccumulator = 0;
  21429. this._currentStepId = 0;
  21430. this._currentInternalStep = 0;
  21431. // Keyboard
  21432. /**
  21433. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  21434. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  21435. */
  21436. this.onPreKeyboardObservable = new BABYLON.Observable();
  21437. /**
  21438. * Observable event triggered each time an keyboard event is received from the hosting window
  21439. */
  21440. this.onKeyboardObservable = new BABYLON.Observable();
  21441. // Coordinate system
  21442. /**
  21443. * use right-handed coordinate system on this scene.
  21444. * @type {boolean}
  21445. */
  21446. this._useRightHandedSystem = false;
  21447. // Fog
  21448. this._fogEnabled = true;
  21449. this._fogMode = Scene.FOGMODE_NONE;
  21450. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  21451. this.fogDensity = 0.1;
  21452. this.fogStart = 0;
  21453. this.fogEnd = 1000.0;
  21454. // Lights
  21455. /**
  21456. * is shadow enabled on this scene.
  21457. * @type {boolean}
  21458. */
  21459. this._shadowsEnabled = true;
  21460. /**
  21461. * is light enabled on this scene.
  21462. * @type {boolean}
  21463. */
  21464. this._lightsEnabled = true;
  21465. /**
  21466. * All of the lights added to this scene.
  21467. * @see BABYLON.Light
  21468. * @type {BABYLON.Light[]}
  21469. */
  21470. this.lights = new Array();
  21471. // Cameras
  21472. /** All of the cameras added to this scene. */
  21473. this.cameras = new Array();
  21474. /** All of the active cameras added to this scene. */
  21475. this.activeCameras = new Array();
  21476. // Meshes
  21477. /**
  21478. * All of the tranform nodes added to this scene.
  21479. * @see BABYLON.TransformNode
  21480. * @type {BABYLON.TransformNode[]}
  21481. */
  21482. this.transformNodes = new Array();
  21483. /**
  21484. * All of the (abstract) meshes added to this scene.
  21485. * @see BABYLON.AbstractMesh
  21486. * @type {BABYLON.AbstractMesh[]}
  21487. */
  21488. this.meshes = new Array();
  21489. /**
  21490. * All of the animation groups added to this scene.
  21491. * @see BABYLON.AnimationGroup
  21492. * @type {BABYLON.AnimationGroup[]}
  21493. */
  21494. this.animationGroups = new Array();
  21495. // Geometries
  21496. this._geometries = new Array();
  21497. this.materials = new Array();
  21498. this.multiMaterials = new Array();
  21499. // Textures
  21500. this._texturesEnabled = true;
  21501. this.textures = new Array();
  21502. // Particles
  21503. this.particlesEnabled = true;
  21504. this.particleSystems = new Array();
  21505. // Sprites
  21506. this.spritesEnabled = true;
  21507. this.spriteManagers = new Array();
  21508. /**
  21509. * The list of layers (background and foreground) of the scene.
  21510. */
  21511. this.layers = new Array();
  21512. /**
  21513. * The list of effect layers (highlights/glow) contained in the scene.
  21514. */
  21515. this.effectLayers = new Array();
  21516. // Skeletons
  21517. this._skeletonsEnabled = true;
  21518. this.skeletons = new Array();
  21519. // Morph targets
  21520. this.morphTargetManagers = new Array();
  21521. // Lens flares
  21522. this.lensFlaresEnabled = true;
  21523. this.lensFlareSystems = new Array();
  21524. // Collisions
  21525. this.collisionsEnabled = true;
  21526. /** Defines the gravity applied to this scene */
  21527. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  21528. // Postprocesses
  21529. this.postProcesses = new Array();
  21530. this.postProcessesEnabled = true;
  21531. // Customs render targets
  21532. this.renderTargetsEnabled = true;
  21533. this.dumpNextRenderTargets = false;
  21534. this.customRenderTargets = new Array();
  21535. // Imported meshes
  21536. this.importedMeshesFiles = new Array();
  21537. // Probes
  21538. this.probesEnabled = true;
  21539. this.reflectionProbes = new Array();
  21540. this._actionManagers = new Array();
  21541. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  21542. // Procedural textures
  21543. this.proceduralTexturesEnabled = true;
  21544. this._proceduralTextures = new Array();
  21545. this.soundTracks = new Array();
  21546. this._audioEnabled = true;
  21547. this._headphone = false;
  21548. // Performance counters
  21549. this._totalVertices = new BABYLON.PerfCounter();
  21550. this._activeIndices = new BABYLON.PerfCounter();
  21551. this._activeParticles = new BABYLON.PerfCounter();
  21552. this._activeBones = new BABYLON.PerfCounter();
  21553. this._animationTime = 0;
  21554. this.animationTimeScale = 1;
  21555. this._renderId = 0;
  21556. this._executeWhenReadyTimeoutId = -1;
  21557. this._intermediateRendering = false;
  21558. this._viewUpdateFlag = -1;
  21559. this._projectionUpdateFlag = -1;
  21560. this._alternateViewUpdateFlag = -1;
  21561. this._alternateProjectionUpdateFlag = -1;
  21562. this._toBeDisposed = new BABYLON.SmartArray(256);
  21563. this._activeRequests = new Array();
  21564. this._pendingData = new Array();
  21565. this._isDisposed = false;
  21566. this.dispatchAllSubMeshesOfActiveMeshes = false;
  21567. this._activeMeshes = new BABYLON.SmartArray(256);
  21568. this._processedMaterials = new BABYLON.SmartArray(256);
  21569. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  21570. this._activeParticleSystems = new BABYLON.SmartArray(256);
  21571. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  21572. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  21573. this._activeAnimatables = new Array();
  21574. this._transformMatrix = BABYLON.Matrix.Zero();
  21575. this._useAlternateCameraConfiguration = false;
  21576. this._alternateRendering = false;
  21577. this.requireLightSorting = false;
  21578. this._depthRenderer = {};
  21579. this._activeMeshesFrozen = false;
  21580. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  21581. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  21582. this._engine.scenes.push(this);
  21583. this._uid = null;
  21584. this._renderingManager = new BABYLON.RenderingManager(this);
  21585. this.postProcessManager = new BABYLON.PostProcessManager(this);
  21586. if (BABYLON.OutlineRenderer) {
  21587. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  21588. }
  21589. if (BABYLON.Tools.IsWindowObjectExist()) {
  21590. this.attachControl();
  21591. }
  21592. //simplification queue
  21593. if (BABYLON.SimplificationQueue) {
  21594. this.simplificationQueue = new BABYLON.SimplificationQueue();
  21595. }
  21596. //collision coordinator initialization. For now legacy per default.
  21597. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  21598. // Uniform Buffer
  21599. this._createUbo();
  21600. // Default Image processing definition.
  21601. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  21602. }
  21603. Object.defineProperty(Scene, "FOGMODE_NONE", {
  21604. /** The fog is deactivated */
  21605. get: function () {
  21606. return Scene._FOGMODE_NONE;
  21607. },
  21608. enumerable: true,
  21609. configurable: true
  21610. });
  21611. Object.defineProperty(Scene, "FOGMODE_EXP", {
  21612. /** The fog density is following an exponential function */
  21613. get: function () {
  21614. return Scene._FOGMODE_EXP;
  21615. },
  21616. enumerable: true,
  21617. configurable: true
  21618. });
  21619. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  21620. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  21621. get: function () {
  21622. return Scene._FOGMODE_EXP2;
  21623. },
  21624. enumerable: true,
  21625. configurable: true
  21626. });
  21627. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  21628. /** The fog density is following a linear function. */
  21629. get: function () {
  21630. return Scene._FOGMODE_LINEAR;
  21631. },
  21632. enumerable: true,
  21633. configurable: true
  21634. });
  21635. Object.defineProperty(Scene.prototype, "environmentTexture", {
  21636. /**
  21637. * Texture used in all pbr material as the reflection texture.
  21638. * As in the majority of the scene they are the same (exception for multi room and so on),
  21639. * this is easier to reference from here than from all the materials.
  21640. */
  21641. get: function () {
  21642. return this._environmentTexture;
  21643. },
  21644. /**
  21645. * Texture used in all pbr material as the reflection texture.
  21646. * As in the majority of the scene they are the same (exception for multi room and so on),
  21647. * this is easier to set here than in all the materials.
  21648. */
  21649. set: function (value) {
  21650. if (this._environmentTexture === value) {
  21651. return;
  21652. }
  21653. this._environmentTexture = value;
  21654. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  21655. },
  21656. enumerable: true,
  21657. configurable: true
  21658. });
  21659. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  21660. /**
  21661. * Default image processing configuration used either in the rendering
  21662. * Forward main pass or through the imageProcessingPostProcess if present.
  21663. * As in the majority of the scene they are the same (exception for multi camera),
  21664. * this is easier to reference from here than from all the materials and post process.
  21665. *
  21666. * No setter as we it is a shared configuration, you can set the values instead.
  21667. */
  21668. get: function () {
  21669. return this._imageProcessingConfiguration;
  21670. },
  21671. enumerable: true,
  21672. configurable: true
  21673. });
  21674. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  21675. get: function () {
  21676. return this._forcePointsCloud;
  21677. },
  21678. set: function (value) {
  21679. if (this._forcePointsCloud === value) {
  21680. return;
  21681. }
  21682. this._forcePointsCloud = value;
  21683. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21684. },
  21685. enumerable: true,
  21686. configurable: true
  21687. });
  21688. Object.defineProperty(Scene.prototype, "onDispose", {
  21689. /** A function to be executed when this scene is disposed. */
  21690. set: function (callback) {
  21691. if (this._onDisposeObserver) {
  21692. this.onDisposeObservable.remove(this._onDisposeObserver);
  21693. }
  21694. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  21695. },
  21696. enumerable: true,
  21697. configurable: true
  21698. });
  21699. Object.defineProperty(Scene.prototype, "beforeRender", {
  21700. /** A function to be executed before rendering this scene */
  21701. set: function (callback) {
  21702. if (this._onBeforeRenderObserver) {
  21703. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  21704. }
  21705. if (callback) {
  21706. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  21707. }
  21708. },
  21709. enumerable: true,
  21710. configurable: true
  21711. });
  21712. Object.defineProperty(Scene.prototype, "afterRender", {
  21713. /** A function to be executed after rendering this scene */
  21714. set: function (callback) {
  21715. if (this._onAfterRenderObserver) {
  21716. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  21717. }
  21718. if (callback) {
  21719. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  21720. }
  21721. },
  21722. enumerable: true,
  21723. configurable: true
  21724. });
  21725. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  21726. set: function (callback) {
  21727. if (this._onBeforeCameraRenderObserver) {
  21728. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  21729. }
  21730. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  21731. },
  21732. enumerable: true,
  21733. configurable: true
  21734. });
  21735. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  21736. set: function (callback) {
  21737. if (this._onAfterCameraRenderObserver) {
  21738. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  21739. }
  21740. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  21741. },
  21742. enumerable: true,
  21743. configurable: true
  21744. });
  21745. Object.defineProperty(Scene.prototype, "gamepadManager", {
  21746. get: function () {
  21747. if (!this._gamepadManager) {
  21748. this._gamepadManager = new BABYLON.GamepadManager(this);
  21749. }
  21750. return this._gamepadManager;
  21751. },
  21752. enumerable: true,
  21753. configurable: true
  21754. });
  21755. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  21756. get: function () {
  21757. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  21758. },
  21759. enumerable: true,
  21760. configurable: true
  21761. });
  21762. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  21763. get: function () {
  21764. return this._useRightHandedSystem;
  21765. },
  21766. set: function (value) {
  21767. if (this._useRightHandedSystem === value) {
  21768. return;
  21769. }
  21770. this._useRightHandedSystem = value;
  21771. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21772. },
  21773. enumerable: true,
  21774. configurable: true
  21775. });
  21776. Scene.prototype.setStepId = function (newStepId) {
  21777. this._currentStepId = newStepId;
  21778. };
  21779. ;
  21780. Scene.prototype.getStepId = function () {
  21781. return this._currentStepId;
  21782. };
  21783. ;
  21784. Scene.prototype.getInternalStep = function () {
  21785. return this._currentInternalStep;
  21786. };
  21787. ;
  21788. Object.defineProperty(Scene.prototype, "fogEnabled", {
  21789. get: function () {
  21790. return this._fogEnabled;
  21791. },
  21792. /**
  21793. * is fog enabled on this scene.
  21794. */
  21795. set: function (value) {
  21796. if (this._fogEnabled === value) {
  21797. return;
  21798. }
  21799. this._fogEnabled = value;
  21800. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21801. },
  21802. enumerable: true,
  21803. configurable: true
  21804. });
  21805. Object.defineProperty(Scene.prototype, "fogMode", {
  21806. get: function () {
  21807. return this._fogMode;
  21808. },
  21809. set: function (value) {
  21810. if (this._fogMode === value) {
  21811. return;
  21812. }
  21813. this._fogMode = value;
  21814. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21815. },
  21816. enumerable: true,
  21817. configurable: true
  21818. });
  21819. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  21820. get: function () {
  21821. return this._shadowsEnabled;
  21822. },
  21823. set: function (value) {
  21824. if (this._shadowsEnabled === value) {
  21825. return;
  21826. }
  21827. this._shadowsEnabled = value;
  21828. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  21829. },
  21830. enumerable: true,
  21831. configurable: true
  21832. });
  21833. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  21834. get: function () {
  21835. return this._lightsEnabled;
  21836. },
  21837. set: function (value) {
  21838. if (this._lightsEnabled === value) {
  21839. return;
  21840. }
  21841. this._lightsEnabled = value;
  21842. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  21843. },
  21844. enumerable: true,
  21845. configurable: true
  21846. });
  21847. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  21848. /** The default material used on meshes when no material is affected */
  21849. get: function () {
  21850. if (!this._defaultMaterial) {
  21851. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  21852. }
  21853. return this._defaultMaterial;
  21854. },
  21855. /** The default material used on meshes when no material is affected */
  21856. set: function (value) {
  21857. this._defaultMaterial = value;
  21858. },
  21859. enumerable: true,
  21860. configurable: true
  21861. });
  21862. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  21863. get: function () {
  21864. return this._texturesEnabled;
  21865. },
  21866. set: function (value) {
  21867. if (this._texturesEnabled === value) {
  21868. return;
  21869. }
  21870. this._texturesEnabled = value;
  21871. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  21872. },
  21873. enumerable: true,
  21874. configurable: true
  21875. });
  21876. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  21877. get: function () {
  21878. return this._skeletonsEnabled;
  21879. },
  21880. set: function (value) {
  21881. if (this._skeletonsEnabled === value) {
  21882. return;
  21883. }
  21884. this._skeletonsEnabled = value;
  21885. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  21886. },
  21887. enumerable: true,
  21888. configurable: true
  21889. });
  21890. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  21891. get: function () {
  21892. if (!this._postProcessRenderPipelineManager) {
  21893. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  21894. }
  21895. return this._postProcessRenderPipelineManager;
  21896. },
  21897. enumerable: true,
  21898. configurable: true
  21899. });
  21900. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  21901. get: function () {
  21902. if (!this._mainSoundTrack) {
  21903. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  21904. }
  21905. return this._mainSoundTrack;
  21906. },
  21907. enumerable: true,
  21908. configurable: true
  21909. });
  21910. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  21911. get: function () {
  21912. return this._alternateRendering;
  21913. },
  21914. enumerable: true,
  21915. configurable: true
  21916. });
  21917. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  21918. get: function () {
  21919. return this._frustumPlanes;
  21920. },
  21921. enumerable: true,
  21922. configurable: true
  21923. });
  21924. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  21925. /**
  21926. * Gets the current geometry buffer associated to the scene.
  21927. */
  21928. get: function () {
  21929. return this._geometryBufferRenderer;
  21930. },
  21931. /**
  21932. * Sets the current geometry buffer for the scene.
  21933. */
  21934. set: function (geometryBufferRenderer) {
  21935. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  21936. this._geometryBufferRenderer = geometryBufferRenderer;
  21937. }
  21938. },
  21939. enumerable: true,
  21940. configurable: true
  21941. });
  21942. Object.defineProperty(Scene.prototype, "debugLayer", {
  21943. // Properties
  21944. get: function () {
  21945. if (!this._debugLayer) {
  21946. this._debugLayer = new BABYLON.DebugLayer(this);
  21947. }
  21948. return this._debugLayer;
  21949. },
  21950. enumerable: true,
  21951. configurable: true
  21952. });
  21953. Object.defineProperty(Scene.prototype, "workerCollisions", {
  21954. get: function () {
  21955. return this._workerCollisions;
  21956. },
  21957. set: function (enabled) {
  21958. if (!BABYLON.CollisionCoordinatorLegacy) {
  21959. return;
  21960. }
  21961. enabled = (enabled && !!Worker);
  21962. this._workerCollisions = enabled;
  21963. if (this.collisionCoordinator) {
  21964. this.collisionCoordinator.destroy();
  21965. }
  21966. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  21967. this.collisionCoordinator.init(this);
  21968. },
  21969. enumerable: true,
  21970. configurable: true
  21971. });
  21972. Object.defineProperty(Scene.prototype, "selectionOctree", {
  21973. get: function () {
  21974. return this._selectionOctree;
  21975. },
  21976. enumerable: true,
  21977. configurable: true
  21978. });
  21979. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  21980. /**
  21981. * The mesh that is currently under the pointer.
  21982. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  21983. */
  21984. get: function () {
  21985. return this._pointerOverMesh;
  21986. },
  21987. enumerable: true,
  21988. configurable: true
  21989. });
  21990. Object.defineProperty(Scene.prototype, "pointerX", {
  21991. /**
  21992. * Current on-screen X position of the pointer
  21993. * @return {number} X position of the pointer
  21994. */
  21995. get: function () {
  21996. return this._pointerX;
  21997. },
  21998. enumerable: true,
  21999. configurable: true
  22000. });
  22001. Object.defineProperty(Scene.prototype, "pointerY", {
  22002. /**
  22003. * Current on-screen Y position of the pointer
  22004. * @return {number} Y position of the pointer
  22005. */
  22006. get: function () {
  22007. return this._pointerY;
  22008. },
  22009. enumerable: true,
  22010. configurable: true
  22011. });
  22012. Scene.prototype.getCachedMaterial = function () {
  22013. return this._cachedMaterial;
  22014. };
  22015. Scene.prototype.getCachedEffect = function () {
  22016. return this._cachedEffect;
  22017. };
  22018. Scene.prototype.getCachedVisibility = function () {
  22019. return this._cachedVisibility;
  22020. };
  22021. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  22022. if (visibility === void 0) { visibility = 1; }
  22023. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  22024. };
  22025. Scene.prototype.getBoundingBoxRenderer = function () {
  22026. if (!this._boundingBoxRenderer) {
  22027. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  22028. }
  22029. return this._boundingBoxRenderer;
  22030. };
  22031. Scene.prototype.getOutlineRenderer = function () {
  22032. return this._outlineRenderer;
  22033. };
  22034. Scene.prototype.getEngine = function () {
  22035. return this._engine;
  22036. };
  22037. Scene.prototype.getTotalVertices = function () {
  22038. return this._totalVertices.current;
  22039. };
  22040. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  22041. get: function () {
  22042. return this._totalVertices;
  22043. },
  22044. enumerable: true,
  22045. configurable: true
  22046. });
  22047. Scene.prototype.getActiveIndices = function () {
  22048. return this._activeIndices.current;
  22049. };
  22050. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  22051. get: function () {
  22052. return this._activeIndices;
  22053. },
  22054. enumerable: true,
  22055. configurable: true
  22056. });
  22057. Scene.prototype.getActiveParticles = function () {
  22058. return this._activeParticles.current;
  22059. };
  22060. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  22061. get: function () {
  22062. return this._activeParticles;
  22063. },
  22064. enumerable: true,
  22065. configurable: true
  22066. });
  22067. Scene.prototype.getActiveBones = function () {
  22068. return this._activeBones.current;
  22069. };
  22070. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  22071. get: function () {
  22072. return this._activeBones;
  22073. },
  22074. enumerable: true,
  22075. configurable: true
  22076. });
  22077. // Stats
  22078. Scene.prototype.getInterFramePerfCounter = function () {
  22079. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  22080. return 0;
  22081. };
  22082. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  22083. get: function () {
  22084. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  22085. return null;
  22086. },
  22087. enumerable: true,
  22088. configurable: true
  22089. });
  22090. Scene.prototype.getLastFrameDuration = function () {
  22091. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  22092. return 0;
  22093. };
  22094. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  22095. get: function () {
  22096. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  22097. return null;
  22098. },
  22099. enumerable: true,
  22100. configurable: true
  22101. });
  22102. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  22103. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  22104. return 0;
  22105. };
  22106. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  22107. get: function () {
  22108. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  22109. return null;
  22110. },
  22111. enumerable: true,
  22112. configurable: true
  22113. });
  22114. Scene.prototype.getActiveMeshes = function () {
  22115. return this._activeMeshes;
  22116. };
  22117. Scene.prototype.getRenderTargetsDuration = function () {
  22118. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  22119. return 0;
  22120. };
  22121. Scene.prototype.getRenderDuration = function () {
  22122. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  22123. return 0;
  22124. };
  22125. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  22126. get: function () {
  22127. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  22128. return null;
  22129. },
  22130. enumerable: true,
  22131. configurable: true
  22132. });
  22133. Scene.prototype.getParticlesDuration = function () {
  22134. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  22135. return 0;
  22136. };
  22137. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  22138. get: function () {
  22139. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  22140. return null;
  22141. },
  22142. enumerable: true,
  22143. configurable: true
  22144. });
  22145. Scene.prototype.getSpritesDuration = function () {
  22146. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  22147. return 0;
  22148. };
  22149. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  22150. get: function () {
  22151. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  22152. return null;
  22153. },
  22154. enumerable: true,
  22155. configurable: true
  22156. });
  22157. Scene.prototype.getAnimationRatio = function () {
  22158. return this._animationRatio;
  22159. };
  22160. Scene.prototype.getRenderId = function () {
  22161. return this._renderId;
  22162. };
  22163. Scene.prototype.incrementRenderId = function () {
  22164. this._renderId++;
  22165. };
  22166. Scene.prototype._updatePointerPosition = function (evt) {
  22167. var canvasRect = this._engine.getRenderingCanvasClientRect();
  22168. if (!canvasRect) {
  22169. return;
  22170. }
  22171. this._pointerX = evt.clientX - canvasRect.left;
  22172. this._pointerY = evt.clientY - canvasRect.top;
  22173. this._unTranslatedPointerX = this._pointerX;
  22174. this._unTranslatedPointerY = this._pointerY;
  22175. };
  22176. Scene.prototype._createUbo = function () {
  22177. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  22178. this._sceneUbo.addUniform("viewProjection", 16);
  22179. this._sceneUbo.addUniform("view", 16);
  22180. };
  22181. Scene.prototype._createAlternateUbo = function () {
  22182. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  22183. this._alternateSceneUbo.addUniform("viewProjection", 16);
  22184. this._alternateSceneUbo.addUniform("view", 16);
  22185. };
  22186. // Pointers handling
  22187. /**
  22188. * Use this method to simulate a pointer move on a mesh
  22189. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  22190. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  22191. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  22192. */
  22193. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  22194. var evt = new PointerEvent("pointermove", pointerEventInit);
  22195. return this._processPointerMove(pickResult, evt);
  22196. };
  22197. Scene.prototype._processPointerMove = function (pickResult, evt) {
  22198. var canvas = this._engine.getRenderingCanvas();
  22199. if (!canvas) {
  22200. return this;
  22201. }
  22202. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  22203. this.setPointerOverSprite(null);
  22204. this.setPointerOverMesh(pickResult.pickedMesh);
  22205. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  22206. if (this._pointerOverMesh.actionManager.hoverCursor) {
  22207. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  22208. }
  22209. else {
  22210. canvas.style.cursor = this.hoverCursor;
  22211. }
  22212. }
  22213. else {
  22214. canvas.style.cursor = this.defaultCursor;
  22215. }
  22216. }
  22217. else {
  22218. this.setPointerOverMesh(null);
  22219. // Sprites
  22220. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  22221. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  22222. this.setPointerOverSprite(pickResult.pickedSprite);
  22223. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  22224. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  22225. }
  22226. else {
  22227. canvas.style.cursor = this.hoverCursor;
  22228. }
  22229. }
  22230. else {
  22231. this.setPointerOverSprite(null);
  22232. // Restore pointer
  22233. canvas.style.cursor = this.defaultCursor;
  22234. }
  22235. }
  22236. if (pickResult) {
  22237. if (this.onPointerMove) {
  22238. this.onPointerMove(evt, pickResult);
  22239. }
  22240. if (this.onPointerObservable.hasObservers()) {
  22241. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  22242. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22243. this.onPointerObservable.notifyObservers(pi, type);
  22244. }
  22245. }
  22246. return this;
  22247. };
  22248. /**
  22249. * Use this method to simulate a pointer down on a mesh
  22250. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  22251. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  22252. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  22253. */
  22254. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  22255. var evt = new PointerEvent("pointerdown", pointerEventInit);
  22256. return this._processPointerDown(pickResult, evt);
  22257. };
  22258. Scene.prototype._processPointerDown = function (pickResult, evt) {
  22259. var _this = this;
  22260. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  22261. this._pickedDownMesh = pickResult.pickedMesh;
  22262. var actionManager = pickResult.pickedMesh.actionManager;
  22263. if (actionManager) {
  22264. if (actionManager.hasPickTriggers) {
  22265. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22266. switch (evt.button) {
  22267. case 0:
  22268. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22269. break;
  22270. case 1:
  22271. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22272. break;
  22273. case 2:
  22274. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22275. break;
  22276. }
  22277. }
  22278. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  22279. window.setTimeout(function () {
  22280. 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);
  22281. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  22282. if (_this._totalPointersPressed !== 0 &&
  22283. ((new Date().getTime() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  22284. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  22285. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  22286. _this._startingPointerTime = 0;
  22287. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22288. }
  22289. }
  22290. }, Scene.LongPressDelay);
  22291. }
  22292. }
  22293. }
  22294. if (pickResult) {
  22295. if (this.onPointerDown) {
  22296. this.onPointerDown(evt, pickResult);
  22297. }
  22298. if (this.onPointerObservable.hasObservers()) {
  22299. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  22300. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22301. this.onPointerObservable.notifyObservers(pi, type);
  22302. }
  22303. }
  22304. return this;
  22305. };
  22306. /**
  22307. * Use this method to simulate a pointer up on a mesh
  22308. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  22309. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  22310. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  22311. */
  22312. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  22313. var evt = new PointerEvent("pointerup", pointerEventInit);
  22314. var clickInfo = new ClickInfo();
  22315. clickInfo.singleClick = true;
  22316. clickInfo.ignore = true;
  22317. return this._processPointerUp(pickResult, evt, clickInfo);
  22318. };
  22319. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  22320. if (pickResult && pickResult && pickResult.pickedMesh) {
  22321. this._pickedUpMesh = pickResult.pickedMesh;
  22322. if (this._pickedDownMesh === this._pickedUpMesh) {
  22323. if (this.onPointerPick) {
  22324. this.onPointerPick(evt, pickResult);
  22325. }
  22326. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  22327. var type = BABYLON.PointerEventTypes.POINTERPICK;
  22328. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22329. this.onPointerObservable.notifyObservers(pi, type);
  22330. }
  22331. }
  22332. if (pickResult.pickedMesh.actionManager) {
  22333. if (clickInfo.ignore) {
  22334. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22335. }
  22336. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  22337. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22338. }
  22339. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  22340. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22341. }
  22342. }
  22343. }
  22344. if (this._pickedDownMesh &&
  22345. this._pickedDownMesh.actionManager &&
  22346. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  22347. this._pickedDownMesh !== this._pickedUpMesh) {
  22348. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  22349. }
  22350. if (this.onPointerUp) {
  22351. this.onPointerUp(evt, pickResult);
  22352. }
  22353. if (this.onPointerObservable.hasObservers()) {
  22354. if (!clickInfo.ignore) {
  22355. if (!clickInfo.hasSwiped) {
  22356. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  22357. var type = BABYLON.PointerEventTypes.POINTERTAP;
  22358. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22359. this.onPointerObservable.notifyObservers(pi, type);
  22360. }
  22361. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  22362. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  22363. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22364. this.onPointerObservable.notifyObservers(pi, type);
  22365. }
  22366. }
  22367. }
  22368. else {
  22369. var type = BABYLON.PointerEventTypes.POINTERUP;
  22370. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22371. this.onPointerObservable.notifyObservers(pi, type);
  22372. }
  22373. }
  22374. return this;
  22375. };
  22376. /**
  22377. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  22378. * @param attachUp defines if you want to attach events to pointerup
  22379. * @param attachDown defines if you want to attach events to pointerdown
  22380. * @param attachMove defines if you want to attach events to pointermove
  22381. */
  22382. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  22383. var _this = this;
  22384. if (attachUp === void 0) { attachUp = true; }
  22385. if (attachDown === void 0) { attachDown = true; }
  22386. if (attachMove === void 0) { attachMove = true; }
  22387. this._initActionManager = function (act, clickInfo) {
  22388. if (!_this._meshPickProceed) {
  22389. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  22390. _this._currentPickResult = pickResult;
  22391. if (pickResult) {
  22392. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  22393. }
  22394. _this._meshPickProceed = true;
  22395. }
  22396. return act;
  22397. };
  22398. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  22399. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  22400. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  22401. btn !== _this._previousButtonPressed) {
  22402. _this._doubleClickOccured = false;
  22403. clickInfo.singleClick = true;
  22404. clickInfo.ignore = false;
  22405. cb(clickInfo, _this._currentPickResult);
  22406. }
  22407. };
  22408. this._initClickEvent = function (obs1, obs2, evt, cb) {
  22409. var clickInfo = new ClickInfo();
  22410. _this._currentPickResult = null;
  22411. var act = null;
  22412. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  22413. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  22414. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  22415. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  22416. act = _this._initActionManager(act, clickInfo);
  22417. if (act)
  22418. checkPicking = act.hasPickTriggers;
  22419. }
  22420. if (checkPicking) {
  22421. var btn = evt.button;
  22422. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  22423. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  22424. if (!clickInfo.hasSwiped) {
  22425. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  22426. if (!checkSingleClickImmediately) {
  22427. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  22428. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  22429. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  22430. act = _this._initActionManager(act, clickInfo);
  22431. if (act)
  22432. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  22433. }
  22434. }
  22435. if (checkSingleClickImmediately) {
  22436. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  22437. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  22438. btn !== _this._previousButtonPressed) {
  22439. clickInfo.singleClick = true;
  22440. cb(clickInfo, _this._currentPickResult);
  22441. }
  22442. }
  22443. else {
  22444. // wait that no double click has been raised during the double click delay
  22445. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22446. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  22447. }
  22448. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  22449. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  22450. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  22451. act = _this._initActionManager(act, clickInfo);
  22452. if (act)
  22453. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  22454. }
  22455. if (checkDoubleClick) {
  22456. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  22457. if (btn === _this._previousButtonPressed &&
  22458. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  22459. !_this._doubleClickOccured) {
  22460. // pointer has not moved for 2 clicks, it's a double click
  22461. if (!clickInfo.hasSwiped &&
  22462. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  22463. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  22464. _this._previousStartingPointerTime = 0;
  22465. _this._doubleClickOccured = true;
  22466. clickInfo.doubleClick = true;
  22467. clickInfo.ignore = false;
  22468. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  22469. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  22470. }
  22471. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22472. cb(clickInfo, _this._currentPickResult);
  22473. }
  22474. else {
  22475. _this._doubleClickOccured = false;
  22476. _this._previousStartingPointerTime = _this._startingPointerTime;
  22477. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  22478. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  22479. _this._previousButtonPressed = btn;
  22480. if (Scene.ExclusiveDoubleClickMode) {
  22481. if (_this._previousDelayedSimpleClickTimeout) {
  22482. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  22483. }
  22484. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22485. cb(clickInfo, _this._previousPickResult);
  22486. }
  22487. else {
  22488. cb(clickInfo, _this._currentPickResult);
  22489. }
  22490. }
  22491. }
  22492. else {
  22493. _this._doubleClickOccured = false;
  22494. _this._previousStartingPointerTime = _this._startingPointerTime;
  22495. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  22496. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  22497. _this._previousButtonPressed = btn;
  22498. }
  22499. }
  22500. }
  22501. }
  22502. clickInfo.ignore = true;
  22503. cb(clickInfo, _this._currentPickResult);
  22504. };
  22505. this._spritePredicate = function (sprite) {
  22506. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  22507. };
  22508. this._onPointerMove = function (evt) {
  22509. _this._updatePointerPosition(evt);
  22510. // PreObservable support
  22511. if (_this.onPrePointerObservable.hasObservers()) {
  22512. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  22513. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22514. _this.onPrePointerObservable.notifyObservers(pi, type);
  22515. if (pi.skipOnPointerObservable) {
  22516. return;
  22517. }
  22518. }
  22519. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  22520. return;
  22521. }
  22522. if (!_this.pointerMovePredicate) {
  22523. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  22524. }
  22525. // Meshes
  22526. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  22527. _this._processPointerMove(pickResult, evt);
  22528. };
  22529. this._onPointerDown = function (evt) {
  22530. _this._totalPointersPressed++;
  22531. _this._pickedDownMesh = null;
  22532. _this._meshPickProceed = false;
  22533. _this._updatePointerPosition(evt);
  22534. if (_this.preventDefaultOnPointerDown && canvas) {
  22535. evt.preventDefault();
  22536. canvas.focus();
  22537. }
  22538. // PreObservable support
  22539. if (_this.onPrePointerObservable.hasObservers()) {
  22540. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  22541. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22542. _this.onPrePointerObservable.notifyObservers(pi, type);
  22543. if (pi.skipOnPointerObservable) {
  22544. return;
  22545. }
  22546. }
  22547. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  22548. return;
  22549. }
  22550. _this._startingPointerPosition.x = _this._pointerX;
  22551. _this._startingPointerPosition.y = _this._pointerY;
  22552. _this._startingPointerTime = new Date().getTime();
  22553. if (!_this.pointerDownPredicate) {
  22554. _this.pointerDownPredicate = function (mesh) {
  22555. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  22556. };
  22557. }
  22558. // Meshes
  22559. _this._pickedDownMesh = null;
  22560. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  22561. _this._processPointerDown(pickResult, evt);
  22562. // Sprites
  22563. _this._pickedDownSprite = null;
  22564. if (_this.spriteManagers.length > 0) {
  22565. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  22566. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  22567. if (pickResult.pickedSprite.actionManager) {
  22568. _this._pickedDownSprite = pickResult.pickedSprite;
  22569. switch (evt.button) {
  22570. case 0:
  22571. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22572. break;
  22573. case 1:
  22574. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22575. break;
  22576. case 2:
  22577. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22578. break;
  22579. }
  22580. if (pickResult.pickedSprite.actionManager) {
  22581. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22582. }
  22583. }
  22584. }
  22585. }
  22586. };
  22587. this._onPointerUp = function (evt) {
  22588. if (_this._totalPointersPressed === 0) {
  22589. return; // So we need to test it the pointer down was pressed before.
  22590. }
  22591. _this._totalPointersPressed--;
  22592. _this._pickedUpMesh = null;
  22593. _this._meshPickProceed = false;
  22594. _this._updatePointerPosition(evt);
  22595. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  22596. // PreObservable support
  22597. if (_this.onPrePointerObservable.hasObservers()) {
  22598. if (!clickInfo.ignore) {
  22599. if (!clickInfo.hasSwiped) {
  22600. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  22601. var type = BABYLON.PointerEventTypes.POINTERTAP;
  22602. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22603. _this.onPrePointerObservable.notifyObservers(pi, type);
  22604. if (pi.skipOnPointerObservable) {
  22605. return;
  22606. }
  22607. }
  22608. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  22609. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  22610. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22611. _this.onPrePointerObservable.notifyObservers(pi, type);
  22612. if (pi.skipOnPointerObservable) {
  22613. return;
  22614. }
  22615. }
  22616. }
  22617. }
  22618. else {
  22619. var type = BABYLON.PointerEventTypes.POINTERUP;
  22620. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22621. _this.onPrePointerObservable.notifyObservers(pi, type);
  22622. if (pi.skipOnPointerObservable) {
  22623. return;
  22624. }
  22625. }
  22626. }
  22627. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  22628. return;
  22629. }
  22630. if (!_this.pointerUpPredicate) {
  22631. _this.pointerUpPredicate = function (mesh) {
  22632. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  22633. };
  22634. }
  22635. // Meshes
  22636. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  22637. _this._initActionManager(null, clickInfo);
  22638. }
  22639. if (!pickResult) {
  22640. pickResult = _this._currentPickResult;
  22641. }
  22642. _this._processPointerUp(pickResult, evt, clickInfo);
  22643. // Sprites
  22644. if (_this.spriteManagers.length > 0) {
  22645. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  22646. if (spritePickResult) {
  22647. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  22648. if (spritePickResult.pickedSprite.actionManager) {
  22649. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  22650. if (spritePickResult.pickedSprite.actionManager) {
  22651. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  22652. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  22653. }
  22654. }
  22655. }
  22656. }
  22657. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  22658. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  22659. }
  22660. }
  22661. }
  22662. _this._previousPickResult = _this._currentPickResult;
  22663. });
  22664. };
  22665. this._onKeyDown = function (evt) {
  22666. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  22667. if (_this.onPreKeyboardObservable.hasObservers()) {
  22668. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  22669. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  22670. if (pi.skipOnPointerObservable) {
  22671. return;
  22672. }
  22673. }
  22674. if (_this.onKeyboardObservable.hasObservers()) {
  22675. var pi = new BABYLON.KeyboardInfo(type, evt);
  22676. _this.onKeyboardObservable.notifyObservers(pi, type);
  22677. }
  22678. if (_this.actionManager) {
  22679. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  22680. }
  22681. };
  22682. this._onKeyUp = function (evt) {
  22683. var type = BABYLON.KeyboardEventTypes.KEYUP;
  22684. if (_this.onPreKeyboardObservable.hasObservers()) {
  22685. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  22686. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  22687. if (pi.skipOnPointerObservable) {
  22688. return;
  22689. }
  22690. }
  22691. if (_this.onKeyboardObservable.hasObservers()) {
  22692. var pi = new BABYLON.KeyboardInfo(type, evt);
  22693. _this.onKeyboardObservable.notifyObservers(pi, type);
  22694. }
  22695. if (_this.actionManager) {
  22696. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  22697. }
  22698. };
  22699. var engine = this.getEngine();
  22700. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  22701. if (!canvas) {
  22702. return;
  22703. }
  22704. canvas.addEventListener("keydown", _this._onKeyDown, false);
  22705. canvas.addEventListener("keyup", _this._onKeyUp, false);
  22706. });
  22707. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  22708. if (!canvas) {
  22709. return;
  22710. }
  22711. canvas.removeEventListener("keydown", _this._onKeyDown);
  22712. canvas.removeEventListener("keyup", _this._onKeyUp);
  22713. });
  22714. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  22715. var canvas = this._engine.getRenderingCanvas();
  22716. if (!canvas) {
  22717. return;
  22718. }
  22719. if (attachMove) {
  22720. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  22721. // Wheel
  22722. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  22723. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  22724. }
  22725. if (attachDown) {
  22726. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  22727. }
  22728. if (attachUp) {
  22729. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  22730. }
  22731. canvas.tabIndex = 1;
  22732. };
  22733. Scene.prototype.detachControl = function () {
  22734. var engine = this.getEngine();
  22735. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  22736. var canvas = engine.getRenderingCanvas();
  22737. if (!canvas) {
  22738. return;
  22739. }
  22740. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  22741. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  22742. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  22743. if (this._onCanvasBlurObserver) {
  22744. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  22745. }
  22746. if (this._onCanvasFocusObserver) {
  22747. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  22748. }
  22749. // Wheel
  22750. canvas.removeEventListener('mousewheel', this._onPointerMove);
  22751. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  22752. // Keyboard
  22753. canvas.removeEventListener("keydown", this._onKeyDown);
  22754. canvas.removeEventListener("keyup", this._onKeyUp);
  22755. // Observables
  22756. this.onKeyboardObservable.clear();
  22757. this.onPreKeyboardObservable.clear();
  22758. this.onPointerObservable.clear();
  22759. this.onPrePointerObservable.clear();
  22760. };
  22761. /**
  22762. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  22763. * Delay loaded resources are not taking in account
  22764. * @return true if all required resources are ready
  22765. */
  22766. Scene.prototype.isReady = function () {
  22767. if (this._isDisposed) {
  22768. return false;
  22769. }
  22770. if (this._pendingData.length > 0) {
  22771. return false;
  22772. }
  22773. var index;
  22774. var engine = this.getEngine();
  22775. // Geometries
  22776. for (index = 0; index < this._geometries.length; index++) {
  22777. var geometry = this._geometries[index];
  22778. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  22779. return false;
  22780. }
  22781. }
  22782. // Meshes
  22783. for (index = 0; index < this.meshes.length; index++) {
  22784. var mesh = this.meshes[index];
  22785. if (!mesh.isEnabled()) {
  22786. continue;
  22787. }
  22788. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  22789. continue;
  22790. }
  22791. if (!mesh.isReady(true)) {
  22792. return false;
  22793. }
  22794. // Effect layers
  22795. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  22796. for (var _i = 0, _a = this.effectLayers; _i < _a.length; _i++) {
  22797. var layer = _a[_i];
  22798. if (!layer.hasMesh(mesh)) {
  22799. continue;
  22800. }
  22801. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  22802. var subMesh = _c[_b];
  22803. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  22804. return false;
  22805. }
  22806. }
  22807. }
  22808. }
  22809. return true;
  22810. };
  22811. Scene.prototype.resetCachedMaterial = function () {
  22812. this._cachedMaterial = null;
  22813. this._cachedEffect = null;
  22814. this._cachedVisibility = null;
  22815. };
  22816. Scene.prototype.registerBeforeRender = function (func) {
  22817. this.onBeforeRenderObservable.add(func);
  22818. };
  22819. Scene.prototype.unregisterBeforeRender = function (func) {
  22820. this.onBeforeRenderObservable.removeCallback(func);
  22821. };
  22822. Scene.prototype.registerAfterRender = function (func) {
  22823. this.onAfterRenderObservable.add(func);
  22824. };
  22825. Scene.prototype.unregisterAfterRender = function (func) {
  22826. this.onAfterRenderObservable.removeCallback(func);
  22827. };
  22828. Scene.prototype._executeOnceBeforeRender = function (func) {
  22829. var _this = this;
  22830. var execFunc = function () {
  22831. func();
  22832. setTimeout(function () {
  22833. _this.unregisterBeforeRender(execFunc);
  22834. });
  22835. };
  22836. this.registerBeforeRender(execFunc);
  22837. };
  22838. /**
  22839. * The provided function will run before render once and will be disposed afterwards.
  22840. * A timeout delay can be provided so that the function will be executed in N ms.
  22841. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  22842. * @param func The function to be executed.
  22843. * @param timeout optional delay in ms
  22844. */
  22845. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  22846. var _this = this;
  22847. if (timeout !== undefined) {
  22848. setTimeout(function () {
  22849. _this._executeOnceBeforeRender(func);
  22850. }, timeout);
  22851. }
  22852. else {
  22853. this._executeOnceBeforeRender(func);
  22854. }
  22855. };
  22856. Scene.prototype._addPendingData = function (data) {
  22857. this._pendingData.push(data);
  22858. };
  22859. Scene.prototype._removePendingData = function (data) {
  22860. var wasLoading = this.isLoading;
  22861. var index = this._pendingData.indexOf(data);
  22862. if (index !== -1) {
  22863. this._pendingData.splice(index, 1);
  22864. }
  22865. if (wasLoading && !this.isLoading) {
  22866. this.onDataLoadedObservable.notifyObservers(this);
  22867. }
  22868. };
  22869. Scene.prototype.getWaitingItemsCount = function () {
  22870. return this._pendingData.length;
  22871. };
  22872. Object.defineProperty(Scene.prototype, "isLoading", {
  22873. get: function () {
  22874. return this._pendingData.length > 0;
  22875. },
  22876. enumerable: true,
  22877. configurable: true
  22878. });
  22879. /**
  22880. * Registers a function to be executed when the scene is ready.
  22881. * @param {Function} func - the function to be executed.
  22882. */
  22883. Scene.prototype.executeWhenReady = function (func) {
  22884. var _this = this;
  22885. this.onReadyObservable.add(func);
  22886. if (this._executeWhenReadyTimeoutId !== -1) {
  22887. return;
  22888. }
  22889. this._executeWhenReadyTimeoutId = setTimeout(function () {
  22890. _this._checkIsReady();
  22891. }, 150);
  22892. };
  22893. /**
  22894. * Returns a promise that resolves when the scene is ready.
  22895. * @returns A promise that resolves when the scene is ready.
  22896. */
  22897. Scene.prototype.whenReadyAsync = function () {
  22898. var _this = this;
  22899. return new Promise(function (resolve) {
  22900. _this.executeWhenReady(function () {
  22901. resolve();
  22902. });
  22903. });
  22904. };
  22905. Scene.prototype._checkIsReady = function () {
  22906. var _this = this;
  22907. if (this.isReady()) {
  22908. this.onReadyObservable.notifyObservers(this);
  22909. this.onReadyObservable.clear();
  22910. this._executeWhenReadyTimeoutId = -1;
  22911. return;
  22912. }
  22913. this._executeWhenReadyTimeoutId = setTimeout(function () {
  22914. _this._checkIsReady();
  22915. }, 150);
  22916. };
  22917. // Animations
  22918. /**
  22919. * Will start the animation sequence of a given target
  22920. * @param target - the target
  22921. * @param {number} from - from which frame should animation start
  22922. * @param {number} to - till which frame should animation run.
  22923. * @param {boolean} [loop] - should the animation loop
  22924. * @param {number} [speedRatio] - the speed in which to run the animation
  22925. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  22926. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  22927. * Returns {BABYLON.Animatable} the animatable object created for this animation
  22928. * See BABYLON.Animatable
  22929. */
  22930. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  22931. if (speedRatio === void 0) { speedRatio = 1.0; }
  22932. if (from > to && speedRatio > 0) {
  22933. speedRatio *= -1;
  22934. }
  22935. this.stopAnimation(target);
  22936. if (!animatable) {
  22937. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  22938. }
  22939. // Local animations
  22940. if (target.animations) {
  22941. animatable.appendAnimations(target, target.animations);
  22942. }
  22943. // Children animations
  22944. if (target.getAnimatables) {
  22945. var animatables = target.getAnimatables();
  22946. for (var index = 0; index < animatables.length; index++) {
  22947. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  22948. }
  22949. }
  22950. animatable.reset();
  22951. return animatable;
  22952. };
  22953. /**
  22954. * Begin a new animation on a given node
  22955. * @param {BABYLON.Node} node defines the root node where the animation will take place
  22956. * @param {BABYLON.Animation[]} defines the list of animations to start
  22957. * @param {number} from defines the initial value
  22958. * @param {number} to defines the final value
  22959. * @param {boolean} loop defines if you want animation to loop (off by default)
  22960. * @param {number} speedRatio defines the speed ratio to apply to all animations
  22961. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  22962. * @returns the list of created animatables
  22963. */
  22964. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  22965. if (speedRatio === undefined) {
  22966. speedRatio = 1.0;
  22967. }
  22968. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  22969. return animatable;
  22970. };
  22971. /**
  22972. * Begin a new animation on a given node and its hierarchy
  22973. * @param {BABYLON.Node} node defines the root node where the animation will take place
  22974. * @param {boolean} directDescendantsOnly if true only direct descendants will be used, if false direct and also indirect (children of children, an so on in a recursive manner) descendants will be used.
  22975. * @param {BABYLON.Animation[]} defines the list of animations to start
  22976. * @param {number} from defines the initial value
  22977. * @param {number} to defines the final value
  22978. * @param {boolean} loop defines if you want animation to loop (off by default)
  22979. * @param {number} speedRatio defines the speed ratio to apply to all animations
  22980. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  22981. * @returns the list of animatables created for all nodes
  22982. */
  22983. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  22984. var children = target.getDescendants(directDescendantsOnly);
  22985. var result = [];
  22986. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  22987. var child = children_1[_i];
  22988. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  22989. }
  22990. return result;
  22991. };
  22992. Scene.prototype.getAnimatableByTarget = function (target) {
  22993. for (var index = 0; index < this._activeAnimatables.length; index++) {
  22994. if (this._activeAnimatables[index].target === target) {
  22995. return this._activeAnimatables[index];
  22996. }
  22997. }
  22998. return null;
  22999. };
  23000. Object.defineProperty(Scene.prototype, "animatables", {
  23001. get: function () {
  23002. return this._activeAnimatables;
  23003. },
  23004. enumerable: true,
  23005. configurable: true
  23006. });
  23007. /**
  23008. * Will stop the animation of the given target
  23009. * @param target - the target
  23010. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  23011. * @see beginAnimation
  23012. */
  23013. Scene.prototype.stopAnimation = function (target, animationName) {
  23014. var animatable = this.getAnimatableByTarget(target);
  23015. if (animatable) {
  23016. animatable.stop(animationName);
  23017. }
  23018. };
  23019. /**
  23020. * Stops and removes all animations that have been applied to the scene
  23021. */
  23022. Scene.prototype.stopAllAnimations = function () {
  23023. if (this._activeAnimatables) {
  23024. for (var i = 0; i < this._activeAnimatables.length; i++) {
  23025. this._activeAnimatables[i].stop();
  23026. }
  23027. this._activeAnimatables = [];
  23028. }
  23029. };
  23030. Scene.prototype._animate = function () {
  23031. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  23032. return;
  23033. }
  23034. // Getting time
  23035. var now = BABYLON.Tools.Now;
  23036. if (!this._animationTimeLast) {
  23037. if (this._pendingData.length > 0) {
  23038. return;
  23039. }
  23040. this._animationTimeLast = now;
  23041. }
  23042. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  23043. this._animationTime += deltaTime;
  23044. this._animationTimeLast = now;
  23045. for (var index = 0; index < this._activeAnimatables.length; index++) {
  23046. this._activeAnimatables[index]._animate(this._animationTime);
  23047. }
  23048. };
  23049. // Matrix
  23050. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  23051. this._useAlternateCameraConfiguration = active;
  23052. };
  23053. Scene.prototype.getViewMatrix = function () {
  23054. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  23055. };
  23056. Scene.prototype.getProjectionMatrix = function () {
  23057. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  23058. };
  23059. Scene.prototype.getTransformMatrix = function () {
  23060. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  23061. };
  23062. Scene.prototype.setTransformMatrix = function (view, projection) {
  23063. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  23064. return;
  23065. }
  23066. this._viewUpdateFlag = view.updateFlag;
  23067. this._projectionUpdateFlag = projection.updateFlag;
  23068. this._viewMatrix = view;
  23069. this._projectionMatrix = projection;
  23070. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  23071. // Update frustum
  23072. if (!this._frustumPlanes) {
  23073. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  23074. }
  23075. else {
  23076. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  23077. }
  23078. if (this.activeCamera && this.activeCamera._alternateCamera) {
  23079. var otherCamera = this.activeCamera._alternateCamera;
  23080. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  23081. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  23082. }
  23083. if (this._sceneUbo.useUbo) {
  23084. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  23085. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  23086. this._sceneUbo.update();
  23087. }
  23088. };
  23089. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  23090. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  23091. return;
  23092. }
  23093. this._alternateViewUpdateFlag = view.updateFlag;
  23094. this._alternateProjectionUpdateFlag = projection.updateFlag;
  23095. this._alternateViewMatrix = view;
  23096. this._alternateProjectionMatrix = projection;
  23097. if (!this._alternateTransformMatrix) {
  23098. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  23099. }
  23100. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  23101. if (!this._alternateSceneUbo) {
  23102. this._createAlternateUbo();
  23103. }
  23104. if (this._alternateSceneUbo.useUbo) {
  23105. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  23106. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  23107. this._alternateSceneUbo.update();
  23108. }
  23109. };
  23110. Scene.prototype.getSceneUniformBuffer = function () {
  23111. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  23112. };
  23113. // Methods
  23114. Scene.prototype.getUniqueId = function () {
  23115. var result = Scene._uniqueIdCounter;
  23116. Scene._uniqueIdCounter++;
  23117. return result;
  23118. };
  23119. Scene.prototype.addMesh = function (newMesh) {
  23120. this.meshes.push(newMesh);
  23121. //notify the collision coordinator
  23122. if (this.collisionCoordinator) {
  23123. this.collisionCoordinator.onMeshAdded(newMesh);
  23124. }
  23125. newMesh._resyncLightSources();
  23126. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  23127. };
  23128. Scene.prototype.removeMesh = function (toRemove) {
  23129. var index = this.meshes.indexOf(toRemove);
  23130. if (index !== -1) {
  23131. // Remove from the scene if mesh found
  23132. this.meshes.splice(index, 1);
  23133. }
  23134. this.onMeshRemovedObservable.notifyObservers(toRemove);
  23135. return index;
  23136. };
  23137. Scene.prototype.addTransformNode = function (newTransformNode) {
  23138. this.transformNodes.push(newTransformNode);
  23139. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  23140. };
  23141. Scene.prototype.removeTransformNode = function (toRemove) {
  23142. var index = this.transformNodes.indexOf(toRemove);
  23143. if (index !== -1) {
  23144. // Remove from the scene if found
  23145. this.transformNodes.splice(index, 1);
  23146. }
  23147. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  23148. return index;
  23149. };
  23150. Scene.prototype.removeSkeleton = function (toRemove) {
  23151. var index = this.skeletons.indexOf(toRemove);
  23152. if (index !== -1) {
  23153. // Remove from the scene if found
  23154. this.skeletons.splice(index, 1);
  23155. }
  23156. return index;
  23157. };
  23158. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  23159. var index = this.morphTargetManagers.indexOf(toRemove);
  23160. if (index !== -1) {
  23161. // Remove from the scene if found
  23162. this.morphTargetManagers.splice(index, 1);
  23163. }
  23164. return index;
  23165. };
  23166. Scene.prototype.removeLight = function (toRemove) {
  23167. var index = this.lights.indexOf(toRemove);
  23168. if (index !== -1) {
  23169. // Remove from meshes
  23170. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  23171. var mesh = _a[_i];
  23172. mesh._removeLightSource(toRemove);
  23173. }
  23174. // Remove from the scene if mesh found
  23175. this.lights.splice(index, 1);
  23176. this.sortLightsByPriority();
  23177. }
  23178. this.onLightRemovedObservable.notifyObservers(toRemove);
  23179. return index;
  23180. };
  23181. Scene.prototype.removeCamera = function (toRemove) {
  23182. var index = this.cameras.indexOf(toRemove);
  23183. if (index !== -1) {
  23184. // Remove from the scene if mesh found
  23185. this.cameras.splice(index, 1);
  23186. }
  23187. // Remove from activeCameras
  23188. var index2 = this.activeCameras.indexOf(toRemove);
  23189. if (index2 !== -1) {
  23190. // Remove from the scene if mesh found
  23191. this.activeCameras.splice(index2, 1);
  23192. }
  23193. // Reset the activeCamera
  23194. if (this.activeCamera === toRemove) {
  23195. if (this.cameras.length > 0) {
  23196. this.activeCamera = this.cameras[0];
  23197. }
  23198. else {
  23199. this.activeCamera = null;
  23200. }
  23201. }
  23202. this.onCameraRemovedObservable.notifyObservers(toRemove);
  23203. return index;
  23204. };
  23205. Scene.prototype.removeParticleSystem = function (toRemove) {
  23206. var index = this.particleSystems.indexOf(toRemove);
  23207. if (index !== -1) {
  23208. this.particleSystems.splice(index, 1);
  23209. }
  23210. return index;
  23211. };
  23212. ;
  23213. Scene.prototype.removeAnimation = function (toRemove) {
  23214. var index = this.animations.indexOf(toRemove);
  23215. if (index !== -1) {
  23216. this.animations.splice(index, 1);
  23217. }
  23218. return index;
  23219. };
  23220. ;
  23221. Scene.prototype.removeMultiMaterial = function (toRemove) {
  23222. var index = this.multiMaterials.indexOf(toRemove);
  23223. if (index !== -1) {
  23224. this.multiMaterials.splice(index, 1);
  23225. }
  23226. return index;
  23227. };
  23228. ;
  23229. Scene.prototype.removeMaterial = function (toRemove) {
  23230. var index = this.materials.indexOf(toRemove);
  23231. if (index !== -1) {
  23232. this.materials.splice(index, 1);
  23233. }
  23234. return index;
  23235. };
  23236. ;
  23237. Scene.prototype.removeLensFlareSystem = function (toRemove) {
  23238. var index = this.lensFlareSystems.indexOf(toRemove);
  23239. if (index !== -1) {
  23240. this.lensFlareSystems.splice(index, 1);
  23241. }
  23242. return index;
  23243. };
  23244. ;
  23245. Scene.prototype.removeActionManager = function (toRemove) {
  23246. var index = this._actionManagers.indexOf(toRemove);
  23247. if (index !== -1) {
  23248. this._actionManagers.splice(index, 1);
  23249. }
  23250. return index;
  23251. };
  23252. ;
  23253. Scene.prototype.addLight = function (newLight) {
  23254. this.lights.push(newLight);
  23255. this.sortLightsByPriority();
  23256. // Add light to all meshes (To support if the light is removed and then readded)
  23257. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  23258. var mesh = _a[_i];
  23259. if (mesh._lightSources.indexOf(newLight) === -1) {
  23260. mesh._lightSources.push(newLight);
  23261. mesh._resyncLightSources();
  23262. }
  23263. }
  23264. this.onNewLightAddedObservable.notifyObservers(newLight);
  23265. };
  23266. Scene.prototype.sortLightsByPriority = function () {
  23267. if (this.requireLightSorting) {
  23268. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  23269. }
  23270. };
  23271. Scene.prototype.addCamera = function (newCamera) {
  23272. this.cameras.push(newCamera);
  23273. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  23274. };
  23275. Scene.prototype.addSkeleton = function (newSkeleton) {
  23276. this.skeletons.push(newSkeleton);
  23277. };
  23278. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  23279. this.particleSystems.push(newParticleSystem);
  23280. };
  23281. Scene.prototype.addAnimation = function (newAnimation) {
  23282. this.animations.push(newAnimation);
  23283. };
  23284. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  23285. this.multiMaterials.push(newMultiMaterial);
  23286. };
  23287. Scene.prototype.addMaterial = function (newMaterial) {
  23288. this.materials.push(newMaterial);
  23289. };
  23290. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  23291. this.morphTargetManagers.push(newMorphTargetManager);
  23292. };
  23293. Scene.prototype.addGeometry = function (newGeometrie) {
  23294. this._geometries.push(newGeometrie);
  23295. };
  23296. Scene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  23297. this.lensFlareSystems.push(newLensFlareSystem);
  23298. };
  23299. Scene.prototype.addActionManager = function (newActionManager) {
  23300. this._actionManagers.push(newActionManager);
  23301. };
  23302. /**
  23303. * Switch active camera
  23304. * @param {Camera} newCamera - new active camera
  23305. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  23306. */
  23307. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  23308. if (attachControl === void 0) { attachControl = true; }
  23309. var canvas = this._engine.getRenderingCanvas();
  23310. if (!canvas) {
  23311. return;
  23312. }
  23313. if (this.activeCamera) {
  23314. this.activeCamera.detachControl(canvas);
  23315. }
  23316. this.activeCamera = newCamera;
  23317. if (attachControl) {
  23318. newCamera.attachControl(canvas);
  23319. }
  23320. };
  23321. /**
  23322. * sets the active camera of the scene using its ID
  23323. * @param {string} id - the camera's ID
  23324. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  23325. * @see activeCamera
  23326. */
  23327. Scene.prototype.setActiveCameraByID = function (id) {
  23328. var camera = this.getCameraByID(id);
  23329. if (camera) {
  23330. this.activeCamera = camera;
  23331. return camera;
  23332. }
  23333. return null;
  23334. };
  23335. /**
  23336. * sets the active camera of the scene using its name
  23337. * @param {string} name - the camera's name
  23338. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  23339. * @see activeCamera
  23340. */
  23341. Scene.prototype.setActiveCameraByName = function (name) {
  23342. var camera = this.getCameraByName(name);
  23343. if (camera) {
  23344. this.activeCamera = camera;
  23345. return camera;
  23346. }
  23347. return null;
  23348. };
  23349. /**
  23350. * get an animation group using its name
  23351. * @param {string} the material's name
  23352. * @return {BABYLON.AnimationGroup|null} the animation group or null if none found.
  23353. */
  23354. Scene.prototype.getAnimationGroupByName = function (name) {
  23355. for (var index = 0; index < this.animationGroups.length; index++) {
  23356. if (this.animationGroups[index].name === name) {
  23357. return this.animationGroups[index];
  23358. }
  23359. }
  23360. return null;
  23361. };
  23362. /**
  23363. * get a material using its id
  23364. * @param {string} the material's ID
  23365. * @return {BABYLON.Material|null} the material or null if none found.
  23366. */
  23367. Scene.prototype.getMaterialByID = function (id) {
  23368. for (var index = 0; index < this.materials.length; index++) {
  23369. if (this.materials[index].id === id) {
  23370. return this.materials[index];
  23371. }
  23372. }
  23373. return null;
  23374. };
  23375. /**
  23376. * get a material using its name
  23377. * @param {string} the material's name
  23378. * @return {BABYLON.Material|null} the material or null if none found.
  23379. */
  23380. Scene.prototype.getMaterialByName = function (name) {
  23381. for (var index = 0; index < this.materials.length; index++) {
  23382. if (this.materials[index].name === name) {
  23383. return this.materials[index];
  23384. }
  23385. }
  23386. return null;
  23387. };
  23388. Scene.prototype.getLensFlareSystemByName = function (name) {
  23389. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  23390. if (this.lensFlareSystems[index].name === name) {
  23391. return this.lensFlareSystems[index];
  23392. }
  23393. }
  23394. return null;
  23395. };
  23396. Scene.prototype.getLensFlareSystemByID = function (id) {
  23397. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  23398. if (this.lensFlareSystems[index].id === id) {
  23399. return this.lensFlareSystems[index];
  23400. }
  23401. }
  23402. return null;
  23403. };
  23404. Scene.prototype.getCameraByID = function (id) {
  23405. for (var index = 0; index < this.cameras.length; index++) {
  23406. if (this.cameras[index].id === id) {
  23407. return this.cameras[index];
  23408. }
  23409. }
  23410. return null;
  23411. };
  23412. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  23413. for (var index = 0; index < this.cameras.length; index++) {
  23414. if (this.cameras[index].uniqueId === uniqueId) {
  23415. return this.cameras[index];
  23416. }
  23417. }
  23418. return null;
  23419. };
  23420. /**
  23421. * get a camera using its name
  23422. * @param {string} the camera's name
  23423. * @return {BABYLON.Camera|null} the camera or null if none found.
  23424. */
  23425. Scene.prototype.getCameraByName = function (name) {
  23426. for (var index = 0; index < this.cameras.length; index++) {
  23427. if (this.cameras[index].name === name) {
  23428. return this.cameras[index];
  23429. }
  23430. }
  23431. return null;
  23432. };
  23433. /**
  23434. * get a bone using its id
  23435. * @param {string} the bone's id
  23436. * @return {BABYLON.Bone|null} the bone or null if not found
  23437. */
  23438. Scene.prototype.getBoneByID = function (id) {
  23439. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  23440. var skeleton = this.skeletons[skeletonIndex];
  23441. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  23442. if (skeleton.bones[boneIndex].id === id) {
  23443. return skeleton.bones[boneIndex];
  23444. }
  23445. }
  23446. }
  23447. return null;
  23448. };
  23449. /**
  23450. * get a bone using its id
  23451. * @param {string} the bone's name
  23452. * @return {BABYLON.Bone|null} the bone or null if not found
  23453. */
  23454. Scene.prototype.getBoneByName = function (name) {
  23455. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  23456. var skeleton = this.skeletons[skeletonIndex];
  23457. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  23458. if (skeleton.bones[boneIndex].name === name) {
  23459. return skeleton.bones[boneIndex];
  23460. }
  23461. }
  23462. }
  23463. return null;
  23464. };
  23465. /**
  23466. * get a light node using its name
  23467. * @param {string} the light's name
  23468. * @return {BABYLON.Light|null} the light or null if none found.
  23469. */
  23470. Scene.prototype.getLightByName = function (name) {
  23471. for (var index = 0; index < this.lights.length; index++) {
  23472. if (this.lights[index].name === name) {
  23473. return this.lights[index];
  23474. }
  23475. }
  23476. return null;
  23477. };
  23478. /**
  23479. * get a light node using its ID
  23480. * @param {string} the light's id
  23481. * @return {BABYLON.Light|null} the light or null if none found.
  23482. */
  23483. Scene.prototype.getLightByID = function (id) {
  23484. for (var index = 0; index < this.lights.length; index++) {
  23485. if (this.lights[index].id === id) {
  23486. return this.lights[index];
  23487. }
  23488. }
  23489. return null;
  23490. };
  23491. /**
  23492. * get a light node using its scene-generated unique ID
  23493. * @param {number} the light's unique id
  23494. * @return {BABYLON.Light|null} the light or null if none found.
  23495. */
  23496. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  23497. for (var index = 0; index < this.lights.length; index++) {
  23498. if (this.lights[index].uniqueId === uniqueId) {
  23499. return this.lights[index];
  23500. }
  23501. }
  23502. return null;
  23503. };
  23504. /**
  23505. * get a particle system by id
  23506. * @param id {number} the particle system id
  23507. * @return {BABYLON.IParticleSystem|null} the corresponding system or null if none found.
  23508. */
  23509. Scene.prototype.getParticleSystemByID = function (id) {
  23510. for (var index = 0; index < this.particleSystems.length; index++) {
  23511. if (this.particleSystems[index].id === id) {
  23512. return this.particleSystems[index];
  23513. }
  23514. }
  23515. return null;
  23516. };
  23517. /**
  23518. * get a geometry using its ID
  23519. * @param {string} the geometry's id
  23520. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  23521. */
  23522. Scene.prototype.getGeometryByID = function (id) {
  23523. for (var index = 0; index < this._geometries.length; index++) {
  23524. if (this._geometries[index].id === id) {
  23525. return this._geometries[index];
  23526. }
  23527. }
  23528. return null;
  23529. };
  23530. /**
  23531. * add a new geometry to this scene.
  23532. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  23533. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  23534. * @return {boolean} was the geometry added or not
  23535. */
  23536. Scene.prototype.pushGeometry = function (geometry, force) {
  23537. if (!force && this.getGeometryByID(geometry.id)) {
  23538. return false;
  23539. }
  23540. this._geometries.push(geometry);
  23541. //notify the collision coordinator
  23542. if (this.collisionCoordinator) {
  23543. this.collisionCoordinator.onGeometryAdded(geometry);
  23544. }
  23545. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  23546. return true;
  23547. };
  23548. /**
  23549. * Removes an existing geometry
  23550. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  23551. * @return {boolean} was the geometry removed or not
  23552. */
  23553. Scene.prototype.removeGeometry = function (geometry) {
  23554. var index = this._geometries.indexOf(geometry);
  23555. if (index > -1) {
  23556. this._geometries.splice(index, 1);
  23557. //notify the collision coordinator
  23558. if (this.collisionCoordinator) {
  23559. this.collisionCoordinator.onGeometryDeleted(geometry);
  23560. }
  23561. this.onGeometryRemovedObservable.notifyObservers(geometry);
  23562. return true;
  23563. }
  23564. return false;
  23565. };
  23566. Scene.prototype.getGeometries = function () {
  23567. return this._geometries;
  23568. };
  23569. /**
  23570. * Get the first added mesh found of a given ID
  23571. * @param {string} id - the id to search for
  23572. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  23573. */
  23574. Scene.prototype.getMeshByID = function (id) {
  23575. for (var index = 0; index < this.meshes.length; index++) {
  23576. if (this.meshes[index].id === id) {
  23577. return this.meshes[index];
  23578. }
  23579. }
  23580. return null;
  23581. };
  23582. Scene.prototype.getMeshesByID = function (id) {
  23583. return this.meshes.filter(function (m) {
  23584. return m.id === id;
  23585. });
  23586. };
  23587. /**
  23588. * Get the first added transform node found of a given ID
  23589. * @param {string} id - the id to search for
  23590. * @return {BABYLON.TransformNode|null} the transform node found or null if not found at all.
  23591. */
  23592. Scene.prototype.getTransformNodeByID = function (id) {
  23593. for (var index = 0; index < this.transformNodes.length; index++) {
  23594. if (this.transformNodes[index].id === id) {
  23595. return this.transformNodes[index];
  23596. }
  23597. }
  23598. return null;
  23599. };
  23600. Scene.prototype.getTransformNodesByID = function (id) {
  23601. return this.transformNodes.filter(function (m) {
  23602. return m.id === id;
  23603. });
  23604. };
  23605. /**
  23606. * Get a mesh with its auto-generated unique id
  23607. * @param {number} uniqueId - the unique id to search for
  23608. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  23609. */
  23610. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  23611. for (var index = 0; index < this.meshes.length; index++) {
  23612. if (this.meshes[index].uniqueId === uniqueId) {
  23613. return this.meshes[index];
  23614. }
  23615. }
  23616. return null;
  23617. };
  23618. /**
  23619. * Get a the last added mesh found of a given ID
  23620. * @param {string} id - the id to search for
  23621. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  23622. */
  23623. Scene.prototype.getLastMeshByID = function (id) {
  23624. for (var index = this.meshes.length - 1; index >= 0; index--) {
  23625. if (this.meshes[index].id === id) {
  23626. return this.meshes[index];
  23627. }
  23628. }
  23629. return null;
  23630. };
  23631. /**
  23632. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  23633. * @param {string} id - the id to search for
  23634. * @return {BABYLON.Node|null} the node found or null if not found at all.
  23635. */
  23636. Scene.prototype.getLastEntryByID = function (id) {
  23637. var index;
  23638. for (index = this.meshes.length - 1; index >= 0; index--) {
  23639. if (this.meshes[index].id === id) {
  23640. return this.meshes[index];
  23641. }
  23642. }
  23643. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  23644. if (this.transformNodes[index].id === id) {
  23645. return this.transformNodes[index];
  23646. }
  23647. }
  23648. for (index = this.cameras.length - 1; index >= 0; index--) {
  23649. if (this.cameras[index].id === id) {
  23650. return this.cameras[index];
  23651. }
  23652. }
  23653. for (index = this.lights.length - 1; index >= 0; index--) {
  23654. if (this.lights[index].id === id) {
  23655. return this.lights[index];
  23656. }
  23657. }
  23658. return null;
  23659. };
  23660. Scene.prototype.getNodeByID = function (id) {
  23661. var mesh = this.getMeshByID(id);
  23662. if (mesh) {
  23663. return mesh;
  23664. }
  23665. var light = this.getLightByID(id);
  23666. if (light) {
  23667. return light;
  23668. }
  23669. var camera = this.getCameraByID(id);
  23670. if (camera) {
  23671. return camera;
  23672. }
  23673. var bone = this.getBoneByID(id);
  23674. return bone;
  23675. };
  23676. Scene.prototype.getNodeByName = function (name) {
  23677. var mesh = this.getMeshByName(name);
  23678. if (mesh) {
  23679. return mesh;
  23680. }
  23681. var light = this.getLightByName(name);
  23682. if (light) {
  23683. return light;
  23684. }
  23685. var camera = this.getCameraByName(name);
  23686. if (camera) {
  23687. return camera;
  23688. }
  23689. var bone = this.getBoneByName(name);
  23690. return bone;
  23691. };
  23692. Scene.prototype.getMeshByName = function (name) {
  23693. for (var index = 0; index < this.meshes.length; index++) {
  23694. if (this.meshes[index].name === name) {
  23695. return this.meshes[index];
  23696. }
  23697. }
  23698. return null;
  23699. };
  23700. Scene.prototype.getTransformNodeByName = function (name) {
  23701. for (var index = 0; index < this.transformNodes.length; index++) {
  23702. if (this.transformNodes[index].name === name) {
  23703. return this.transformNodes[index];
  23704. }
  23705. }
  23706. return null;
  23707. };
  23708. Scene.prototype.getSoundByName = function (name) {
  23709. var index;
  23710. if (BABYLON.AudioEngine) {
  23711. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  23712. if (this.mainSoundTrack.soundCollection[index].name === name) {
  23713. return this.mainSoundTrack.soundCollection[index];
  23714. }
  23715. }
  23716. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  23717. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  23718. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  23719. return this.soundTracks[sdIndex].soundCollection[index];
  23720. }
  23721. }
  23722. }
  23723. }
  23724. return null;
  23725. };
  23726. Scene.prototype.getLastSkeletonByID = function (id) {
  23727. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  23728. if (this.skeletons[index].id === id) {
  23729. return this.skeletons[index];
  23730. }
  23731. }
  23732. return null;
  23733. };
  23734. Scene.prototype.getSkeletonById = function (id) {
  23735. for (var index = 0; index < this.skeletons.length; index++) {
  23736. if (this.skeletons[index].id === id) {
  23737. return this.skeletons[index];
  23738. }
  23739. }
  23740. return null;
  23741. };
  23742. Scene.prototype.getSkeletonByName = function (name) {
  23743. for (var index = 0; index < this.skeletons.length; index++) {
  23744. if (this.skeletons[index].name === name) {
  23745. return this.skeletons[index];
  23746. }
  23747. }
  23748. return null;
  23749. };
  23750. Scene.prototype.getMorphTargetManagerById = function (id) {
  23751. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  23752. if (this.morphTargetManagers[index].uniqueId === id) {
  23753. return this.morphTargetManagers[index];
  23754. }
  23755. }
  23756. return null;
  23757. };
  23758. Scene.prototype.isActiveMesh = function (mesh) {
  23759. return (this._activeMeshes.indexOf(mesh) !== -1);
  23760. };
  23761. /**
  23762. * Return a the first highlight layer of the scene with a given name.
  23763. * @param name The name of the highlight layer to look for.
  23764. * @return The highlight layer if found otherwise null.
  23765. */
  23766. Scene.prototype.getHighlightLayerByName = function (name) {
  23767. for (var index = 0; index < this.effectLayers.length; index++) {
  23768. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.HighlightLayer.EffectName) {
  23769. return this.effectLayers[index];
  23770. }
  23771. }
  23772. return null;
  23773. };
  23774. /**
  23775. * Return a the first highlight layer of the scene with a given name.
  23776. * @param name The name of the highlight layer to look for.
  23777. * @return The highlight layer if found otherwise null.
  23778. */
  23779. Scene.prototype.getGlowLayerByName = function (name) {
  23780. for (var index = 0; index < this.effectLayers.length; index++) {
  23781. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.GlowLayer.EffectName) {
  23782. return this.effectLayers[index];
  23783. }
  23784. }
  23785. return null;
  23786. };
  23787. Object.defineProperty(Scene.prototype, "uid", {
  23788. /**
  23789. * Return a unique id as a string which can serve as an identifier for the scene
  23790. */
  23791. get: function () {
  23792. if (!this._uid) {
  23793. this._uid = BABYLON.Tools.RandomId();
  23794. }
  23795. return this._uid;
  23796. },
  23797. enumerable: true,
  23798. configurable: true
  23799. });
  23800. /**
  23801. * Add an externaly attached data from its key.
  23802. * This method call will fail and return false, if such key already exists.
  23803. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  23804. * @param key the unique key that identifies the data
  23805. * @param data the data object to associate to the key for this Engine instance
  23806. * @return true if no such key were already present and the data was added successfully, false otherwise
  23807. */
  23808. Scene.prototype.addExternalData = function (key, data) {
  23809. if (!this._externalData) {
  23810. this._externalData = new BABYLON.StringDictionary();
  23811. }
  23812. return this._externalData.add(key, data);
  23813. };
  23814. /**
  23815. * Get an externaly attached data from its key
  23816. * @param key the unique key that identifies the data
  23817. * @return the associated data, if present (can be null), or undefined if not present
  23818. */
  23819. Scene.prototype.getExternalData = function (key) {
  23820. if (!this._externalData) {
  23821. return null;
  23822. }
  23823. return this._externalData.get(key);
  23824. };
  23825. /**
  23826. * Get an externaly attached data from its key, create it using a factory if it's not already present
  23827. * @param key the unique key that identifies the data
  23828. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  23829. * @return the associated data, can be null if the factory returned null.
  23830. */
  23831. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  23832. if (!this._externalData) {
  23833. this._externalData = new BABYLON.StringDictionary();
  23834. }
  23835. return this._externalData.getOrAddWithFactory(key, factory);
  23836. };
  23837. /**
  23838. * Remove an externaly attached data from the Engine instance
  23839. * @param key the unique key that identifies the data
  23840. * @return true if the data was successfully removed, false if it doesn't exist
  23841. */
  23842. Scene.prototype.removeExternalData = function (key) {
  23843. return this._externalData.remove(key);
  23844. };
  23845. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  23846. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  23847. if (mesh.showSubMeshesBoundingBox) {
  23848. var boundingInfo = subMesh.getBoundingInfo();
  23849. if (boundingInfo !== null && boundingInfo !== undefined) {
  23850. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  23851. }
  23852. }
  23853. var material = subMesh.getMaterial();
  23854. if (material !== null && material !== undefined) {
  23855. // Render targets
  23856. if (material.getRenderTargetTextures !== undefined) {
  23857. if (this._processedMaterials.indexOf(material) === -1) {
  23858. this._processedMaterials.push(material);
  23859. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  23860. }
  23861. }
  23862. // Dispatch
  23863. this._activeIndices.addCount(subMesh.indexCount, false);
  23864. this._renderingManager.dispatch(subMesh, mesh, material);
  23865. }
  23866. }
  23867. };
  23868. Scene.prototype._isInIntermediateRendering = function () {
  23869. return this._intermediateRendering;
  23870. };
  23871. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  23872. this._activeMeshCandidateProvider = provider;
  23873. };
  23874. Scene.prototype.getActiveMeshCandidateProvider = function () {
  23875. return this._activeMeshCandidateProvider;
  23876. };
  23877. /**
  23878. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  23879. */
  23880. Scene.prototype.freezeActiveMeshes = function () {
  23881. this._evaluateActiveMeshes();
  23882. this._activeMeshesFrozen = true;
  23883. return this;
  23884. };
  23885. /**
  23886. * Use this function to restart evaluating active meshes on every frame
  23887. */
  23888. Scene.prototype.unfreezeActiveMeshes = function () {
  23889. this._activeMeshesFrozen = false;
  23890. return this;
  23891. };
  23892. Scene.prototype._evaluateActiveMeshes = function () {
  23893. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  23894. return;
  23895. }
  23896. if (!this.activeCamera) {
  23897. return;
  23898. }
  23899. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  23900. this.activeCamera._activeMeshes.reset();
  23901. this._activeMeshes.reset();
  23902. this._renderingManager.reset();
  23903. this._processedMaterials.reset();
  23904. this._activeParticleSystems.reset();
  23905. this._activeSkeletons.reset();
  23906. this._softwareSkinnedMeshes.reset();
  23907. if (this._boundingBoxRenderer) {
  23908. this._boundingBoxRenderer.reset();
  23909. }
  23910. // Meshes
  23911. var meshes;
  23912. var len;
  23913. var checkIsEnabled = true;
  23914. // Determine mesh candidates
  23915. if (this._activeMeshCandidateProvider !== undefined) {
  23916. // Use _activeMeshCandidateProvider
  23917. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  23918. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  23919. if (meshes !== undefined) {
  23920. len = meshes.length;
  23921. }
  23922. else {
  23923. len = 0;
  23924. }
  23925. }
  23926. else if (this._selectionOctree !== undefined) {
  23927. // Octree
  23928. var selection = this._selectionOctree.select(this._frustumPlanes);
  23929. meshes = selection.data;
  23930. len = selection.length;
  23931. }
  23932. else {
  23933. // Full scene traversal
  23934. len = this.meshes.length;
  23935. meshes = this.meshes;
  23936. }
  23937. // Check each mesh
  23938. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  23939. mesh = meshes[meshIndex];
  23940. if (mesh.isBlocked) {
  23941. continue;
  23942. }
  23943. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  23944. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  23945. continue;
  23946. }
  23947. mesh.computeWorldMatrix();
  23948. // Intersections
  23949. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  23950. this._meshesForIntersections.pushNoDuplicate(mesh);
  23951. }
  23952. // Switch to current LOD
  23953. meshLOD = mesh.getLOD(this.activeCamera);
  23954. if (meshLOD === undefined || meshLOD === null) {
  23955. continue;
  23956. }
  23957. mesh._preActivate();
  23958. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  23959. this._activeMeshes.push(mesh);
  23960. this.activeCamera._activeMeshes.push(mesh);
  23961. mesh._activate(this._renderId);
  23962. if (meshLOD !== mesh) {
  23963. meshLOD._activate(this._renderId);
  23964. }
  23965. this._activeMesh(mesh, meshLOD);
  23966. }
  23967. }
  23968. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  23969. // Particle systems
  23970. if (this.particlesEnabled) {
  23971. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  23972. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  23973. var particleSystem = this.particleSystems[particleIndex];
  23974. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  23975. continue;
  23976. }
  23977. var emitter = particleSystem.emitter;
  23978. if (!emitter.position || emitter.isEnabled()) {
  23979. this._activeParticleSystems.push(particleSystem);
  23980. particleSystem.animate();
  23981. this._renderingManager.dispatchParticles(particleSystem);
  23982. }
  23983. }
  23984. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  23985. }
  23986. };
  23987. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  23988. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  23989. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  23990. mesh.skeleton.prepare();
  23991. }
  23992. if (!mesh.computeBonesUsingShaders) {
  23993. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  23994. }
  23995. }
  23996. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  23997. var boundingInfo = sourceMesh.getBoundingInfo();
  23998. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  23999. }
  24000. if (mesh !== undefined && mesh !== null
  24001. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  24002. // Submeshes Octrees
  24003. var len;
  24004. var subMeshes;
  24005. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  24006. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  24007. len = intersections.length;
  24008. subMeshes = intersections.data;
  24009. }
  24010. else {
  24011. subMeshes = mesh.subMeshes;
  24012. len = subMeshes.length;
  24013. }
  24014. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  24015. subMesh = subMeshes[subIndex];
  24016. this._evaluateSubMesh(subMesh, mesh);
  24017. }
  24018. }
  24019. };
  24020. Scene.prototype.updateTransformMatrix = function (force) {
  24021. if (!this.activeCamera) {
  24022. return;
  24023. }
  24024. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  24025. };
  24026. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  24027. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  24028. };
  24029. Scene.prototype._renderForCamera = function (camera, rigParent) {
  24030. if (camera && camera._skipRendering) {
  24031. return;
  24032. }
  24033. var engine = this._engine;
  24034. this.activeCamera = camera;
  24035. if (!this.activeCamera)
  24036. throw new Error("Active camera not set");
  24037. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  24038. // Viewport
  24039. engine.setViewport(this.activeCamera.viewport);
  24040. // Camera
  24041. this.resetCachedMaterial();
  24042. this._renderId++;
  24043. this.activeCamera.update();
  24044. this.updateTransformMatrix();
  24045. if (camera._alternateCamera) {
  24046. this.updateAlternateTransformMatrix(camera._alternateCamera);
  24047. this._alternateRendering = true;
  24048. }
  24049. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  24050. // Meshes
  24051. this._evaluateActiveMeshes();
  24052. // Software skinning
  24053. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  24054. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  24055. mesh.applySkeleton(mesh.skeleton);
  24056. }
  24057. // Render targets
  24058. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  24059. var needsRestoreFrameBuffer = false;
  24060. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  24061. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  24062. }
  24063. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  24064. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  24065. }
  24066. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  24067. this._intermediateRendering = true;
  24068. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  24069. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  24070. var renderTarget = this._renderTargets.data[renderIndex];
  24071. if (renderTarget._shouldRender()) {
  24072. this._renderId++;
  24073. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  24074. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  24075. }
  24076. }
  24077. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  24078. this._intermediateRendering = false;
  24079. this._renderId++;
  24080. needsRestoreFrameBuffer = true; // Restore back buffer
  24081. }
  24082. // Render EffecttLayer Texture
  24083. var stencilState = this._engine.getStencilBuffer();
  24084. var renderEffects = false;
  24085. var needStencil = false;
  24086. if (this.renderTargetsEnabled && this.effectLayers && this.effectLayers.length > 0) {
  24087. this._intermediateRendering = true;
  24088. for (var i = 0; i < this.effectLayers.length; i++) {
  24089. var effectLayer = this.effectLayers[i];
  24090. if (effectLayer.shouldRender() &&
  24091. (!effectLayer.camera ||
  24092. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  24093. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  24094. renderEffects = true;
  24095. needStencil = needStencil || effectLayer.needStencil();
  24096. var renderTarget = effectLayer._mainTexture;
  24097. if (renderTarget._shouldRender()) {
  24098. this._renderId++;
  24099. renderTarget.render(false, false);
  24100. needsRestoreFrameBuffer = true;
  24101. }
  24102. }
  24103. }
  24104. this._intermediateRendering = false;
  24105. this._renderId++;
  24106. }
  24107. if (needsRestoreFrameBuffer) {
  24108. engine.restoreDefaultFramebuffer(); // Restore back buffer
  24109. }
  24110. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  24111. // Prepare Frame
  24112. this.postProcessManager._prepareFrame();
  24113. // Backgrounds
  24114. var layerIndex;
  24115. var layer;
  24116. if (this.layers.length) {
  24117. engine.setDepthBuffer(false);
  24118. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  24119. layer = this.layers[layerIndex];
  24120. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  24121. layer.render();
  24122. }
  24123. }
  24124. engine.setDepthBuffer(true);
  24125. }
  24126. // Activate effect Layer stencil
  24127. if (needStencil) {
  24128. this._engine.setStencilBuffer(true);
  24129. }
  24130. // Render
  24131. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  24132. this._renderingManager.render(null, null, true, true);
  24133. this.onAfterDrawPhaseObservable.notifyObservers(this);
  24134. // Restore effect Layer stencil
  24135. if (needStencil) {
  24136. this._engine.setStencilBuffer(stencilState);
  24137. }
  24138. // Bounding boxes
  24139. if (this._boundingBoxRenderer) {
  24140. this._boundingBoxRenderer.render();
  24141. }
  24142. // Lens flares
  24143. if (this.lensFlaresEnabled) {
  24144. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  24145. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  24146. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  24147. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  24148. lensFlareSystem.render();
  24149. }
  24150. }
  24151. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  24152. }
  24153. // Foregrounds
  24154. if (this.layers.length) {
  24155. engine.setDepthBuffer(false);
  24156. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  24157. layer = this.layers[layerIndex];
  24158. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  24159. layer.render();
  24160. }
  24161. }
  24162. engine.setDepthBuffer(true);
  24163. }
  24164. // Effect Layer
  24165. if (renderEffects) {
  24166. engine.setDepthBuffer(false);
  24167. for (var i = 0; i < this.effectLayers.length; i++) {
  24168. if (this.effectLayers[i].shouldRender()) {
  24169. this.effectLayers[i].render();
  24170. }
  24171. }
  24172. engine.setDepthBuffer(true);
  24173. }
  24174. // Finalize frame
  24175. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  24176. // Reset some special arrays
  24177. this._renderTargets.reset();
  24178. this._alternateRendering = false;
  24179. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  24180. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  24181. };
  24182. Scene.prototype._processSubCameras = function (camera) {
  24183. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  24184. this._renderForCamera(camera);
  24185. return;
  24186. }
  24187. // Update camera
  24188. if (this.activeCamera) {
  24189. this.activeCamera.update();
  24190. }
  24191. // rig cameras
  24192. for (var index = 0; index < camera._rigCameras.length; index++) {
  24193. this._renderForCamera(camera._rigCameras[index], camera);
  24194. }
  24195. this.activeCamera = camera;
  24196. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  24197. };
  24198. Scene.prototype._checkIntersections = function () {
  24199. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  24200. var sourceMesh = this._meshesForIntersections.data[index];
  24201. if (!sourceMesh.actionManager) {
  24202. continue;
  24203. }
  24204. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  24205. var action = sourceMesh.actionManager.actions[actionIndex];
  24206. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24207. var parameters = action.getTriggerParameter();
  24208. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  24209. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  24210. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  24211. if (areIntersecting && currentIntersectionInProgress === -1) {
  24212. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  24213. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  24214. sourceMesh._intersectionsInProgress.push(otherMesh);
  24215. }
  24216. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24217. sourceMesh._intersectionsInProgress.push(otherMesh);
  24218. }
  24219. }
  24220. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  24221. //They intersected, and now they don't.
  24222. //is this trigger an exit trigger? execute an event.
  24223. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24224. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  24225. }
  24226. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  24227. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24228. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  24229. }
  24230. }
  24231. }
  24232. }
  24233. }
  24234. };
  24235. Scene.prototype.render = function () {
  24236. if (this.isDisposed) {
  24237. return;
  24238. }
  24239. this._activeParticles.fetchNewFrame();
  24240. this._totalVertices.fetchNewFrame();
  24241. this._activeIndices.fetchNewFrame();
  24242. this._activeBones.fetchNewFrame();
  24243. this._meshesForIntersections.reset();
  24244. this.resetCachedMaterial();
  24245. this.onBeforeAnimationsObservable.notifyObservers(this);
  24246. // Actions
  24247. if (this.actionManager) {
  24248. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  24249. }
  24250. //Simplification Queue
  24251. if (this.simplificationQueue && !this.simplificationQueue.running) {
  24252. this.simplificationQueue.executeNext();
  24253. }
  24254. if (this._engine.isDeterministicLockStep()) {
  24255. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  24256. var defaultFPS = (60.0 / 1000.0);
  24257. var defaultFrameTime = 1000 / 60; // frame time in MS
  24258. if (this._physicsEngine) {
  24259. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  24260. }
  24261. var stepsTaken = 0;
  24262. var maxSubSteps = this._engine.getLockstepMaxSteps();
  24263. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  24264. internalSteps = Math.min(internalSteps, maxSubSteps);
  24265. do {
  24266. this.onBeforeStepObservable.notifyObservers(this);
  24267. // Animations
  24268. this._animationRatio = defaultFrameTime * defaultFPS;
  24269. this._animate();
  24270. this.onAfterAnimationsObservable.notifyObservers(this);
  24271. // Physics
  24272. if (this._physicsEngine) {
  24273. this.onBeforePhysicsObservable.notifyObservers(this);
  24274. this._physicsEngine._step(defaultFrameTime / 1000);
  24275. this.onAfterPhysicsObservable.notifyObservers(this);
  24276. }
  24277. this.onAfterStepObservable.notifyObservers(this);
  24278. this._currentStepId++;
  24279. stepsTaken++;
  24280. deltaTime -= defaultFrameTime;
  24281. } while (deltaTime > 0 && stepsTaken < internalSteps);
  24282. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  24283. }
  24284. else {
  24285. // Animations
  24286. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  24287. this._animationRatio = deltaTime * (60.0 / 1000.0);
  24288. this._animate();
  24289. this.onAfterAnimationsObservable.notifyObservers(this);
  24290. // Physics
  24291. if (this._physicsEngine) {
  24292. this.onBeforePhysicsObservable.notifyObservers(this);
  24293. this._physicsEngine._step(deltaTime / 1000.0);
  24294. this.onAfterPhysicsObservable.notifyObservers(this);
  24295. }
  24296. }
  24297. // update gamepad manager
  24298. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  24299. this._gamepadManager._checkGamepadsStatus();
  24300. }
  24301. // Before render
  24302. this.onBeforeRenderObservable.notifyObservers(this);
  24303. // Customs render targets
  24304. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  24305. var engine = this.getEngine();
  24306. var currentActiveCamera = this.activeCamera;
  24307. if (this.renderTargetsEnabled) {
  24308. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  24309. this._intermediateRendering = true;
  24310. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  24311. var renderTarget = this.customRenderTargets[customIndex];
  24312. if (renderTarget._shouldRender()) {
  24313. this._renderId++;
  24314. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  24315. if (!this.activeCamera)
  24316. throw new Error("Active camera not set");
  24317. // Viewport
  24318. engine.setViewport(this.activeCamera.viewport);
  24319. // Camera
  24320. this.updateTransformMatrix();
  24321. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  24322. }
  24323. }
  24324. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  24325. this._intermediateRendering = false;
  24326. this._renderId++;
  24327. }
  24328. // Restore back buffer
  24329. if (this.customRenderTargets.length > 0) {
  24330. engine.restoreDefaultFramebuffer();
  24331. }
  24332. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  24333. this.activeCamera = currentActiveCamera;
  24334. // Procedural textures
  24335. if (this.proceduralTexturesEnabled) {
  24336. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  24337. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  24338. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  24339. if (proceduralTexture._shouldRender()) {
  24340. proceduralTexture.render();
  24341. }
  24342. }
  24343. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  24344. }
  24345. // Clear
  24346. if (this.autoClearDepthAndStencil || this.autoClear) {
  24347. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  24348. }
  24349. // Shadows
  24350. if (this.shadowsEnabled) {
  24351. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  24352. var light = this.lights[lightIndex];
  24353. var shadowGenerator = light.getShadowGenerator();
  24354. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  24355. var shadowMap = (shadowGenerator.getShadowMap());
  24356. if (this.textures.indexOf(shadowMap) !== -1) {
  24357. this._renderTargets.push(shadowMap);
  24358. }
  24359. }
  24360. }
  24361. }
  24362. // Depth renderer
  24363. for (var key in this._depthRenderer) {
  24364. this._renderTargets.push(this._depthRenderer[key].getDepthMap());
  24365. }
  24366. // Geometry renderer
  24367. if (this._geometryBufferRenderer) {
  24368. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  24369. }
  24370. // RenderPipeline
  24371. if (this._postProcessRenderPipelineManager) {
  24372. this._postProcessRenderPipelineManager.update();
  24373. }
  24374. // Multi-cameras?
  24375. if (this.activeCameras.length > 0) {
  24376. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  24377. if (cameraIndex > 0) {
  24378. this._engine.clear(null, false, true, true);
  24379. }
  24380. this._processSubCameras(this.activeCameras[cameraIndex]);
  24381. }
  24382. }
  24383. else {
  24384. if (!this.activeCamera) {
  24385. throw new Error("No camera defined");
  24386. }
  24387. this._processSubCameras(this.activeCamera);
  24388. }
  24389. // Intersection checks
  24390. this._checkIntersections();
  24391. // Update the audio listener attached to the camera
  24392. if (BABYLON.AudioEngine) {
  24393. this._updateAudioParameters();
  24394. }
  24395. // After render
  24396. if (this.afterRender) {
  24397. this.afterRender();
  24398. }
  24399. this.onAfterRenderObservable.notifyObservers(this);
  24400. // Cleaning
  24401. for (var index = 0; index < this._toBeDisposed.length; index++) {
  24402. var data = this._toBeDisposed.data[index];
  24403. if (data) {
  24404. data.dispose();
  24405. }
  24406. this._toBeDisposed[index] = null;
  24407. }
  24408. this._toBeDisposed.reset();
  24409. if (this.dumpNextRenderTargets) {
  24410. this.dumpNextRenderTargets = false;
  24411. }
  24412. this._activeBones.addCount(0, true);
  24413. this._activeIndices.addCount(0, true);
  24414. this._activeParticles.addCount(0, true);
  24415. };
  24416. Scene.prototype._updateAudioParameters = function () {
  24417. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  24418. return;
  24419. }
  24420. var listeningCamera;
  24421. var audioEngine = BABYLON.Engine.audioEngine;
  24422. if (this.activeCameras.length > 0) {
  24423. listeningCamera = this.activeCameras[0];
  24424. }
  24425. else {
  24426. listeningCamera = this.activeCamera;
  24427. }
  24428. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  24429. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  24430. // for VR cameras
  24431. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  24432. listeningCamera = listeningCamera.rigCameras[0];
  24433. }
  24434. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  24435. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  24436. cameraDirection.normalize();
  24437. // To avoid some errors on GearVR
  24438. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  24439. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  24440. }
  24441. var i;
  24442. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  24443. var sound = this.mainSoundTrack.soundCollection[i];
  24444. if (sound.useCustomAttenuation) {
  24445. sound.updateDistanceFromListener();
  24446. }
  24447. }
  24448. for (i = 0; i < this.soundTracks.length; i++) {
  24449. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  24450. sound = this.soundTracks[i].soundCollection[j];
  24451. if (sound.useCustomAttenuation) {
  24452. sound.updateDistanceFromListener();
  24453. }
  24454. }
  24455. }
  24456. }
  24457. };
  24458. Object.defineProperty(Scene.prototype, "audioEnabled", {
  24459. // Audio
  24460. get: function () {
  24461. return this._audioEnabled;
  24462. },
  24463. set: function (value) {
  24464. this._audioEnabled = value;
  24465. if (BABYLON.AudioEngine) {
  24466. if (this._audioEnabled) {
  24467. this._enableAudio();
  24468. }
  24469. else {
  24470. this._disableAudio();
  24471. }
  24472. }
  24473. },
  24474. enumerable: true,
  24475. configurable: true
  24476. });
  24477. Scene.prototype._disableAudio = function () {
  24478. var i;
  24479. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  24480. this.mainSoundTrack.soundCollection[i].pause();
  24481. }
  24482. for (i = 0; i < this.soundTracks.length; i++) {
  24483. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  24484. this.soundTracks[i].soundCollection[j].pause();
  24485. }
  24486. }
  24487. };
  24488. Scene.prototype._enableAudio = function () {
  24489. var i;
  24490. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  24491. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  24492. this.mainSoundTrack.soundCollection[i].play();
  24493. }
  24494. }
  24495. for (i = 0; i < this.soundTracks.length; i++) {
  24496. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  24497. if (this.soundTracks[i].soundCollection[j].isPaused) {
  24498. this.soundTracks[i].soundCollection[j].play();
  24499. }
  24500. }
  24501. }
  24502. };
  24503. Object.defineProperty(Scene.prototype, "headphone", {
  24504. get: function () {
  24505. return this._headphone;
  24506. },
  24507. set: function (value) {
  24508. this._headphone = value;
  24509. if (BABYLON.AudioEngine) {
  24510. if (this._headphone) {
  24511. this._switchAudioModeForHeadphones();
  24512. }
  24513. else {
  24514. this._switchAudioModeForNormalSpeakers();
  24515. }
  24516. }
  24517. },
  24518. enumerable: true,
  24519. configurable: true
  24520. });
  24521. Scene.prototype._switchAudioModeForHeadphones = function () {
  24522. this.mainSoundTrack.switchPanningModelToHRTF();
  24523. for (var i = 0; i < this.soundTracks.length; i++) {
  24524. this.soundTracks[i].switchPanningModelToHRTF();
  24525. }
  24526. };
  24527. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  24528. this.mainSoundTrack.switchPanningModelToEqualPower();
  24529. for (var i = 0; i < this.soundTracks.length; i++) {
  24530. this.soundTracks[i].switchPanningModelToEqualPower();
  24531. }
  24532. };
  24533. /**
  24534. * Creates a depth renderer a given camera which contains a depth map which can be used for post processing.
  24535. * @param camera The camera to create the depth renderer on (default: scene's active camera)
  24536. * @returns the created depth renderer
  24537. */
  24538. Scene.prototype.enableDepthRenderer = function (camera) {
  24539. camera = camera || this.activeCamera;
  24540. if (!camera) {
  24541. throw "No camera available to enable depth renderer";
  24542. }
  24543. if (!this._depthRenderer[camera.id]) {
  24544. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, BABYLON.Engine.TEXTURETYPE_FLOAT, camera);
  24545. }
  24546. return this._depthRenderer[camera.id];
  24547. };
  24548. /**
  24549. * Disables a depth renderer for a given camera
  24550. * @param camera The camera to disable the depth renderer on (default: scene's active camera)
  24551. */
  24552. Scene.prototype.disableDepthRenderer = function (camera) {
  24553. camera = camera || this.activeCamera;
  24554. if (!camera || !this._depthRenderer[camera.id]) {
  24555. return;
  24556. }
  24557. this._depthRenderer[camera.id].dispose();
  24558. delete this._depthRenderer[camera.id];
  24559. };
  24560. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  24561. if (ratio === void 0) { ratio = 1; }
  24562. if (this._geometryBufferRenderer) {
  24563. return this._geometryBufferRenderer;
  24564. }
  24565. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  24566. if (!this._geometryBufferRenderer.isSupported) {
  24567. this._geometryBufferRenderer = null;
  24568. }
  24569. return this._geometryBufferRenderer;
  24570. };
  24571. Scene.prototype.disableGeometryBufferRenderer = function () {
  24572. if (!this._geometryBufferRenderer) {
  24573. return;
  24574. }
  24575. this._geometryBufferRenderer.dispose();
  24576. this._geometryBufferRenderer = null;
  24577. };
  24578. Scene.prototype.freezeMaterials = function () {
  24579. for (var i = 0; i < this.materials.length; i++) {
  24580. this.materials[i].freeze();
  24581. }
  24582. };
  24583. Scene.prototype.unfreezeMaterials = function () {
  24584. for (var i = 0; i < this.materials.length; i++) {
  24585. this.materials[i].unfreeze();
  24586. }
  24587. };
  24588. Scene.prototype.dispose = function () {
  24589. this.beforeRender = null;
  24590. this.afterRender = null;
  24591. this.skeletons = [];
  24592. this.morphTargetManagers = [];
  24593. this.importedMeshesFiles = new Array();
  24594. this.stopAllAnimations();
  24595. this.resetCachedMaterial();
  24596. for (var key in this._depthRenderer) {
  24597. this._depthRenderer[key].dispose();
  24598. }
  24599. if (this._gamepadManager) {
  24600. this._gamepadManager.dispose();
  24601. this._gamepadManager = null;
  24602. }
  24603. // Smart arrays
  24604. if (this.activeCamera) {
  24605. this.activeCamera._activeMeshes.dispose();
  24606. this.activeCamera = null;
  24607. }
  24608. this._activeMeshes.dispose();
  24609. this._renderingManager.dispose();
  24610. this._processedMaterials.dispose();
  24611. this._activeParticleSystems.dispose();
  24612. this._activeSkeletons.dispose();
  24613. this._softwareSkinnedMeshes.dispose();
  24614. this._renderTargets.dispose();
  24615. if (this._boundingBoxRenderer) {
  24616. this._boundingBoxRenderer.dispose();
  24617. }
  24618. this._meshesForIntersections.dispose();
  24619. this._toBeDisposed.dispose();
  24620. // Abort active requests
  24621. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  24622. var request = _a[_i];
  24623. request.abort();
  24624. }
  24625. // Debug layer
  24626. if (this._debugLayer) {
  24627. this._debugLayer.hide();
  24628. }
  24629. // Events
  24630. this.onDisposeObservable.notifyObservers(this);
  24631. this.onDisposeObservable.clear();
  24632. this.onBeforeRenderObservable.clear();
  24633. this.onAfterRenderObservable.clear();
  24634. this.OnBeforeRenderTargetsRenderObservable.clear();
  24635. this.OnAfterRenderTargetsRenderObservable.clear();
  24636. this.onAfterStepObservable.clear();
  24637. this.onBeforeStepObservable.clear();
  24638. this.onBeforeActiveMeshesEvaluationObservable.clear();
  24639. this.onAfterActiveMeshesEvaluationObservable.clear();
  24640. this.onBeforeParticlesRenderingObservable.clear();
  24641. this.onAfterParticlesRenderingObservable.clear();
  24642. this.onBeforeSpritesRenderingObservable.clear();
  24643. this.onAfterSpritesRenderingObservable.clear();
  24644. this.onBeforeDrawPhaseObservable.clear();
  24645. this.onAfterDrawPhaseObservable.clear();
  24646. this.onBeforePhysicsObservable.clear();
  24647. this.onAfterPhysicsObservable.clear();
  24648. this.onBeforeAnimationsObservable.clear();
  24649. this.onAfterAnimationsObservable.clear();
  24650. this.onDataLoadedObservable.clear();
  24651. this.detachControl();
  24652. // Release sounds & sounds tracks
  24653. if (BABYLON.AudioEngine) {
  24654. this.disposeSounds();
  24655. }
  24656. // VR Helper
  24657. if (this.VRHelper) {
  24658. this.VRHelper.dispose();
  24659. }
  24660. // Detach cameras
  24661. var canvas = this._engine.getRenderingCanvas();
  24662. if (canvas) {
  24663. var index;
  24664. for (index = 0; index < this.cameras.length; index++) {
  24665. this.cameras[index].detachControl(canvas);
  24666. }
  24667. }
  24668. // Release animation groups
  24669. while (this.animationGroups.length) {
  24670. this.animationGroups[0].dispose();
  24671. }
  24672. // Release lights
  24673. while (this.lights.length) {
  24674. this.lights[0].dispose();
  24675. }
  24676. // Release meshes
  24677. while (this.meshes.length) {
  24678. this.meshes[0].dispose(true);
  24679. }
  24680. while (this.transformNodes.length) {
  24681. this.removeTransformNode(this.transformNodes[0]);
  24682. }
  24683. // Release cameras
  24684. while (this.cameras.length) {
  24685. this.cameras[0].dispose();
  24686. }
  24687. // Release materials
  24688. if (this.defaultMaterial) {
  24689. this.defaultMaterial.dispose();
  24690. }
  24691. while (this.multiMaterials.length) {
  24692. this.multiMaterials[0].dispose();
  24693. }
  24694. while (this.materials.length) {
  24695. this.materials[0].dispose();
  24696. }
  24697. // Release particles
  24698. while (this.particleSystems.length) {
  24699. this.particleSystems[0].dispose();
  24700. }
  24701. // Release sprites
  24702. while (this.spriteManagers.length) {
  24703. this.spriteManagers[0].dispose();
  24704. }
  24705. // Release postProcesses
  24706. while (this.postProcesses.length) {
  24707. this.postProcesses[0].dispose();
  24708. }
  24709. // Release layers
  24710. while (this.layers.length) {
  24711. this.layers[0].dispose();
  24712. }
  24713. while (this.effectLayers.length) {
  24714. this.effectLayers[0].dispose();
  24715. }
  24716. // Release textures
  24717. while (this.textures.length) {
  24718. this.textures[0].dispose();
  24719. }
  24720. // Release UBO
  24721. this._sceneUbo.dispose();
  24722. if (this._alternateSceneUbo) {
  24723. this._alternateSceneUbo.dispose();
  24724. }
  24725. // Post-processes
  24726. this.postProcessManager.dispose();
  24727. if (this._postProcessRenderPipelineManager) {
  24728. this._postProcessRenderPipelineManager.dispose();
  24729. }
  24730. // Physics
  24731. if (this._physicsEngine) {
  24732. this.disablePhysicsEngine();
  24733. }
  24734. // Remove from engine
  24735. index = this._engine.scenes.indexOf(this);
  24736. if (index > -1) {
  24737. this._engine.scenes.splice(index, 1);
  24738. }
  24739. this._engine.wipeCaches(true);
  24740. this._isDisposed = true;
  24741. };
  24742. Object.defineProperty(Scene.prototype, "isDisposed", {
  24743. get: function () {
  24744. return this._isDisposed;
  24745. },
  24746. enumerable: true,
  24747. configurable: true
  24748. });
  24749. // Release sounds & sounds tracks
  24750. Scene.prototype.disposeSounds = function () {
  24751. if (!this._mainSoundTrack) {
  24752. return;
  24753. }
  24754. this.mainSoundTrack.dispose();
  24755. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  24756. this.soundTracks[scIndex].dispose();
  24757. }
  24758. };
  24759. // Octrees
  24760. /**
  24761. * Get the world extend vectors with an optional filter
  24762. *
  24763. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  24764. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  24765. */
  24766. Scene.prototype.getWorldExtends = function (filterPredicate) {
  24767. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  24768. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  24769. filterPredicate = filterPredicate || (function () { return true; });
  24770. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  24771. mesh.computeWorldMatrix(true);
  24772. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  24773. return;
  24774. }
  24775. var boundingInfo = mesh.getBoundingInfo();
  24776. var minBox = boundingInfo.boundingBox.minimumWorld;
  24777. var maxBox = boundingInfo.boundingBox.maximumWorld;
  24778. BABYLON.Tools.CheckExtends(minBox, min, max);
  24779. BABYLON.Tools.CheckExtends(maxBox, min, max);
  24780. });
  24781. return {
  24782. min: min,
  24783. max: max
  24784. };
  24785. };
  24786. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  24787. if (maxCapacity === void 0) { maxCapacity = 64; }
  24788. if (maxDepth === void 0) { maxDepth = 2; }
  24789. if (!this._selectionOctree) {
  24790. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  24791. }
  24792. var worldExtends = this.getWorldExtends();
  24793. // Update octree
  24794. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  24795. return this._selectionOctree;
  24796. };
  24797. // Picking
  24798. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  24799. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  24800. var result = BABYLON.Ray.Zero();
  24801. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  24802. return result;
  24803. };
  24804. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  24805. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  24806. var engine = this._engine;
  24807. if (!camera) {
  24808. if (!this.activeCamera)
  24809. throw new Error("Active camera not set");
  24810. camera = this.activeCamera;
  24811. }
  24812. var cameraViewport = camera.viewport;
  24813. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  24814. // Moving coordinates to local viewport world
  24815. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  24816. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  24817. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  24818. return this;
  24819. };
  24820. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  24821. var result = BABYLON.Ray.Zero();
  24822. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  24823. return result;
  24824. };
  24825. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  24826. if (!BABYLON.PickingInfo) {
  24827. return this;
  24828. }
  24829. var engine = this._engine;
  24830. if (!camera) {
  24831. if (!this.activeCamera)
  24832. throw new Error("Active camera not set");
  24833. camera = this.activeCamera;
  24834. }
  24835. var cameraViewport = camera.viewport;
  24836. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  24837. var identity = BABYLON.Matrix.Identity();
  24838. // Moving coordinates to local viewport world
  24839. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  24840. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  24841. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  24842. return this;
  24843. };
  24844. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  24845. if (!BABYLON.PickingInfo) {
  24846. return null;
  24847. }
  24848. var pickingInfo = null;
  24849. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  24850. var mesh = this.meshes[meshIndex];
  24851. if (predicate) {
  24852. if (!predicate(mesh)) {
  24853. continue;
  24854. }
  24855. }
  24856. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  24857. continue;
  24858. }
  24859. var world = mesh.getWorldMatrix();
  24860. var ray = rayFunction(world);
  24861. var result = mesh.intersects(ray, fastCheck);
  24862. if (!result || !result.hit)
  24863. continue;
  24864. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  24865. continue;
  24866. pickingInfo = result;
  24867. if (fastCheck) {
  24868. break;
  24869. }
  24870. }
  24871. return pickingInfo || new BABYLON.PickingInfo();
  24872. };
  24873. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  24874. if (!BABYLON.PickingInfo) {
  24875. return null;
  24876. }
  24877. var pickingInfos = new Array();
  24878. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  24879. var mesh = this.meshes[meshIndex];
  24880. if (predicate) {
  24881. if (!predicate(mesh)) {
  24882. continue;
  24883. }
  24884. }
  24885. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  24886. continue;
  24887. }
  24888. var world = mesh.getWorldMatrix();
  24889. var ray = rayFunction(world);
  24890. var result = mesh.intersects(ray, false);
  24891. if (!result || !result.hit)
  24892. continue;
  24893. pickingInfos.push(result);
  24894. }
  24895. return pickingInfos;
  24896. };
  24897. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  24898. if (!BABYLON.PickingInfo) {
  24899. return null;
  24900. }
  24901. var pickingInfo = null;
  24902. if (!camera) {
  24903. if (!this.activeCamera) {
  24904. return null;
  24905. }
  24906. camera = this.activeCamera;
  24907. }
  24908. if (this.spriteManagers.length > 0) {
  24909. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  24910. var spriteManager = this.spriteManagers[spriteIndex];
  24911. if (!spriteManager.isPickable) {
  24912. continue;
  24913. }
  24914. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  24915. if (!result || !result.hit)
  24916. continue;
  24917. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  24918. continue;
  24919. pickingInfo = result;
  24920. if (fastCheck) {
  24921. break;
  24922. }
  24923. }
  24924. }
  24925. return pickingInfo || new BABYLON.PickingInfo();
  24926. };
  24927. /** Launch a ray to try to pick a mesh in the scene
  24928. * @param x position on screen
  24929. * @param y position on screen
  24930. * @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
  24931. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  24932. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  24933. */
  24934. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  24935. var _this = this;
  24936. if (!BABYLON.PickingInfo) {
  24937. return null;
  24938. }
  24939. return this._internalPick(function (world) {
  24940. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  24941. return _this._tempPickingRay;
  24942. }, predicate, fastCheck);
  24943. };
  24944. /** Launch a ray to try to pick a sprite in the scene
  24945. * @param x position on screen
  24946. * @param y position on screen
  24947. * @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
  24948. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  24949. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  24950. */
  24951. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  24952. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  24953. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  24954. };
  24955. /** Use the given ray to pick a mesh in the scene
  24956. * @param ray The ray to use to pick meshes
  24957. * @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
  24958. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  24959. */
  24960. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  24961. var _this = this;
  24962. return this._internalPick(function (world) {
  24963. if (!_this._pickWithRayInverseMatrix) {
  24964. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  24965. }
  24966. world.invertToRef(_this._pickWithRayInverseMatrix);
  24967. if (!_this._cachedRayForTransform) {
  24968. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  24969. }
  24970. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  24971. return _this._cachedRayForTransform;
  24972. }, predicate, fastCheck);
  24973. };
  24974. /**
  24975. * Launch a ray to try to pick a mesh in the scene
  24976. * @param x X position on screen
  24977. * @param y Y position on screen
  24978. * @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
  24979. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  24980. */
  24981. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  24982. var _this = this;
  24983. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  24984. };
  24985. /**
  24986. * Launch a ray to try to pick a mesh in the scene
  24987. * @param ray Ray to use
  24988. * @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
  24989. */
  24990. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  24991. var _this = this;
  24992. return this._internalMultiPick(function (world) {
  24993. if (!_this._pickWithRayInverseMatrix) {
  24994. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  24995. }
  24996. world.invertToRef(_this._pickWithRayInverseMatrix);
  24997. if (!_this._cachedRayForTransform) {
  24998. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  24999. }
  25000. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  25001. return _this._cachedRayForTransform;
  25002. }, predicate);
  25003. };
  25004. Scene.prototype.setPointerOverMesh = function (mesh) {
  25005. if (this._pointerOverMesh === mesh) {
  25006. return;
  25007. }
  25008. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  25009. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  25010. }
  25011. this._pointerOverMesh = mesh;
  25012. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  25013. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  25014. }
  25015. };
  25016. Scene.prototype.getPointerOverMesh = function () {
  25017. return this._pointerOverMesh;
  25018. };
  25019. Scene.prototype.setPointerOverSprite = function (sprite) {
  25020. if (this._pointerOverSprite === sprite) {
  25021. return;
  25022. }
  25023. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  25024. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  25025. }
  25026. this._pointerOverSprite = sprite;
  25027. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  25028. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  25029. }
  25030. };
  25031. Scene.prototype.getPointerOverSprite = function () {
  25032. return this._pointerOverSprite;
  25033. };
  25034. // Physics
  25035. Scene.prototype.getPhysicsEngine = function () {
  25036. return this._physicsEngine;
  25037. };
  25038. /**
  25039. * Enables physics to the current scene
  25040. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  25041. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  25042. * @return {boolean} was the physics engine initialized
  25043. */
  25044. Scene.prototype.enablePhysics = function (gravity, plugin) {
  25045. if (gravity === void 0) { gravity = null; }
  25046. if (this._physicsEngine) {
  25047. return true;
  25048. }
  25049. try {
  25050. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  25051. return true;
  25052. }
  25053. catch (e) {
  25054. BABYLON.Tools.Error(e.message);
  25055. return false;
  25056. }
  25057. };
  25058. Scene.prototype.disablePhysicsEngine = function () {
  25059. if (!this._physicsEngine) {
  25060. return;
  25061. }
  25062. this._physicsEngine.dispose();
  25063. this._physicsEngine = null;
  25064. };
  25065. Scene.prototype.isPhysicsEnabled = function () {
  25066. return this._physicsEngine !== undefined;
  25067. };
  25068. Scene.prototype.deleteCompoundImpostor = function (compound) {
  25069. var mesh = compound.parts[0].mesh;
  25070. if (mesh.physicsImpostor) {
  25071. mesh.physicsImpostor.dispose();
  25072. mesh.physicsImpostor = null;
  25073. }
  25074. };
  25075. // Misc.
  25076. Scene.prototype._rebuildGeometries = function () {
  25077. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  25078. var geometry = _a[_i];
  25079. geometry._rebuild();
  25080. }
  25081. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  25082. var mesh = _c[_b];
  25083. mesh._rebuild();
  25084. }
  25085. if (this.postProcessManager) {
  25086. this.postProcessManager._rebuild();
  25087. }
  25088. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  25089. var layer = _e[_d];
  25090. layer._rebuild();
  25091. }
  25092. for (var _f = 0, _g = this.effectLayers; _f < _g.length; _f++) {
  25093. var effectLayer = _g[_f];
  25094. effectLayer._rebuild();
  25095. }
  25096. if (this._boundingBoxRenderer) {
  25097. this._boundingBoxRenderer._rebuild();
  25098. }
  25099. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  25100. var system = _j[_h];
  25101. system.rebuild();
  25102. }
  25103. if (this._postProcessRenderPipelineManager) {
  25104. this._postProcessRenderPipelineManager._rebuild();
  25105. }
  25106. };
  25107. Scene.prototype._rebuildTextures = function () {
  25108. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  25109. var texture = _a[_i];
  25110. texture._rebuild();
  25111. }
  25112. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  25113. };
  25114. /**
  25115. * Creates a default light for the scene.
  25116. * @param replace Whether to replace the existing lights in the scene.
  25117. */
  25118. Scene.prototype.createDefaultLight = function (replace) {
  25119. if (replace === void 0) { replace = false; }
  25120. // Dispose existing light in replace mode.
  25121. if (replace) {
  25122. if (this.lights) {
  25123. for (var i = 0; i < this.lights.length; i++) {
  25124. this.lights[i].dispose();
  25125. }
  25126. }
  25127. }
  25128. // Light
  25129. if (this.lights.length === 0) {
  25130. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  25131. }
  25132. };
  25133. /**
  25134. * Creates a default camera for the scene.
  25135. * @param createArcRotateCamera Whether to create an arc rotate or a free camera.
  25136. * @param replace Whether to replace the existing active camera in the scene.
  25137. * @param attachCameraControls Whether to attach camera controls to the canvas.
  25138. */
  25139. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  25140. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  25141. if (replace === void 0) { replace = false; }
  25142. if (attachCameraControls === void 0) { attachCameraControls = false; }
  25143. // Dispose existing camera in replace mode.
  25144. if (replace) {
  25145. if (this.activeCamera) {
  25146. this.activeCamera.dispose();
  25147. this.activeCamera = null;
  25148. }
  25149. }
  25150. // Camera
  25151. if (!this.activeCamera) {
  25152. var worldExtends = this.getWorldExtends();
  25153. var worldSize = worldExtends.max.subtract(worldExtends.min);
  25154. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  25155. var camera;
  25156. var radius = worldSize.length() * 1.5;
  25157. // empty scene scenario!
  25158. if (!isFinite(radius)) {
  25159. radius = 1;
  25160. worldCenter.copyFromFloats(0, 0, 0);
  25161. }
  25162. if (createArcRotateCamera) {
  25163. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  25164. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  25165. arcRotateCamera.wheelPrecision = 100 / radius;
  25166. camera = arcRotateCamera;
  25167. }
  25168. else {
  25169. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  25170. freeCamera.setTarget(worldCenter);
  25171. camera = freeCamera;
  25172. }
  25173. camera.minZ = radius * 0.01;
  25174. camera.maxZ = radius * 1000;
  25175. camera.speed = radius * 0.2;
  25176. this.activeCamera = camera;
  25177. var canvas = this.getEngine().getRenderingCanvas();
  25178. if (attachCameraControls && canvas) {
  25179. camera.attachControl(canvas);
  25180. }
  25181. }
  25182. };
  25183. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  25184. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  25185. if (replace === void 0) { replace = false; }
  25186. if (attachCameraControls === void 0) { attachCameraControls = false; }
  25187. this.createDefaultLight(replace);
  25188. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  25189. };
  25190. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  25191. if (pbr === void 0) { pbr = false; }
  25192. if (scale === void 0) { scale = 1000; }
  25193. if (blur === void 0) { blur = 0; }
  25194. if (environmentTexture) {
  25195. this.environmentTexture = environmentTexture;
  25196. }
  25197. if (!this.environmentTexture) {
  25198. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  25199. return null;
  25200. }
  25201. // Skybox
  25202. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  25203. if (pbr) {
  25204. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  25205. hdrSkyboxMaterial.backFaceCulling = false;
  25206. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  25207. if (hdrSkyboxMaterial.reflectionTexture) {
  25208. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  25209. }
  25210. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  25211. hdrSkyboxMaterial.disableLighting = true;
  25212. hdrSkyboxMaterial.twoSidedLighting = true;
  25213. hdrSkybox.infiniteDistance = true;
  25214. hdrSkybox.material = hdrSkyboxMaterial;
  25215. }
  25216. else {
  25217. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  25218. skyboxMaterial.backFaceCulling = false;
  25219. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  25220. if (skyboxMaterial.reflectionTexture) {
  25221. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  25222. }
  25223. skyboxMaterial.disableLighting = true;
  25224. hdrSkybox.infiniteDistance = true;
  25225. hdrSkybox.material = skyboxMaterial;
  25226. }
  25227. return hdrSkybox;
  25228. };
  25229. Scene.prototype.createDefaultEnvironment = function (options) {
  25230. if (BABYLON.EnvironmentHelper) {
  25231. return new BABYLON.EnvironmentHelper(options, this);
  25232. }
  25233. return null;
  25234. };
  25235. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  25236. if (webVROptions === void 0) { webVROptions = {}; }
  25237. return new BABYLON.VRExperienceHelper(this, webVROptions);
  25238. };
  25239. // Tags
  25240. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  25241. if (tagsQuery === undefined) {
  25242. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  25243. return list;
  25244. }
  25245. var listByTags = [];
  25246. forEach = forEach || (function (item) { return; });
  25247. for (var i in list) {
  25248. var item = list[i];
  25249. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  25250. listByTags.push(item);
  25251. forEach(item);
  25252. }
  25253. }
  25254. return listByTags;
  25255. };
  25256. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  25257. return this._getByTags(this.meshes, tagsQuery, forEach);
  25258. };
  25259. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  25260. return this._getByTags(this.cameras, tagsQuery, forEach);
  25261. };
  25262. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  25263. return this._getByTags(this.lights, tagsQuery, forEach);
  25264. };
  25265. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  25266. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  25267. };
  25268. /**
  25269. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  25270. * This allowed control for front to back rendering or reversly depending of the special needs.
  25271. *
  25272. * @param renderingGroupId The rendering group id corresponding to its index
  25273. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  25274. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  25275. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  25276. */
  25277. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  25278. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  25279. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  25280. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  25281. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  25282. };
  25283. /**
  25284. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  25285. *
  25286. * @param renderingGroupId The rendering group id corresponding to its index
  25287. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  25288. * @param depth Automatically clears depth between groups if true and autoClear is true.
  25289. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  25290. */
  25291. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  25292. if (depth === void 0) { depth = true; }
  25293. if (stencil === void 0) { stencil = true; }
  25294. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  25295. };
  25296. /**
  25297. * Will flag all materials as dirty to trigger new shader compilation
  25298. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  25299. */
  25300. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  25301. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  25302. var material = _a[_i];
  25303. if (predicate && !predicate(material)) {
  25304. continue;
  25305. }
  25306. material.markAsDirty(flag);
  25307. }
  25308. };
  25309. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  25310. var _this = this;
  25311. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  25312. this._activeRequests.push(request);
  25313. request.onCompleteObservable.add(function (request) {
  25314. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  25315. });
  25316. return request;
  25317. };
  25318. /** @ignore */
  25319. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  25320. var _this = this;
  25321. return new Promise(function (resolve, reject) {
  25322. _this._loadFile(url, function (data) {
  25323. resolve(data);
  25324. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  25325. reject(exception);
  25326. });
  25327. });
  25328. };
  25329. // Statics
  25330. Scene._FOGMODE_NONE = 0;
  25331. Scene._FOGMODE_EXP = 1;
  25332. Scene._FOGMODE_EXP2 = 2;
  25333. Scene._FOGMODE_LINEAR = 3;
  25334. Scene._uniqueIdCounter = 0;
  25335. Scene.MinDeltaTime = 1.0;
  25336. Scene.MaxDeltaTime = 1000.0;
  25337. /** The distance in pixel that you have to move to prevent some events */
  25338. Scene.DragMovementThreshold = 10; // in pixels
  25339. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  25340. Scene.LongPressDelay = 500; // in milliseconds
  25341. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  25342. Scene.DoubleClickDelay = 300; // in milliseconds
  25343. /** If you need to check double click without raising a single click at first click, enable this flag */
  25344. Scene.ExclusiveDoubleClickMode = false;
  25345. return Scene;
  25346. }());
  25347. BABYLON.Scene = Scene;
  25348. })(BABYLON || (BABYLON = {}));
  25349. //# sourceMappingURL=babylon.scene.js.map
  25350. var BABYLON;
  25351. (function (BABYLON) {
  25352. /**
  25353. * Set of assets to keep when moving a scene into an asset container.
  25354. */
  25355. var KeepAssets = /** @class */ (function () {
  25356. function KeepAssets() {
  25357. /**
  25358. * Cameras to keep.
  25359. */
  25360. this.cameras = new Array();
  25361. /**
  25362. * Lights to keep.
  25363. */
  25364. this.lights = new Array();
  25365. /**
  25366. * Meshes to keep.
  25367. */
  25368. this.meshes = new Array();
  25369. /**
  25370. * Skeletons to keep.
  25371. */
  25372. this.skeletons = new Array();
  25373. /**
  25374. * ParticleSystems to keep.
  25375. */
  25376. this.particleSystems = new Array();
  25377. /**
  25378. * Animations to keep.
  25379. */
  25380. this.animations = new Array();
  25381. /**
  25382. * MultiMaterials to keep.
  25383. */
  25384. this.multiMaterials = new Array();
  25385. /**
  25386. * Materials to keep.
  25387. */
  25388. this.materials = new Array();
  25389. /**
  25390. * MorphTargetManagers to keep.
  25391. */
  25392. this.morphTargetManagers = new Array();
  25393. /**
  25394. * Geometries to keep.
  25395. */
  25396. this.geometries = new Array();
  25397. /**
  25398. * TransformNodes to keep.
  25399. */
  25400. this.transformNodes = new Array();
  25401. /**
  25402. * LensFlareSystems to keep.
  25403. */
  25404. this.lensFlareSystems = new Array();
  25405. /**
  25406. * ShadowGenerators to keep.
  25407. */
  25408. this.shadowGenerators = new Array();
  25409. /**
  25410. * ActionManagers to keep.
  25411. */
  25412. this.actionManagers = new Array();
  25413. /**
  25414. * Sounds to keep.
  25415. */
  25416. this.sounds = new Array();
  25417. }
  25418. return KeepAssets;
  25419. }());
  25420. BABYLON.KeepAssets = KeepAssets;
  25421. /**
  25422. * Container with a set of assets that can be added or removed from a scene.
  25423. */
  25424. var AssetContainer = /** @class */ (function () {
  25425. /**
  25426. * Instantiates an AssetContainer.
  25427. * @param scene The scene the AssetContainer belongs to.
  25428. */
  25429. function AssetContainer(scene) {
  25430. // Objects
  25431. /**
  25432. * Cameras populated in the container.
  25433. */
  25434. this.cameras = new Array();
  25435. /**
  25436. * Lights populated in the container.
  25437. */
  25438. this.lights = new Array();
  25439. /**
  25440. * Meshes populated in the container.
  25441. */
  25442. this.meshes = new Array();
  25443. /**
  25444. * Skeletons populated in the container.
  25445. */
  25446. this.skeletons = new Array();
  25447. /**
  25448. * ParticleSystems populated in the container.
  25449. */
  25450. this.particleSystems = new Array();
  25451. /**
  25452. * Animations populated in the container.
  25453. */
  25454. this.animations = new Array();
  25455. /**
  25456. * MultiMaterials populated in the container.
  25457. */
  25458. this.multiMaterials = new Array();
  25459. /**
  25460. * Materials populated in the container.
  25461. */
  25462. this.materials = new Array();
  25463. /**
  25464. * MorphTargetManagers populated in the container.
  25465. */
  25466. this.morphTargetManagers = new Array();
  25467. /**
  25468. * Geometries populated in the container.
  25469. */
  25470. this.geometries = new Array();
  25471. /**
  25472. * TransformNodes populated in the container.
  25473. */
  25474. this.transformNodes = new Array();
  25475. /**
  25476. * LensFlareSystems populated in the container.
  25477. */
  25478. this.lensFlareSystems = new Array();
  25479. /**
  25480. * ShadowGenerators populated in the container.
  25481. */
  25482. this.shadowGenerators = new Array();
  25483. /**
  25484. * ActionManagers populated in the container.
  25485. */
  25486. this.actionManagers = new Array();
  25487. /**
  25488. * Sounds populated in the container.
  25489. */
  25490. this.sounds = new Array();
  25491. this.scene = scene;
  25492. }
  25493. /**
  25494. * Adds all the assets from the container to the scene.
  25495. */
  25496. AssetContainer.prototype.addAllToScene = function () {
  25497. var _this = this;
  25498. this.cameras.forEach(function (o) {
  25499. _this.scene.addCamera(o);
  25500. });
  25501. this.lights.forEach(function (o) {
  25502. _this.scene.addLight(o);
  25503. });
  25504. this.meshes.forEach(function (o) {
  25505. _this.scene.addMesh(o);
  25506. });
  25507. this.skeletons.forEach(function (o) {
  25508. _this.scene.addSkeleton(o);
  25509. });
  25510. this.particleSystems.forEach(function (o) {
  25511. _this.scene.addParticleSystem(o);
  25512. });
  25513. this.animations.forEach(function (o) {
  25514. _this.scene.addAnimation(o);
  25515. });
  25516. this.multiMaterials.forEach(function (o) {
  25517. _this.scene.addMultiMaterial(o);
  25518. });
  25519. this.materials.forEach(function (o) {
  25520. _this.scene.addMaterial(o);
  25521. });
  25522. this.morphTargetManagers.forEach(function (o) {
  25523. _this.scene.addMorphTargetManager(o);
  25524. });
  25525. this.geometries.forEach(function (o) {
  25526. _this.scene.addGeometry(o);
  25527. });
  25528. this.transformNodes.forEach(function (o) {
  25529. _this.scene.addTransformNode(o);
  25530. });
  25531. this.lensFlareSystems.forEach(function (o) {
  25532. _this.scene.addLensFlareSystem(o);
  25533. });
  25534. this.actionManagers.forEach(function (o) {
  25535. _this.scene.addActionManager(o);
  25536. });
  25537. this.sounds.forEach(function (o) {
  25538. o.play();
  25539. o.autoplay = true;
  25540. _this.scene.mainSoundTrack.AddSound(o);
  25541. });
  25542. };
  25543. /**
  25544. * Removes all the assets in the container from the scene
  25545. */
  25546. AssetContainer.prototype.removeAllFromScene = function () {
  25547. var _this = this;
  25548. this.cameras.forEach(function (o) {
  25549. _this.scene.removeCamera(o);
  25550. });
  25551. this.lights.forEach(function (o) {
  25552. _this.scene.removeLight(o);
  25553. });
  25554. this.meshes.forEach(function (o) {
  25555. _this.scene.removeMesh(o);
  25556. });
  25557. this.skeletons.forEach(function (o) {
  25558. _this.scene.removeSkeleton(o);
  25559. });
  25560. this.particleSystems.forEach(function (o) {
  25561. _this.scene.removeParticleSystem(o);
  25562. });
  25563. this.animations.forEach(function (o) {
  25564. _this.scene.removeAnimation(o);
  25565. });
  25566. this.multiMaterials.forEach(function (o) {
  25567. _this.scene.removeMultiMaterial(o);
  25568. });
  25569. this.materials.forEach(function (o) {
  25570. _this.scene.removeMaterial(o);
  25571. });
  25572. this.morphTargetManagers.forEach(function (o) {
  25573. _this.scene.removeMorphTargetManager(o);
  25574. });
  25575. this.geometries.forEach(function (o) {
  25576. _this.scene.removeGeometry(o);
  25577. });
  25578. this.transformNodes.forEach(function (o) {
  25579. _this.scene.removeTransformNode(o);
  25580. });
  25581. this.lensFlareSystems.forEach(function (o) {
  25582. _this.scene.removeLensFlareSystem(o);
  25583. });
  25584. this.actionManagers.forEach(function (o) {
  25585. _this.scene.removeActionManager(o);
  25586. });
  25587. this.sounds.forEach(function (o) {
  25588. o.stop();
  25589. o.autoplay = false;
  25590. _this.scene.mainSoundTrack.RemoveSound(o);
  25591. });
  25592. };
  25593. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  25594. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  25595. var asset = sourceAssets_1[_i];
  25596. var move = true;
  25597. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  25598. var keepAsset = keepAssets_1[_a];
  25599. if (asset === keepAsset) {
  25600. move = false;
  25601. break;
  25602. }
  25603. }
  25604. if (move) {
  25605. targetAssets.push(asset);
  25606. }
  25607. }
  25608. };
  25609. /**
  25610. * Removes all the assets contained in the scene and adds them to the container.
  25611. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  25612. */
  25613. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  25614. if (keepAssets === undefined) {
  25615. keepAssets = new KeepAssets();
  25616. }
  25617. this._moveAssets(this.scene.cameras, this.cameras, keepAssets.cameras);
  25618. this._moveAssets(this.scene.meshes, this.meshes, keepAssets.meshes);
  25619. this._moveAssets(this.scene.getGeometries(), this.geometries, keepAssets.geometries);
  25620. this._moveAssets(this.scene.materials, this.materials, keepAssets.materials);
  25621. this._moveAssets(this.scene._actionManagers, this.actionManagers, keepAssets.actionManagers);
  25622. this._moveAssets(this.scene.animations, this.animations, keepAssets.animations);
  25623. this._moveAssets(this.scene.lensFlareSystems, this.lensFlareSystems, keepAssets.lensFlareSystems);
  25624. this._moveAssets(this.scene.lights, this.lights, keepAssets.lights);
  25625. this._moveAssets(this.scene.morphTargetManagers, this.morphTargetManagers, keepAssets.morphTargetManagers);
  25626. this._moveAssets(this.scene.multiMaterials, this.multiMaterials, keepAssets.multiMaterials);
  25627. this._moveAssets(this.scene.skeletons, this.skeletons, keepAssets.skeletons);
  25628. this._moveAssets(this.scene.particleSystems, this.particleSystems, keepAssets.particleSystems);
  25629. this._moveAssets(this.scene.mainSoundTrack.soundCollection, this.sounds, keepAssets.sounds);
  25630. this._moveAssets(this.scene.transformNodes, this.transformNodes, keepAssets.transformNodes);
  25631. this.removeAllFromScene();
  25632. };
  25633. return AssetContainer;
  25634. }());
  25635. BABYLON.AssetContainer = AssetContainer;
  25636. })(BABYLON || (BABYLON = {}));
  25637. //# sourceMappingURL=babylon.assetContainer.js.map
  25638. var BABYLON;
  25639. (function (BABYLON) {
  25640. var Buffer = /** @class */ (function () {
  25641. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  25642. if (instanced === void 0) { instanced = false; }
  25643. if (engine instanceof BABYLON.Mesh) {
  25644. this._engine = engine.getScene().getEngine();
  25645. }
  25646. else {
  25647. this._engine = engine;
  25648. }
  25649. this._updatable = updatable;
  25650. this._instanced = instanced;
  25651. this._data = data;
  25652. this._strideSize = stride;
  25653. if (!postponeInternalCreation) {
  25654. this.create();
  25655. }
  25656. }
  25657. /**
  25658. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  25659. * @param kind defines the vertex buffer kind (position, normal, etc.)
  25660. * @param offset defines offset in the buffer (0 by default)
  25661. * @param size defines the size in floats of attributes (position is 3 for instance)
  25662. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  25663. * @param instanced defines if the vertex buffer contains indexed data
  25664. * @returns the new vertex buffer
  25665. */
  25666. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced) {
  25667. // a lot of these parameters are ignored as they are overriden by the buffer
  25668. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, instanced === undefined ? this._instanced : instanced, offset, size);
  25669. };
  25670. // Properties
  25671. Buffer.prototype.isUpdatable = function () {
  25672. return this._updatable;
  25673. };
  25674. Buffer.prototype.getData = function () {
  25675. return this._data;
  25676. };
  25677. Buffer.prototype.getBuffer = function () {
  25678. return this._buffer;
  25679. };
  25680. Buffer.prototype.getStrideSize = function () {
  25681. return this._strideSize;
  25682. };
  25683. // public getIsInstanced(): boolean {
  25684. // return this._instanced;
  25685. // }
  25686. // public get instanceDivisor(): number {
  25687. // return this._instanceDivisor;
  25688. // }
  25689. // public set instanceDivisor(value: number) {
  25690. // this._instanceDivisor = value;
  25691. // if (value == 0) {
  25692. // this._instanced = false;
  25693. // } else {
  25694. // this._instanced = true;
  25695. // }
  25696. // }
  25697. // Methods
  25698. Buffer.prototype.create = function (data) {
  25699. if (data === void 0) { data = null; }
  25700. if (!data && this._buffer) {
  25701. return; // nothing to do
  25702. }
  25703. data = data || this._data;
  25704. if (!data) {
  25705. return;
  25706. }
  25707. if (!this._buffer) {
  25708. if (this._updatable) {
  25709. this._buffer = this._engine.createDynamicVertexBuffer(data);
  25710. this._data = data;
  25711. }
  25712. else {
  25713. this._buffer = this._engine.createVertexBuffer(data);
  25714. }
  25715. }
  25716. else if (this._updatable) {
  25717. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  25718. this._data = data;
  25719. }
  25720. };
  25721. Buffer.prototype._rebuild = function () {
  25722. this._buffer = null;
  25723. this.create(this._data);
  25724. };
  25725. Buffer.prototype.update = function (data) {
  25726. this.create(data);
  25727. };
  25728. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  25729. if (!this._buffer) {
  25730. return;
  25731. }
  25732. if (this._updatable) {
  25733. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  25734. this._data = null;
  25735. }
  25736. };
  25737. Buffer.prototype.dispose = function () {
  25738. if (!this._buffer) {
  25739. return;
  25740. }
  25741. if (this._engine._releaseBuffer(this._buffer)) {
  25742. this._buffer = null;
  25743. }
  25744. };
  25745. return Buffer;
  25746. }());
  25747. BABYLON.Buffer = Buffer;
  25748. })(BABYLON || (BABYLON = {}));
  25749. //# sourceMappingURL=babylon.buffer.js.map
  25750. var BABYLON;
  25751. (function (BABYLON) {
  25752. var VertexBuffer = /** @class */ (function () {
  25753. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  25754. if (data instanceof BABYLON.Buffer) {
  25755. if (!stride) {
  25756. stride = data.getStrideSize();
  25757. }
  25758. this._buffer = data;
  25759. this._ownsBuffer = false;
  25760. }
  25761. else {
  25762. if (!stride) {
  25763. stride = VertexBuffer.DeduceStride(kind);
  25764. }
  25765. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  25766. this._ownsBuffer = true;
  25767. }
  25768. this._stride = stride;
  25769. this._instanced = instanced !== undefined ? instanced : false;
  25770. this._instanceDivisor = instanced ? 1 : 0;
  25771. this._offset = offset ? offset : 0;
  25772. this._size = size ? size : stride;
  25773. this._kind = kind;
  25774. }
  25775. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  25776. /**
  25777. * Gets or sets the instance divisor when in instanced mode
  25778. */
  25779. get: function () {
  25780. return this._instanceDivisor;
  25781. },
  25782. set: function (value) {
  25783. this._instanceDivisor = value;
  25784. if (value == 0) {
  25785. this._instanced = false;
  25786. }
  25787. else {
  25788. this._instanced = true;
  25789. }
  25790. },
  25791. enumerable: true,
  25792. configurable: true
  25793. });
  25794. VertexBuffer.prototype._rebuild = function () {
  25795. if (!this._buffer) {
  25796. return;
  25797. }
  25798. this._buffer._rebuild();
  25799. };
  25800. /**
  25801. * Returns the kind of the VertexBuffer (string).
  25802. */
  25803. VertexBuffer.prototype.getKind = function () {
  25804. return this._kind;
  25805. };
  25806. // Properties
  25807. /**
  25808. * Boolean : is the VertexBuffer updatable ?
  25809. */
  25810. VertexBuffer.prototype.isUpdatable = function () {
  25811. return this._buffer.isUpdatable();
  25812. };
  25813. /**
  25814. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  25815. */
  25816. VertexBuffer.prototype.getData = function () {
  25817. return this._buffer.getData();
  25818. };
  25819. /**
  25820. * Returns the WebGLBuffer associated to the VertexBuffer.
  25821. */
  25822. VertexBuffer.prototype.getBuffer = function () {
  25823. return this._buffer.getBuffer();
  25824. };
  25825. /**
  25826. * Returns the stride of the VertexBuffer (integer).
  25827. */
  25828. VertexBuffer.prototype.getStrideSize = function () {
  25829. return this._stride;
  25830. };
  25831. /**
  25832. * Returns the offset (integer).
  25833. */
  25834. VertexBuffer.prototype.getOffset = function () {
  25835. return this._offset;
  25836. };
  25837. /**
  25838. * Returns the VertexBuffer total size (integer).
  25839. */
  25840. VertexBuffer.prototype.getSize = function () {
  25841. return this._size;
  25842. };
  25843. /**
  25844. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  25845. */
  25846. VertexBuffer.prototype.getIsInstanced = function () {
  25847. return this._instanced;
  25848. };
  25849. /**
  25850. * Returns the instancing divisor, zero for non-instanced (integer).
  25851. */
  25852. VertexBuffer.prototype.getInstanceDivisor = function () {
  25853. return this._instanceDivisor;
  25854. };
  25855. // Methods
  25856. /**
  25857. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  25858. * Returns the created WebGLBuffer.
  25859. */
  25860. VertexBuffer.prototype.create = function (data) {
  25861. return this._buffer.create(data);
  25862. };
  25863. /**
  25864. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  25865. * This function will create a new buffer if the current one is not updatable
  25866. * Returns the updated WebGLBuffer.
  25867. */
  25868. VertexBuffer.prototype.update = function (data) {
  25869. return this._buffer.update(data);
  25870. };
  25871. /**
  25872. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  25873. * Returns the directly updated WebGLBuffer.
  25874. */
  25875. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  25876. return this._buffer.updateDirectly(data, offset);
  25877. };
  25878. /**
  25879. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  25880. */
  25881. VertexBuffer.prototype.dispose = function () {
  25882. if (this._ownsBuffer) {
  25883. this._buffer.dispose();
  25884. }
  25885. };
  25886. Object.defineProperty(VertexBuffer, "PositionKind", {
  25887. get: function () {
  25888. return VertexBuffer._PositionKind;
  25889. },
  25890. enumerable: true,
  25891. configurable: true
  25892. });
  25893. Object.defineProperty(VertexBuffer, "NormalKind", {
  25894. get: function () {
  25895. return VertexBuffer._NormalKind;
  25896. },
  25897. enumerable: true,
  25898. configurable: true
  25899. });
  25900. Object.defineProperty(VertexBuffer, "TangentKind", {
  25901. get: function () {
  25902. return VertexBuffer._TangentKind;
  25903. },
  25904. enumerable: true,
  25905. configurable: true
  25906. });
  25907. Object.defineProperty(VertexBuffer, "UVKind", {
  25908. get: function () {
  25909. return VertexBuffer._UVKind;
  25910. },
  25911. enumerable: true,
  25912. configurable: true
  25913. });
  25914. Object.defineProperty(VertexBuffer, "UV2Kind", {
  25915. get: function () {
  25916. return VertexBuffer._UV2Kind;
  25917. },
  25918. enumerable: true,
  25919. configurable: true
  25920. });
  25921. Object.defineProperty(VertexBuffer, "UV3Kind", {
  25922. get: function () {
  25923. return VertexBuffer._UV3Kind;
  25924. },
  25925. enumerable: true,
  25926. configurable: true
  25927. });
  25928. Object.defineProperty(VertexBuffer, "UV4Kind", {
  25929. get: function () {
  25930. return VertexBuffer._UV4Kind;
  25931. },
  25932. enumerable: true,
  25933. configurable: true
  25934. });
  25935. Object.defineProperty(VertexBuffer, "UV5Kind", {
  25936. get: function () {
  25937. return VertexBuffer._UV5Kind;
  25938. },
  25939. enumerable: true,
  25940. configurable: true
  25941. });
  25942. Object.defineProperty(VertexBuffer, "UV6Kind", {
  25943. get: function () {
  25944. return VertexBuffer._UV6Kind;
  25945. },
  25946. enumerable: true,
  25947. configurable: true
  25948. });
  25949. Object.defineProperty(VertexBuffer, "ColorKind", {
  25950. get: function () {
  25951. return VertexBuffer._ColorKind;
  25952. },
  25953. enumerable: true,
  25954. configurable: true
  25955. });
  25956. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  25957. get: function () {
  25958. return VertexBuffer._MatricesIndicesKind;
  25959. },
  25960. enumerable: true,
  25961. configurable: true
  25962. });
  25963. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  25964. get: function () {
  25965. return VertexBuffer._MatricesWeightsKind;
  25966. },
  25967. enumerable: true,
  25968. configurable: true
  25969. });
  25970. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  25971. get: function () {
  25972. return VertexBuffer._MatricesIndicesExtraKind;
  25973. },
  25974. enumerable: true,
  25975. configurable: true
  25976. });
  25977. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  25978. get: function () {
  25979. return VertexBuffer._MatricesWeightsExtraKind;
  25980. },
  25981. enumerable: true,
  25982. configurable: true
  25983. });
  25984. /**
  25985. * Deduces the stride given a kind.
  25986. * @param kind The kind string to deduce
  25987. * @returns The deduced stride
  25988. */
  25989. VertexBuffer.DeduceStride = function (kind) {
  25990. switch (kind) {
  25991. case VertexBuffer.UVKind:
  25992. case VertexBuffer.UV2Kind:
  25993. case VertexBuffer.UV3Kind:
  25994. case VertexBuffer.UV4Kind:
  25995. case VertexBuffer.UV5Kind:
  25996. case VertexBuffer.UV6Kind:
  25997. return 2;
  25998. case VertexBuffer.NormalKind:
  25999. case VertexBuffer.PositionKind:
  26000. return 3;
  26001. case VertexBuffer.ColorKind:
  26002. case VertexBuffer.MatricesIndicesKind:
  26003. case VertexBuffer.MatricesIndicesExtraKind:
  26004. case VertexBuffer.MatricesWeightsKind:
  26005. case VertexBuffer.MatricesWeightsExtraKind:
  26006. case VertexBuffer.TangentKind:
  26007. return 4;
  26008. default:
  26009. throw new Error("Invalid kind '" + kind + "'");
  26010. }
  26011. };
  26012. // Enums
  26013. VertexBuffer._PositionKind = "position";
  26014. VertexBuffer._NormalKind = "normal";
  26015. VertexBuffer._TangentKind = "tangent";
  26016. VertexBuffer._UVKind = "uv";
  26017. VertexBuffer._UV2Kind = "uv2";
  26018. VertexBuffer._UV3Kind = "uv3";
  26019. VertexBuffer._UV4Kind = "uv4";
  26020. VertexBuffer._UV5Kind = "uv5";
  26021. VertexBuffer._UV6Kind = "uv6";
  26022. VertexBuffer._ColorKind = "color";
  26023. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  26024. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  26025. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  26026. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  26027. return VertexBuffer;
  26028. }());
  26029. BABYLON.VertexBuffer = VertexBuffer;
  26030. })(BABYLON || (BABYLON = {}));
  26031. //# sourceMappingURL=babylon.vertexBuffer.js.map
  26032. var BABYLON;
  26033. (function (BABYLON) {
  26034. /**
  26035. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  26036. */
  26037. var DummyInternalTextureTracker = /** @class */ (function () {
  26038. function DummyInternalTextureTracker() {
  26039. /**
  26040. * Gets or set the previous tracker in the list
  26041. */
  26042. this.previous = null;
  26043. /**
  26044. * Gets or set the next tracker in the list
  26045. */
  26046. this.next = null;
  26047. }
  26048. return DummyInternalTextureTracker;
  26049. }());
  26050. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  26051. })(BABYLON || (BABYLON = {}));
  26052. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  26053. var BABYLON;
  26054. (function (BABYLON) {
  26055. /**
  26056. * Class used to store data associated with WebGL texture data for the engine
  26057. * This class should not be used directly
  26058. */
  26059. var InternalTexture = /** @class */ (function () {
  26060. /**
  26061. * Creates a new InternalTexture
  26062. * @param engine defines the engine to use
  26063. * @param dataSource defines the type of data that will be used
  26064. */
  26065. function InternalTexture(engine, dataSource) {
  26066. /**
  26067. * Observable called when the texture is loaded
  26068. */
  26069. this.onLoadedObservable = new BABYLON.Observable();
  26070. /**
  26071. * Gets or set the previous tracker in the list
  26072. */
  26073. this.previous = null;
  26074. /**
  26075. * Gets or set the next tracker in the list
  26076. */
  26077. this.next = null;
  26078. // Private
  26079. /** @ignore */
  26080. this._initialSlot = -1;
  26081. /** @ignore */
  26082. this._designatedSlot = -1;
  26083. /** @ignore */
  26084. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  26085. /** @ignore */
  26086. this._comparisonFunction = 0;
  26087. /** @ignore */
  26088. this._references = 1;
  26089. this._engine = engine;
  26090. this._dataSource = dataSource;
  26091. this._webGLTexture = engine._createTexture();
  26092. }
  26093. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  26094. /**
  26095. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  26096. */
  26097. get: function () {
  26098. return this._dataSource;
  26099. },
  26100. enumerable: true,
  26101. configurable: true
  26102. });
  26103. /**
  26104. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  26105. */
  26106. InternalTexture.prototype.incrementReferences = function () {
  26107. this._references++;
  26108. };
  26109. /**
  26110. * Change the size of the texture (not the size of the content)
  26111. * @param width defines the new width
  26112. * @param height defines the new height
  26113. * @param depth defines the new depth (1 by default)
  26114. */
  26115. InternalTexture.prototype.updateSize = function (width, height, depth) {
  26116. if (depth === void 0) { depth = 1; }
  26117. this.width = width;
  26118. this.height = height;
  26119. this.depth = depth;
  26120. this.baseWidth = width;
  26121. this.baseHeight = height;
  26122. this.baseDepth = depth;
  26123. this._size = width * height * depth;
  26124. };
  26125. /** @ignore */
  26126. InternalTexture.prototype._rebuild = function () {
  26127. var _this = this;
  26128. var proxy;
  26129. this.isReady = false;
  26130. this._cachedCoordinatesMode = null;
  26131. this._cachedWrapU = null;
  26132. this._cachedWrapV = null;
  26133. this._cachedAnisotropicFilteringLevel = null;
  26134. switch (this._dataSource) {
  26135. case InternalTexture.DATASOURCE_TEMP:
  26136. return;
  26137. case InternalTexture.DATASOURCE_URL:
  26138. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  26139. _this.isReady = true;
  26140. }, null, this._buffer, undefined, this.format);
  26141. proxy._swapAndDie(this);
  26142. return;
  26143. case InternalTexture.DATASOURCE_RAW:
  26144. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  26145. proxy._swapAndDie(this);
  26146. this.isReady = true;
  26147. return;
  26148. case InternalTexture.DATASOURCE_RAW3D:
  26149. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  26150. proxy._swapAndDie(this);
  26151. this.isReady = true;
  26152. return;
  26153. case InternalTexture.DATASOURCE_DYNAMIC:
  26154. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  26155. proxy._swapAndDie(this);
  26156. // The engine will make sure to update content so no need to flag it as isReady = true
  26157. return;
  26158. case InternalTexture.DATASOURCE_RENDERTARGET:
  26159. var options = new BABYLON.RenderTargetCreationOptions();
  26160. options.generateDepthBuffer = this._generateDepthBuffer;
  26161. options.generateMipMaps = this.generateMipMaps;
  26162. options.generateStencilBuffer = this._generateStencilBuffer;
  26163. options.samplingMode = this.samplingMode;
  26164. options.type = this.type;
  26165. if (this.isCube) {
  26166. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  26167. }
  26168. else {
  26169. var size = {
  26170. width: this.width,
  26171. height: this.height
  26172. };
  26173. proxy = this._engine.createRenderTargetTexture(size, options);
  26174. }
  26175. proxy._swapAndDie(this);
  26176. this.isReady = true;
  26177. return;
  26178. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  26179. var depthTextureOptions = {
  26180. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  26181. comparisonFunction: this._comparisonFunction,
  26182. generateStencil: this._generateStencilBuffer,
  26183. };
  26184. if (this.isCube) {
  26185. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  26186. }
  26187. else {
  26188. proxy = this._engine.createDepthStencilCubeTexture(this.width, depthTextureOptions);
  26189. }
  26190. proxy._swapAndDie(this);
  26191. this.isReady = true;
  26192. return;
  26193. case InternalTexture.DATASOURCE_CUBE:
  26194. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  26195. _this.isReady = true;
  26196. }, null, this.format, this._extension);
  26197. proxy._swapAndDie(this);
  26198. return;
  26199. case InternalTexture.DATASOURCE_CUBERAW:
  26200. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  26201. proxy._swapAndDie(this);
  26202. this.isReady = true;
  26203. return;
  26204. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  26205. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  26206. if (proxy) {
  26207. proxy._swapAndDie(_this);
  26208. }
  26209. _this.isReady = true;
  26210. }, null, this.format, this._extension);
  26211. return;
  26212. }
  26213. };
  26214. InternalTexture.prototype._swapAndDie = function (target) {
  26215. target._webGLTexture = this._webGLTexture;
  26216. if (this._framebuffer) {
  26217. target._framebuffer = this._framebuffer;
  26218. }
  26219. if (this._depthStencilBuffer) {
  26220. target._depthStencilBuffer = this._depthStencilBuffer;
  26221. }
  26222. if (this._lodTextureHigh) {
  26223. if (target._lodTextureHigh) {
  26224. target._lodTextureHigh.dispose();
  26225. }
  26226. target._lodTextureHigh = this._lodTextureHigh;
  26227. }
  26228. if (this._lodTextureMid) {
  26229. if (target._lodTextureMid) {
  26230. target._lodTextureMid.dispose();
  26231. }
  26232. target._lodTextureMid = this._lodTextureMid;
  26233. }
  26234. if (this._lodTextureLow) {
  26235. if (target._lodTextureLow) {
  26236. target._lodTextureLow.dispose();
  26237. }
  26238. target._lodTextureLow = this._lodTextureLow;
  26239. }
  26240. var cache = this._engine.getLoadedTexturesCache();
  26241. var index = cache.indexOf(this);
  26242. if (index !== -1) {
  26243. cache.splice(index, 1);
  26244. }
  26245. };
  26246. /**
  26247. * Dispose the current allocated resources
  26248. */
  26249. InternalTexture.prototype.dispose = function () {
  26250. if (!this._webGLTexture) {
  26251. return;
  26252. }
  26253. this._references--;
  26254. if (this._references === 0) {
  26255. this._engine._releaseTexture(this);
  26256. this._webGLTexture = null;
  26257. this.previous = null;
  26258. this.next = null;
  26259. }
  26260. };
  26261. /**
  26262. * The source of the texture data is unknown
  26263. */
  26264. InternalTexture.DATASOURCE_UNKNOWN = 0;
  26265. /**
  26266. * Texture data comes from an URL
  26267. */
  26268. InternalTexture.DATASOURCE_URL = 1;
  26269. /**
  26270. * Texture data is only used for temporary storage
  26271. */
  26272. InternalTexture.DATASOURCE_TEMP = 2;
  26273. /**
  26274. * Texture data comes from raw data (ArrayBuffer)
  26275. */
  26276. InternalTexture.DATASOURCE_RAW = 3;
  26277. /**
  26278. * Texture content is dynamic (video or dynamic texture)
  26279. */
  26280. InternalTexture.DATASOURCE_DYNAMIC = 4;
  26281. /**
  26282. * Texture content is generated by rendering to it
  26283. */
  26284. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  26285. /**
  26286. * Texture content is part of a multi render target process
  26287. */
  26288. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  26289. /**
  26290. * Texture data comes from a cube data file
  26291. */
  26292. InternalTexture.DATASOURCE_CUBE = 7;
  26293. /**
  26294. * Texture data comes from a raw cube data
  26295. */
  26296. InternalTexture.DATASOURCE_CUBERAW = 8;
  26297. /**
  26298. * Texture data come from a prefiltered cube data file
  26299. */
  26300. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  26301. /**
  26302. * Texture content is raw 3D data
  26303. */
  26304. InternalTexture.DATASOURCE_RAW3D = 10;
  26305. /**
  26306. * Texture content is a depth texture
  26307. */
  26308. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  26309. return InternalTexture;
  26310. }());
  26311. BABYLON.InternalTexture = InternalTexture;
  26312. })(BABYLON || (BABYLON = {}));
  26313. //# sourceMappingURL=babylon.internalTexture.js.map
  26314. var BABYLON;
  26315. (function (BABYLON) {
  26316. var BaseTexture = /** @class */ (function () {
  26317. function BaseTexture(scene) {
  26318. this._hasAlpha = false;
  26319. this.getAlphaFromRGB = false;
  26320. this.level = 1;
  26321. this.coordinatesIndex = 0;
  26322. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  26323. /**
  26324. * | Value | Type | Description |
  26325. * | ----- | ------------------ | ----------- |
  26326. * | 0 | CLAMP_ADDRESSMODE | |
  26327. * | 1 | WRAP_ADDRESSMODE | |
  26328. * | 2 | MIRROR_ADDRESSMODE | |
  26329. */
  26330. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  26331. /**
  26332. * | Value | Type | Description |
  26333. * | ----- | ------------------ | ----------- |
  26334. * | 0 | CLAMP_ADDRESSMODE | |
  26335. * | 1 | WRAP_ADDRESSMODE | |
  26336. * | 2 | MIRROR_ADDRESSMODE | |
  26337. */
  26338. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  26339. /**
  26340. * | Value | Type | Description |
  26341. * | ----- | ------------------ | ----------- |
  26342. * | 0 | CLAMP_ADDRESSMODE | |
  26343. * | 1 | WRAP_ADDRESSMODE | |
  26344. * | 2 | MIRROR_ADDRESSMODE | |
  26345. */
  26346. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  26347. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  26348. this.isCube = false;
  26349. this.is3D = false;
  26350. this.gammaSpace = true;
  26351. this.invertZ = false;
  26352. this.lodLevelInAlpha = false;
  26353. this.lodGenerationOffset = 0.0;
  26354. this.lodGenerationScale = 0.8;
  26355. this.isRenderTarget = false;
  26356. this.animations = new Array();
  26357. /**
  26358. * An event triggered when the texture is disposed.
  26359. * @type {BABYLON.Observable}
  26360. */
  26361. this.onDisposeObservable = new BABYLON.Observable();
  26362. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  26363. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  26364. if (this._scene) {
  26365. this._scene.textures.push(this);
  26366. }
  26367. this._uid = null;
  26368. }
  26369. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  26370. get: function () {
  26371. return this._hasAlpha;
  26372. },
  26373. set: function (value) {
  26374. if (this._hasAlpha === value) {
  26375. return;
  26376. }
  26377. this._hasAlpha = value;
  26378. if (this._scene) {
  26379. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  26380. }
  26381. },
  26382. enumerable: true,
  26383. configurable: true
  26384. });
  26385. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  26386. get: function () {
  26387. return this._coordinatesMode;
  26388. },
  26389. /**
  26390. * How a texture is mapped.
  26391. *
  26392. * | Value | Type | Description |
  26393. * | ----- | ----------------------------------- | ----------- |
  26394. * | 0 | EXPLICIT_MODE | |
  26395. * | 1 | SPHERICAL_MODE | |
  26396. * | 2 | PLANAR_MODE | |
  26397. * | 3 | CUBIC_MODE | |
  26398. * | 4 | PROJECTION_MODE | |
  26399. * | 5 | SKYBOX_MODE | |
  26400. * | 6 | INVCUBIC_MODE | |
  26401. * | 7 | EQUIRECTANGULAR_MODE | |
  26402. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  26403. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  26404. */
  26405. set: function (value) {
  26406. if (this._coordinatesMode === value) {
  26407. return;
  26408. }
  26409. this._coordinatesMode = value;
  26410. if (this._scene) {
  26411. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  26412. }
  26413. },
  26414. enumerable: true,
  26415. configurable: true
  26416. });
  26417. Object.defineProperty(BaseTexture.prototype, "uid", {
  26418. get: function () {
  26419. if (!this._uid) {
  26420. this._uid = BABYLON.Tools.RandomId();
  26421. }
  26422. return this._uid;
  26423. },
  26424. enumerable: true,
  26425. configurable: true
  26426. });
  26427. BaseTexture.prototype.toString = function () {
  26428. return this.name;
  26429. };
  26430. BaseTexture.prototype.getClassName = function () {
  26431. return "BaseTexture";
  26432. };
  26433. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  26434. set: function (callback) {
  26435. if (this._onDisposeObserver) {
  26436. this.onDisposeObservable.remove(this._onDisposeObserver);
  26437. }
  26438. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  26439. },
  26440. enumerable: true,
  26441. configurable: true
  26442. });
  26443. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  26444. get: function () {
  26445. return true;
  26446. },
  26447. enumerable: true,
  26448. configurable: true
  26449. });
  26450. BaseTexture.prototype.getScene = function () {
  26451. return this._scene;
  26452. };
  26453. BaseTexture.prototype.getTextureMatrix = function () {
  26454. return BABYLON.Matrix.IdentityReadOnly;
  26455. };
  26456. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  26457. return BABYLON.Matrix.IdentityReadOnly;
  26458. };
  26459. BaseTexture.prototype.getInternalTexture = function () {
  26460. return this._texture;
  26461. };
  26462. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  26463. return !this.isBlocking || this.isReady();
  26464. };
  26465. BaseTexture.prototype.isReady = function () {
  26466. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  26467. this.delayLoad();
  26468. return false;
  26469. }
  26470. if (this._texture) {
  26471. return this._texture.isReady;
  26472. }
  26473. return false;
  26474. };
  26475. BaseTexture.prototype.getSize = function () {
  26476. if (this._texture && this._texture.width) {
  26477. return new BABYLON.Size(this._texture.width, this._texture.height);
  26478. }
  26479. if (this._texture && this._texture._size) {
  26480. return new BABYLON.Size(this._texture._size, this._texture._size);
  26481. }
  26482. return BABYLON.Size.Zero();
  26483. };
  26484. BaseTexture.prototype.getBaseSize = function () {
  26485. if (!this.isReady() || !this._texture)
  26486. return BABYLON.Size.Zero();
  26487. if (this._texture._size) {
  26488. return new BABYLON.Size(this._texture._size, this._texture._size);
  26489. }
  26490. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  26491. };
  26492. BaseTexture.prototype.scale = function (ratio) {
  26493. };
  26494. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  26495. get: function () {
  26496. return false;
  26497. },
  26498. enumerable: true,
  26499. configurable: true
  26500. });
  26501. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  26502. if (!this._scene) {
  26503. return null;
  26504. }
  26505. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  26506. for (var index = 0; index < texturesCache.length; index++) {
  26507. var texturesCacheEntry = texturesCache[index];
  26508. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  26509. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  26510. texturesCacheEntry.incrementReferences();
  26511. return texturesCacheEntry;
  26512. }
  26513. }
  26514. }
  26515. return null;
  26516. };
  26517. BaseTexture.prototype._rebuild = function () {
  26518. };
  26519. BaseTexture.prototype.delayLoad = function () {
  26520. };
  26521. BaseTexture.prototype.clone = function () {
  26522. return null;
  26523. };
  26524. Object.defineProperty(BaseTexture.prototype, "textureType", {
  26525. get: function () {
  26526. if (!this._texture) {
  26527. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  26528. }
  26529. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  26530. },
  26531. enumerable: true,
  26532. configurable: true
  26533. });
  26534. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  26535. get: function () {
  26536. if (!this._texture) {
  26537. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  26538. }
  26539. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  26540. },
  26541. enumerable: true,
  26542. configurable: true
  26543. });
  26544. BaseTexture.prototype.readPixels = function (faceIndex) {
  26545. if (faceIndex === void 0) { faceIndex = 0; }
  26546. if (!this._texture) {
  26547. return null;
  26548. }
  26549. var size = this.getSize();
  26550. var scene = this.getScene();
  26551. if (!scene) {
  26552. return null;
  26553. }
  26554. var engine = scene.getEngine();
  26555. if (this._texture.isCube) {
  26556. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  26557. }
  26558. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  26559. };
  26560. BaseTexture.prototype.releaseInternalTexture = function () {
  26561. if (this._texture) {
  26562. this._texture.dispose();
  26563. this._texture = null;
  26564. }
  26565. };
  26566. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  26567. get: function () {
  26568. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  26569. return null;
  26570. }
  26571. if (!this._texture._sphericalPolynomial) {
  26572. this._texture._sphericalPolynomial =
  26573. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  26574. }
  26575. return this._texture._sphericalPolynomial;
  26576. },
  26577. set: function (value) {
  26578. if (this._texture) {
  26579. this._texture._sphericalPolynomial = value;
  26580. }
  26581. },
  26582. enumerable: true,
  26583. configurable: true
  26584. });
  26585. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  26586. get: function () {
  26587. if (this._texture) {
  26588. return this._texture._lodTextureHigh;
  26589. }
  26590. return null;
  26591. },
  26592. enumerable: true,
  26593. configurable: true
  26594. });
  26595. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  26596. get: function () {
  26597. if (this._texture) {
  26598. return this._texture._lodTextureMid;
  26599. }
  26600. return null;
  26601. },
  26602. enumerable: true,
  26603. configurable: true
  26604. });
  26605. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  26606. get: function () {
  26607. if (this._texture) {
  26608. return this._texture._lodTextureLow;
  26609. }
  26610. return null;
  26611. },
  26612. enumerable: true,
  26613. configurable: true
  26614. });
  26615. BaseTexture.prototype.dispose = function () {
  26616. if (!this._scene) {
  26617. return;
  26618. }
  26619. // Animations
  26620. this._scene.stopAnimation(this);
  26621. // Remove from scene
  26622. this._scene._removePendingData(this);
  26623. var index = this._scene.textures.indexOf(this);
  26624. if (index >= 0) {
  26625. this._scene.textures.splice(index, 1);
  26626. }
  26627. if (this._texture === undefined) {
  26628. return;
  26629. }
  26630. // Release
  26631. this.releaseInternalTexture();
  26632. // Callback
  26633. this.onDisposeObservable.notifyObservers(this);
  26634. this.onDisposeObservable.clear();
  26635. };
  26636. BaseTexture.prototype.serialize = function () {
  26637. if (!this.name) {
  26638. return null;
  26639. }
  26640. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  26641. // Animations
  26642. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  26643. return serializationObject;
  26644. };
  26645. BaseTexture.WhenAllReady = function (textures, callback) {
  26646. var numRemaining = textures.length;
  26647. if (numRemaining === 0) {
  26648. callback();
  26649. return;
  26650. }
  26651. var _loop_1 = function () {
  26652. texture = textures[i];
  26653. if (texture.isReady()) {
  26654. if (--numRemaining === 0) {
  26655. callback();
  26656. }
  26657. }
  26658. else {
  26659. onLoadObservable = texture.onLoadObservable;
  26660. var onLoadCallback_1 = function () {
  26661. onLoadObservable.removeCallback(onLoadCallback_1);
  26662. if (--numRemaining === 0) {
  26663. callback();
  26664. }
  26665. };
  26666. onLoadObservable.add(onLoadCallback_1);
  26667. }
  26668. };
  26669. var texture, onLoadObservable;
  26670. for (var i = 0; i < textures.length; i++) {
  26671. _loop_1();
  26672. }
  26673. };
  26674. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  26675. __decorate([
  26676. BABYLON.serialize()
  26677. ], BaseTexture.prototype, "name", void 0);
  26678. __decorate([
  26679. BABYLON.serialize("hasAlpha")
  26680. ], BaseTexture.prototype, "_hasAlpha", void 0);
  26681. __decorate([
  26682. BABYLON.serialize()
  26683. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  26684. __decorate([
  26685. BABYLON.serialize()
  26686. ], BaseTexture.prototype, "level", void 0);
  26687. __decorate([
  26688. BABYLON.serialize()
  26689. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  26690. __decorate([
  26691. BABYLON.serialize("coordinatesMode")
  26692. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  26693. __decorate([
  26694. BABYLON.serialize()
  26695. ], BaseTexture.prototype, "wrapU", void 0);
  26696. __decorate([
  26697. BABYLON.serialize()
  26698. ], BaseTexture.prototype, "wrapV", void 0);
  26699. __decorate([
  26700. BABYLON.serialize()
  26701. ], BaseTexture.prototype, "wrapR", void 0);
  26702. __decorate([
  26703. BABYLON.serialize()
  26704. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  26705. __decorate([
  26706. BABYLON.serialize()
  26707. ], BaseTexture.prototype, "isCube", void 0);
  26708. __decorate([
  26709. BABYLON.serialize()
  26710. ], BaseTexture.prototype, "is3D", void 0);
  26711. __decorate([
  26712. BABYLON.serialize()
  26713. ], BaseTexture.prototype, "gammaSpace", void 0);
  26714. __decorate([
  26715. BABYLON.serialize()
  26716. ], BaseTexture.prototype, "invertZ", void 0);
  26717. __decorate([
  26718. BABYLON.serialize()
  26719. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  26720. __decorate([
  26721. BABYLON.serialize()
  26722. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  26723. __decorate([
  26724. BABYLON.serialize()
  26725. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  26726. __decorate([
  26727. BABYLON.serialize()
  26728. ], BaseTexture.prototype, "isRenderTarget", void 0);
  26729. return BaseTexture;
  26730. }());
  26731. BABYLON.BaseTexture = BaseTexture;
  26732. })(BABYLON || (BABYLON = {}));
  26733. //# sourceMappingURL=babylon.baseTexture.js.map
  26734. var BABYLON;
  26735. (function (BABYLON) {
  26736. var Texture = /** @class */ (function (_super) {
  26737. __extends(Texture, _super);
  26738. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  26739. if (noMipmap === void 0) { noMipmap = false; }
  26740. if (invertY === void 0) { invertY = true; }
  26741. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  26742. if (onLoad === void 0) { onLoad = null; }
  26743. if (onError === void 0) { onError = null; }
  26744. if (buffer === void 0) { buffer = null; }
  26745. if (deleteBuffer === void 0) { deleteBuffer = false; }
  26746. var _this = _super.call(this, scene) || this;
  26747. _this.uOffset = 0;
  26748. _this.vOffset = 0;
  26749. _this.uScale = 1.0;
  26750. _this.vScale = 1.0;
  26751. _this.uAng = 0;
  26752. _this.vAng = 0;
  26753. _this.wAng = 0;
  26754. _this._isBlocking = true;
  26755. _this.name = url || "";
  26756. _this.url = url;
  26757. _this._noMipmap = noMipmap;
  26758. _this._invertY = invertY;
  26759. _this._samplingMode = samplingMode;
  26760. _this._buffer = buffer;
  26761. _this._deleteBuffer = deleteBuffer;
  26762. if (format) {
  26763. _this._format = format;
  26764. }
  26765. scene = _this.getScene();
  26766. if (!scene) {
  26767. return _this;
  26768. }
  26769. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  26770. var load = function () {
  26771. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  26772. _this.onLoadObservable.notifyObservers(_this);
  26773. }
  26774. if (onLoad) {
  26775. onLoad();
  26776. }
  26777. if (!_this.isBlocking && scene) {
  26778. scene.resetCachedMaterial();
  26779. }
  26780. };
  26781. if (!_this.url) {
  26782. _this._delayedOnLoad = load;
  26783. _this._delayedOnError = onError;
  26784. return _this;
  26785. }
  26786. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  26787. if (!_this._texture) {
  26788. if (!scene.useDelayedTextureLoading) {
  26789. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  26790. if (deleteBuffer) {
  26791. delete _this._buffer;
  26792. }
  26793. }
  26794. else {
  26795. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  26796. _this._delayedOnLoad = load;
  26797. _this._delayedOnError = onError;
  26798. }
  26799. }
  26800. else {
  26801. if (_this._texture.isReady) {
  26802. BABYLON.Tools.SetImmediate(function () { return load(); });
  26803. }
  26804. else {
  26805. _this._texture.onLoadedObservable.add(load);
  26806. }
  26807. }
  26808. return _this;
  26809. }
  26810. Object.defineProperty(Texture.prototype, "noMipmap", {
  26811. get: function () {
  26812. return this._noMipmap;
  26813. },
  26814. enumerable: true,
  26815. configurable: true
  26816. });
  26817. Object.defineProperty(Texture.prototype, "isBlocking", {
  26818. get: function () {
  26819. return this._isBlocking;
  26820. },
  26821. set: function (value) {
  26822. this._isBlocking = value;
  26823. },
  26824. enumerable: true,
  26825. configurable: true
  26826. });
  26827. Object.defineProperty(Texture.prototype, "samplingMode", {
  26828. get: function () {
  26829. return this._samplingMode;
  26830. },
  26831. enumerable: true,
  26832. configurable: true
  26833. });
  26834. Texture.prototype.updateURL = function (url) {
  26835. this.url = url;
  26836. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  26837. this.delayLoad();
  26838. };
  26839. Texture.prototype.delayLoad = function () {
  26840. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  26841. return;
  26842. }
  26843. var scene = this.getScene();
  26844. if (!scene) {
  26845. return;
  26846. }
  26847. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  26848. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  26849. if (!this._texture) {
  26850. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  26851. if (this._deleteBuffer) {
  26852. delete this._buffer;
  26853. }
  26854. }
  26855. else {
  26856. if (this._delayedOnLoad) {
  26857. if (this._texture.isReady) {
  26858. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  26859. }
  26860. else {
  26861. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  26862. }
  26863. }
  26864. }
  26865. this._delayedOnLoad = null;
  26866. this._delayedOnError = null;
  26867. };
  26868. Texture.prototype.updateSamplingMode = function (samplingMode) {
  26869. if (!this._texture) {
  26870. return;
  26871. }
  26872. var scene = this.getScene();
  26873. if (!scene) {
  26874. return;
  26875. }
  26876. this._samplingMode = samplingMode;
  26877. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  26878. };
  26879. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  26880. x *= this.uScale;
  26881. y *= this.vScale;
  26882. x -= 0.5 * this.uScale;
  26883. y -= 0.5 * this.vScale;
  26884. z -= 0.5;
  26885. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  26886. t.x += 0.5 * this.uScale + this.uOffset;
  26887. t.y += 0.5 * this.vScale + this.vOffset;
  26888. t.z += 0.5;
  26889. };
  26890. Texture.prototype.getTextureMatrix = function () {
  26891. var _this = this;
  26892. if (this.uOffset === this._cachedUOffset &&
  26893. this.vOffset === this._cachedVOffset &&
  26894. this.uScale === this._cachedUScale &&
  26895. this.vScale === this._cachedVScale &&
  26896. this.uAng === this._cachedUAng &&
  26897. this.vAng === this._cachedVAng &&
  26898. this.wAng === this._cachedWAng) {
  26899. return this._cachedTextureMatrix;
  26900. }
  26901. this._cachedUOffset = this.uOffset;
  26902. this._cachedVOffset = this.vOffset;
  26903. this._cachedUScale = this.uScale;
  26904. this._cachedVScale = this.vScale;
  26905. this._cachedUAng = this.uAng;
  26906. this._cachedVAng = this.vAng;
  26907. this._cachedWAng = this.wAng;
  26908. if (!this._cachedTextureMatrix) {
  26909. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  26910. this._rowGenerationMatrix = new BABYLON.Matrix();
  26911. this._t0 = BABYLON.Vector3.Zero();
  26912. this._t1 = BABYLON.Vector3.Zero();
  26913. this._t2 = BABYLON.Vector3.Zero();
  26914. }
  26915. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  26916. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  26917. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  26918. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  26919. this._t1.subtractInPlace(this._t0);
  26920. this._t2.subtractInPlace(this._t0);
  26921. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  26922. this._cachedTextureMatrix.m[0] = this._t1.x;
  26923. this._cachedTextureMatrix.m[1] = this._t1.y;
  26924. this._cachedTextureMatrix.m[2] = this._t1.z;
  26925. this._cachedTextureMatrix.m[4] = this._t2.x;
  26926. this._cachedTextureMatrix.m[5] = this._t2.y;
  26927. this._cachedTextureMatrix.m[6] = this._t2.z;
  26928. this._cachedTextureMatrix.m[8] = this._t0.x;
  26929. this._cachedTextureMatrix.m[9] = this._t0.y;
  26930. this._cachedTextureMatrix.m[10] = this._t0.z;
  26931. var scene = this.getScene();
  26932. if (!scene) {
  26933. return this._cachedTextureMatrix;
  26934. }
  26935. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  26936. return mat.hasTexture(_this);
  26937. });
  26938. return this._cachedTextureMatrix;
  26939. };
  26940. Texture.prototype.getReflectionTextureMatrix = function () {
  26941. var _this = this;
  26942. var scene = this.getScene();
  26943. if (!scene) {
  26944. return this._cachedTextureMatrix;
  26945. }
  26946. if (this.uOffset === this._cachedUOffset &&
  26947. this.vOffset === this._cachedVOffset &&
  26948. this.uScale === this._cachedUScale &&
  26949. this.vScale === this._cachedVScale &&
  26950. this.coordinatesMode === this._cachedCoordinatesMode) {
  26951. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  26952. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  26953. return this._cachedTextureMatrix;
  26954. }
  26955. }
  26956. else {
  26957. return this._cachedTextureMatrix;
  26958. }
  26959. }
  26960. if (!this._cachedTextureMatrix) {
  26961. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  26962. }
  26963. if (!this._projectionModeMatrix) {
  26964. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  26965. }
  26966. this._cachedUOffset = this.uOffset;
  26967. this._cachedVOffset = this.vOffset;
  26968. this._cachedUScale = this.uScale;
  26969. this._cachedVScale = this.vScale;
  26970. this._cachedCoordinatesMode = this.coordinatesMode;
  26971. switch (this.coordinatesMode) {
  26972. case Texture.PLANAR_MODE:
  26973. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  26974. this._cachedTextureMatrix[0] = this.uScale;
  26975. this._cachedTextureMatrix[5] = this.vScale;
  26976. this._cachedTextureMatrix[12] = this.uOffset;
  26977. this._cachedTextureMatrix[13] = this.vOffset;
  26978. break;
  26979. case Texture.PROJECTION_MODE:
  26980. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  26981. this._projectionModeMatrix.m[0] = 0.5;
  26982. this._projectionModeMatrix.m[5] = -0.5;
  26983. this._projectionModeMatrix.m[10] = 0.0;
  26984. this._projectionModeMatrix.m[12] = 0.5;
  26985. this._projectionModeMatrix.m[13] = 0.5;
  26986. this._projectionModeMatrix.m[14] = 1.0;
  26987. this._projectionModeMatrix.m[15] = 1.0;
  26988. var projectionMatrix = scene.getProjectionMatrix();
  26989. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  26990. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  26991. break;
  26992. default:
  26993. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  26994. break;
  26995. }
  26996. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  26997. return (mat.getActiveTextures().indexOf(_this) !== -1);
  26998. });
  26999. return this._cachedTextureMatrix;
  27000. };
  27001. Texture.prototype.clone = function () {
  27002. var _this = this;
  27003. return BABYLON.SerializationHelper.Clone(function () {
  27004. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  27005. }, this);
  27006. };
  27007. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  27008. get: function () {
  27009. if (!this._onLoadObservable) {
  27010. this._onLoadObservable = new BABYLON.Observable();
  27011. }
  27012. return this._onLoadObservable;
  27013. },
  27014. enumerable: true,
  27015. configurable: true
  27016. });
  27017. Texture.prototype.serialize = function () {
  27018. var serializationObject = _super.prototype.serialize.call(this);
  27019. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  27020. serializationObject.base64String = this._buffer;
  27021. serializationObject.name = serializationObject.name.replace("data:", "");
  27022. }
  27023. return serializationObject;
  27024. };
  27025. Texture.prototype.getClassName = function () {
  27026. return "Texture";
  27027. };
  27028. Texture.prototype.dispose = function () {
  27029. _super.prototype.dispose.call(this);
  27030. if (this.onLoadObservable) {
  27031. this.onLoadObservable.clear();
  27032. this._onLoadObservable = null;
  27033. }
  27034. this._delayedOnLoad = null;
  27035. this._delayedOnError = null;
  27036. };
  27037. // Statics
  27038. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  27039. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  27040. if (onLoad === void 0) { onLoad = null; }
  27041. if (onError === void 0) { onError = null; }
  27042. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  27043. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  27044. };
  27045. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  27046. if (parsedTexture.customType) {
  27047. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  27048. // Update Sampling Mode
  27049. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  27050. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  27051. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  27052. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  27053. }
  27054. }
  27055. return parsedCustomTexture;
  27056. }
  27057. if (parsedTexture.isCube) {
  27058. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  27059. }
  27060. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  27061. return null;
  27062. }
  27063. var texture = BABYLON.SerializationHelper.Parse(function () {
  27064. var generateMipMaps = true;
  27065. if (parsedTexture.noMipmap) {
  27066. generateMipMaps = false;
  27067. }
  27068. if (parsedTexture.mirrorPlane) {
  27069. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  27070. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  27071. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  27072. return mirrorTexture;
  27073. }
  27074. else if (parsedTexture.isRenderTarget) {
  27075. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  27076. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  27077. return renderTargetTexture;
  27078. }
  27079. else {
  27080. var texture;
  27081. if (parsedTexture.base64String) {
  27082. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  27083. }
  27084. else {
  27085. var url = rootUrl + parsedTexture.name;
  27086. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  27087. url = parsedTexture.url;
  27088. }
  27089. texture = new Texture(url, scene, !generateMipMaps);
  27090. }
  27091. return texture;
  27092. }
  27093. }, parsedTexture, scene);
  27094. // Update Sampling Mode
  27095. if (parsedTexture.samplingMode) {
  27096. var sampling = parsedTexture.samplingMode;
  27097. if (texture._samplingMode !== sampling) {
  27098. texture.updateSamplingMode(sampling);
  27099. }
  27100. }
  27101. // Animations
  27102. if (parsedTexture.animations) {
  27103. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  27104. var parsedAnimation = parsedTexture.animations[animationIndex];
  27105. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  27106. }
  27107. }
  27108. return texture;
  27109. };
  27110. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  27111. if (deleteBuffer === void 0) { deleteBuffer = false; }
  27112. if (noMipmap === void 0) { noMipmap = false; }
  27113. if (invertY === void 0) { invertY = true; }
  27114. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  27115. if (onLoad === void 0) { onLoad = null; }
  27116. if (onError === void 0) { onError = null; }
  27117. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  27118. if (name.substr(0, 5) !== "data:") {
  27119. name = "data:" + name;
  27120. }
  27121. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  27122. };
  27123. // Constants
  27124. Texture.NEAREST_SAMPLINGMODE = 1;
  27125. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  27126. Texture.BILINEAR_SAMPLINGMODE = 2;
  27127. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  27128. Texture.TRILINEAR_SAMPLINGMODE = 3;
  27129. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  27130. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  27131. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  27132. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  27133. Texture.NEAREST_LINEAR = 7;
  27134. Texture.NEAREST_NEAREST = 8;
  27135. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  27136. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  27137. Texture.LINEAR_LINEAR = 11;
  27138. Texture.LINEAR_NEAREST = 12;
  27139. Texture.EXPLICIT_MODE = 0;
  27140. Texture.SPHERICAL_MODE = 1;
  27141. Texture.PLANAR_MODE = 2;
  27142. Texture.CUBIC_MODE = 3;
  27143. Texture.PROJECTION_MODE = 4;
  27144. Texture.SKYBOX_MODE = 5;
  27145. Texture.INVCUBIC_MODE = 6;
  27146. Texture.EQUIRECTANGULAR_MODE = 7;
  27147. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  27148. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  27149. Texture.CLAMP_ADDRESSMODE = 0;
  27150. Texture.WRAP_ADDRESSMODE = 1;
  27151. Texture.MIRROR_ADDRESSMODE = 2;
  27152. /**
  27153. * Gets or sets a boolean which defines if the texture url must be build from the serialized URL instead of just using the name and loading them side by side with the scene file
  27154. */
  27155. Texture.UseSerializedUrlIfAny = false;
  27156. __decorate([
  27157. BABYLON.serialize()
  27158. ], Texture.prototype, "url", void 0);
  27159. __decorate([
  27160. BABYLON.serialize()
  27161. ], Texture.prototype, "uOffset", void 0);
  27162. __decorate([
  27163. BABYLON.serialize()
  27164. ], Texture.prototype, "vOffset", void 0);
  27165. __decorate([
  27166. BABYLON.serialize()
  27167. ], Texture.prototype, "uScale", void 0);
  27168. __decorate([
  27169. BABYLON.serialize()
  27170. ], Texture.prototype, "vScale", void 0);
  27171. __decorate([
  27172. BABYLON.serialize()
  27173. ], Texture.prototype, "uAng", void 0);
  27174. __decorate([
  27175. BABYLON.serialize()
  27176. ], Texture.prototype, "vAng", void 0);
  27177. __decorate([
  27178. BABYLON.serialize()
  27179. ], Texture.prototype, "wAng", void 0);
  27180. __decorate([
  27181. BABYLON.serialize()
  27182. ], Texture.prototype, "isBlocking", null);
  27183. return Texture;
  27184. }(BABYLON.BaseTexture));
  27185. BABYLON.Texture = Texture;
  27186. })(BABYLON || (BABYLON = {}));
  27187. //# sourceMappingURL=babylon.texture.js.map
  27188. var BABYLON;
  27189. (function (BABYLON) {
  27190. var _InstancesBatch = /** @class */ (function () {
  27191. function _InstancesBatch() {
  27192. this.mustReturn = false;
  27193. this.visibleInstances = new Array();
  27194. this.renderSelf = new Array();
  27195. }
  27196. return _InstancesBatch;
  27197. }());
  27198. BABYLON._InstancesBatch = _InstancesBatch;
  27199. var Mesh = /** @class */ (function (_super) {
  27200. __extends(Mesh, _super);
  27201. /**
  27202. * @constructor
  27203. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  27204. * @param {Scene} scene The scene to add this mesh to.
  27205. * @param {Node} parent The parent of this mesh, if it has one
  27206. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  27207. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  27208. * When false, achieved by calling a clone(), also passing False.
  27209. * This will make creation of children, recursive.
  27210. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  27211. */
  27212. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  27213. if (scene === void 0) { scene = null; }
  27214. if (parent === void 0) { parent = null; }
  27215. if (source === void 0) { source = null; }
  27216. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  27217. var _this = _super.call(this, name, scene) || this;
  27218. // Events
  27219. /**
  27220. * An event triggered before rendering the mesh
  27221. * @type {BABYLON.Observable}
  27222. */
  27223. _this.onBeforeRenderObservable = new BABYLON.Observable();
  27224. /**
  27225. * An event triggered after rendering the mesh
  27226. * @type {BABYLON.Observable}
  27227. */
  27228. _this.onAfterRenderObservable = new BABYLON.Observable();
  27229. /**
  27230. * An event triggered before drawing the mesh
  27231. * @type {BABYLON.Observable}
  27232. */
  27233. _this.onBeforeDrawObservable = new BABYLON.Observable();
  27234. // Members
  27235. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  27236. _this.instances = new Array();
  27237. _this._LODLevels = new Array();
  27238. _this._visibleInstances = {};
  27239. _this._renderIdForInstances = new Array();
  27240. _this._batchCache = new _InstancesBatch();
  27241. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  27242. // Use by builder only to know what orientation were the mesh build in.
  27243. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  27244. _this.overrideMaterialSideOrientation = null;
  27245. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  27246. // Will be used to save a source mesh reference, If any
  27247. _this._source = null;
  27248. scene = _this.getScene();
  27249. if (source) {
  27250. // Source mesh
  27251. _this._source = source;
  27252. // Geometry
  27253. if (source._geometry) {
  27254. source._geometry.applyToMesh(_this);
  27255. }
  27256. // Deep copy
  27257. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId", "source", "metadata"], ["_poseMatrix", "_source"]);
  27258. // Metadata
  27259. if (source.metadata && source.metadata.clone) {
  27260. _this.metadata = source.metadata.clone();
  27261. }
  27262. else {
  27263. _this.metadata = source.metadata;
  27264. }
  27265. // Tags
  27266. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  27267. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  27268. }
  27269. // Parent
  27270. _this.parent = source.parent;
  27271. // Pivot
  27272. _this.setPivotMatrix(source.getPivotMatrix());
  27273. _this.id = name + "." + source.id;
  27274. // Material
  27275. _this.material = source.material;
  27276. var index;
  27277. if (!doNotCloneChildren) {
  27278. // Children
  27279. var directDescendants = source.getDescendants(true);
  27280. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  27281. var child = directDescendants[index_1];
  27282. if (child.clone) {
  27283. child.clone(name + "." + child.name, _this);
  27284. }
  27285. }
  27286. }
  27287. // Physics clone
  27288. var physicsEngine = _this.getScene().getPhysicsEngine();
  27289. if (clonePhysicsImpostor && physicsEngine) {
  27290. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  27291. if (impostor) {
  27292. _this.physicsImpostor = impostor.clone(_this);
  27293. }
  27294. }
  27295. // Particles
  27296. for (index = 0; index < scene.particleSystems.length; index++) {
  27297. var system = scene.particleSystems[index];
  27298. if (system.emitter === source) {
  27299. system.clone(system.name, _this);
  27300. }
  27301. }
  27302. _this.computeWorldMatrix(true);
  27303. }
  27304. // Parent
  27305. if (parent !== null) {
  27306. _this.parent = parent;
  27307. }
  27308. return _this;
  27309. }
  27310. Object.defineProperty(Mesh, "FRONTSIDE", {
  27311. /**
  27312. * Mesh side orientation : usually the external or front surface
  27313. */
  27314. get: function () {
  27315. return Mesh._FRONTSIDE;
  27316. },
  27317. enumerable: true,
  27318. configurable: true
  27319. });
  27320. Object.defineProperty(Mesh, "BACKSIDE", {
  27321. /**
  27322. * Mesh side orientation : usually the internal or back surface
  27323. */
  27324. get: function () {
  27325. return Mesh._BACKSIDE;
  27326. },
  27327. enumerable: true,
  27328. configurable: true
  27329. });
  27330. Object.defineProperty(Mesh, "DOUBLESIDE", {
  27331. /**
  27332. * Mesh side orientation : both internal and external or front and back surfaces
  27333. */
  27334. get: function () {
  27335. return Mesh._DOUBLESIDE;
  27336. },
  27337. enumerable: true,
  27338. configurable: true
  27339. });
  27340. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  27341. /**
  27342. * Mesh side orientation : by default, `FRONTSIDE`
  27343. */
  27344. get: function () {
  27345. return Mesh._DEFAULTSIDE;
  27346. },
  27347. enumerable: true,
  27348. configurable: true
  27349. });
  27350. Object.defineProperty(Mesh, "NO_CAP", {
  27351. /**
  27352. * Mesh cap setting : no cap
  27353. */
  27354. get: function () {
  27355. return Mesh._NO_CAP;
  27356. },
  27357. enumerable: true,
  27358. configurable: true
  27359. });
  27360. Object.defineProperty(Mesh, "CAP_START", {
  27361. /**
  27362. * Mesh cap setting : one cap at the beginning of the mesh
  27363. */
  27364. get: function () {
  27365. return Mesh._CAP_START;
  27366. },
  27367. enumerable: true,
  27368. configurable: true
  27369. });
  27370. Object.defineProperty(Mesh, "CAP_END", {
  27371. /**
  27372. * Mesh cap setting : one cap at the end of the mesh
  27373. */
  27374. get: function () {
  27375. return Mesh._CAP_END;
  27376. },
  27377. enumerable: true,
  27378. configurable: true
  27379. });
  27380. Object.defineProperty(Mesh, "CAP_ALL", {
  27381. /**
  27382. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  27383. */
  27384. get: function () {
  27385. return Mesh._CAP_ALL;
  27386. },
  27387. enumerable: true,
  27388. configurable: true
  27389. });
  27390. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  27391. set: function (callback) {
  27392. if (this._onBeforeDrawObserver) {
  27393. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  27394. }
  27395. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  27396. },
  27397. enumerable: true,
  27398. configurable: true
  27399. });
  27400. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  27401. get: function () {
  27402. return this._morphTargetManager;
  27403. },
  27404. set: function (value) {
  27405. if (this._morphTargetManager === value) {
  27406. return;
  27407. }
  27408. this._morphTargetManager = value;
  27409. this._syncGeometryWithMorphTargetManager();
  27410. },
  27411. enumerable: true,
  27412. configurable: true
  27413. });
  27414. Object.defineProperty(Mesh.prototype, "source", {
  27415. get: function () {
  27416. return this._source;
  27417. },
  27418. enumerable: true,
  27419. configurable: true
  27420. });
  27421. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  27422. get: function () {
  27423. return this._unIndexed;
  27424. },
  27425. set: function (value) {
  27426. if (this._unIndexed !== value) {
  27427. this._unIndexed = value;
  27428. this._markSubMeshesAsAttributesDirty();
  27429. }
  27430. },
  27431. enumerable: true,
  27432. configurable: true
  27433. });
  27434. // Methods
  27435. /**
  27436. * Returns the string "Mesh".
  27437. */
  27438. Mesh.prototype.getClassName = function () {
  27439. return "Mesh";
  27440. };
  27441. /**
  27442. * Returns a string.
  27443. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  27444. */
  27445. Mesh.prototype.toString = function (fullDetails) {
  27446. var ret = _super.prototype.toString.call(this, fullDetails);
  27447. ret += ", n vertices: " + this.getTotalVertices();
  27448. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  27449. if (this.animations) {
  27450. for (var i = 0; i < this.animations.length; i++) {
  27451. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  27452. }
  27453. }
  27454. if (fullDetails) {
  27455. if (this._geometry) {
  27456. var ib = this.getIndices();
  27457. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27458. if (vb && ib) {
  27459. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  27460. }
  27461. }
  27462. else {
  27463. ret += ", flat shading: UNKNOWN";
  27464. }
  27465. }
  27466. return ret;
  27467. };
  27468. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  27469. /**
  27470. * True if the mesh has some Levels Of Details (LOD).
  27471. * Returns a boolean.
  27472. */
  27473. get: function () {
  27474. return this._LODLevels.length > 0;
  27475. },
  27476. enumerable: true,
  27477. configurable: true
  27478. });
  27479. /**
  27480. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  27481. * @returns an array of {BABYLON.MeshLODLevel}
  27482. */
  27483. Mesh.prototype.getLODLevels = function () {
  27484. return this._LODLevels;
  27485. };
  27486. Mesh.prototype._sortLODLevels = function () {
  27487. this._LODLevels.sort(function (a, b) {
  27488. if (a.distance < b.distance) {
  27489. return 1;
  27490. }
  27491. if (a.distance > b.distance) {
  27492. return -1;
  27493. }
  27494. return 0;
  27495. });
  27496. };
  27497. /**
  27498. * Add a mesh as LOD level triggered at the given distance.
  27499. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  27500. * @param {number} distance The distance from the center of the object to show this level
  27501. * @param {Mesh} mesh The mesh to be added as LOD level
  27502. * @return {Mesh} This mesh (for chaining)
  27503. */
  27504. Mesh.prototype.addLODLevel = function (distance, mesh) {
  27505. if (mesh && mesh._masterMesh) {
  27506. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  27507. return this;
  27508. }
  27509. var level = new BABYLON.MeshLODLevel(distance, mesh);
  27510. this._LODLevels.push(level);
  27511. if (mesh) {
  27512. mesh._masterMesh = this;
  27513. }
  27514. this._sortLODLevels();
  27515. return this;
  27516. };
  27517. /**
  27518. * Returns the LOD level mesh at the passed distance or null if not found.
  27519. * It is related to the method `addLODLevel(distance, mesh)`.
  27520. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  27521. * Returns an object Mesh or `null`.
  27522. */
  27523. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  27524. for (var index = 0; index < this._LODLevels.length; index++) {
  27525. var level = this._LODLevels[index];
  27526. if (level.distance === distance) {
  27527. return level.mesh;
  27528. }
  27529. }
  27530. return null;
  27531. };
  27532. /**
  27533. * Remove a mesh from the LOD array
  27534. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  27535. * @param {Mesh} mesh The mesh to be removed.
  27536. * @return {Mesh} This mesh (for chaining)
  27537. */
  27538. Mesh.prototype.removeLODLevel = function (mesh) {
  27539. for (var index = 0; index < this._LODLevels.length; index++) {
  27540. if (this._LODLevels[index].mesh === mesh) {
  27541. this._LODLevels.splice(index, 1);
  27542. if (mesh) {
  27543. mesh._masterMesh = null;
  27544. }
  27545. }
  27546. }
  27547. this._sortLODLevels();
  27548. return this;
  27549. };
  27550. /**
  27551. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  27552. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  27553. */
  27554. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  27555. if (!this._LODLevels || this._LODLevels.length === 0) {
  27556. return this;
  27557. }
  27558. var bSphere;
  27559. if (boundingSphere) {
  27560. bSphere = boundingSphere;
  27561. }
  27562. else {
  27563. var boundingInfo = this.getBoundingInfo();
  27564. bSphere = boundingInfo.boundingSphere;
  27565. }
  27566. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  27567. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  27568. if (this.onLODLevelSelection) {
  27569. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  27570. }
  27571. return this;
  27572. }
  27573. for (var index = 0; index < this._LODLevels.length; index++) {
  27574. var level = this._LODLevels[index];
  27575. if (level.distance < distanceToCamera) {
  27576. if (level.mesh) {
  27577. level.mesh._preActivate();
  27578. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  27579. }
  27580. if (this.onLODLevelSelection) {
  27581. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  27582. }
  27583. return level.mesh;
  27584. }
  27585. }
  27586. if (this.onLODLevelSelection) {
  27587. this.onLODLevelSelection(distanceToCamera, this, this);
  27588. }
  27589. return this;
  27590. };
  27591. Object.defineProperty(Mesh.prototype, "geometry", {
  27592. /**
  27593. * Returns the mesh internal Geometry object.
  27594. */
  27595. get: function () {
  27596. return this._geometry;
  27597. },
  27598. enumerable: true,
  27599. configurable: true
  27600. });
  27601. /**
  27602. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  27603. */
  27604. Mesh.prototype.getTotalVertices = function () {
  27605. if (this._geometry === null || this._geometry === undefined) {
  27606. return 0;
  27607. }
  27608. return this._geometry.getTotalVertices();
  27609. };
  27610. /**
  27611. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  27612. * 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.
  27613. * You can force the copy with forceCopy === true
  27614. * Returns null if the mesh has no geometry or no vertex buffer.
  27615. * Possible `kind` values :
  27616. * - BABYLON.VertexBuffer.PositionKind
  27617. * - BABYLON.VertexBuffer.UVKind
  27618. * - BABYLON.VertexBuffer.UV2Kind
  27619. * - BABYLON.VertexBuffer.UV3Kind
  27620. * - BABYLON.VertexBuffer.UV4Kind
  27621. * - BABYLON.VertexBuffer.UV5Kind
  27622. * - BABYLON.VertexBuffer.UV6Kind
  27623. * - BABYLON.VertexBuffer.ColorKind
  27624. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27625. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27626. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27627. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27628. */
  27629. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  27630. if (!this._geometry) {
  27631. return null;
  27632. }
  27633. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  27634. };
  27635. /**
  27636. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  27637. * Returns `null` if the mesh has no geometry.
  27638. * Possible `kind` values :
  27639. * - BABYLON.VertexBuffer.PositionKind
  27640. * - BABYLON.VertexBuffer.UVKind
  27641. * - BABYLON.VertexBuffer.UV2Kind
  27642. * - BABYLON.VertexBuffer.UV3Kind
  27643. * - BABYLON.VertexBuffer.UV4Kind
  27644. * - BABYLON.VertexBuffer.UV5Kind
  27645. * - BABYLON.VertexBuffer.UV6Kind
  27646. * - BABYLON.VertexBuffer.ColorKind
  27647. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27648. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27649. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27650. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27651. */
  27652. Mesh.prototype.getVertexBuffer = function (kind) {
  27653. if (!this._geometry) {
  27654. return null;
  27655. }
  27656. return this._geometry.getVertexBuffer(kind);
  27657. };
  27658. /**
  27659. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  27660. * Possible `kind` values :
  27661. * - BABYLON.VertexBuffer.PositionKind
  27662. * - BABYLON.VertexBuffer.UVKind
  27663. * - BABYLON.VertexBuffer.UV2Kind
  27664. * - BABYLON.VertexBuffer.UV3Kind
  27665. * - BABYLON.VertexBuffer.UV4Kind
  27666. * - BABYLON.VertexBuffer.UV5Kind
  27667. * - BABYLON.VertexBuffer.UV6Kind
  27668. * - BABYLON.VertexBuffer.ColorKind
  27669. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27670. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27671. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27672. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27673. */
  27674. Mesh.prototype.isVerticesDataPresent = function (kind) {
  27675. if (!this._geometry) {
  27676. if (this._delayInfo) {
  27677. return this._delayInfo.indexOf(kind) !== -1;
  27678. }
  27679. return false;
  27680. }
  27681. return this._geometry.isVerticesDataPresent(kind);
  27682. };
  27683. /**
  27684. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  27685. * Possible `kind` values :
  27686. * - BABYLON.VertexBuffer.PositionKind
  27687. * - BABYLON.VertexBuffer.UVKind
  27688. * - BABYLON.VertexBuffer.UV2Kind
  27689. * - BABYLON.VertexBuffer.UV3Kind
  27690. * - BABYLON.VertexBuffer.UV4Kind
  27691. * - BABYLON.VertexBuffer.UV5Kind
  27692. * - BABYLON.VertexBuffer.UV6Kind
  27693. * - BABYLON.VertexBuffer.ColorKind
  27694. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27695. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27696. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27697. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27698. */
  27699. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  27700. if (!this._geometry) {
  27701. if (this._delayInfo) {
  27702. return this._delayInfo.indexOf(kind) !== -1;
  27703. }
  27704. return false;
  27705. }
  27706. return this._geometry.isVertexBufferUpdatable(kind);
  27707. };
  27708. /**
  27709. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  27710. * Possible `kind` values :
  27711. * - BABYLON.VertexBuffer.PositionKind
  27712. * - BABYLON.VertexBuffer.UVKind
  27713. * - BABYLON.VertexBuffer.UV2Kind
  27714. * - BABYLON.VertexBuffer.UV3Kind
  27715. * - BABYLON.VertexBuffer.UV4Kind
  27716. * - BABYLON.VertexBuffer.UV5Kind
  27717. * - BABYLON.VertexBuffer.UV6Kind
  27718. * - BABYLON.VertexBuffer.ColorKind
  27719. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27720. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27721. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27722. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27723. */
  27724. Mesh.prototype.getVerticesDataKinds = function () {
  27725. if (!this._geometry) {
  27726. var result = new Array();
  27727. if (this._delayInfo) {
  27728. this._delayInfo.forEach(function (kind, index, array) {
  27729. result.push(kind);
  27730. });
  27731. }
  27732. return result;
  27733. }
  27734. return this._geometry.getVerticesDataKinds();
  27735. };
  27736. /**
  27737. * Returns a positive integer : the total number of indices in this mesh geometry.
  27738. * Returns zero if the mesh has no geometry.
  27739. */
  27740. Mesh.prototype.getTotalIndices = function () {
  27741. if (!this._geometry) {
  27742. return 0;
  27743. }
  27744. return this._geometry.getTotalIndices();
  27745. };
  27746. /**
  27747. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  27748. * 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.
  27749. * Returns an empty array if the mesh has no geometry.
  27750. */
  27751. Mesh.prototype.getIndices = function (copyWhenShared) {
  27752. if (!this._geometry) {
  27753. return [];
  27754. }
  27755. return this._geometry.getIndices(copyWhenShared);
  27756. };
  27757. Object.defineProperty(Mesh.prototype, "isBlocked", {
  27758. get: function () {
  27759. return this._masterMesh !== null && this._masterMesh !== undefined;
  27760. },
  27761. enumerable: true,
  27762. configurable: true
  27763. });
  27764. /**
  27765. * Determine if the current mesh is ready to be rendered
  27766. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  27767. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  27768. * @returns true if all associated assets are ready (material, textures, shaders)
  27769. */
  27770. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  27771. if (completeCheck === void 0) { completeCheck = false; }
  27772. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  27773. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  27774. return false;
  27775. }
  27776. if (!_super.prototype.isReady.call(this, completeCheck)) {
  27777. return false;
  27778. }
  27779. if (!this.subMeshes || this.subMeshes.length === 0) {
  27780. return true;
  27781. }
  27782. if (!completeCheck) {
  27783. return true;
  27784. }
  27785. var engine = this.getEngine();
  27786. var scene = this.getScene();
  27787. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  27788. this.computeWorldMatrix();
  27789. var mat = this.material || scene.defaultMaterial;
  27790. if (mat) {
  27791. if (mat.storeEffectOnSubMeshes) {
  27792. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  27793. var subMesh = _a[_i];
  27794. var effectiveMaterial = subMesh.getMaterial();
  27795. if (effectiveMaterial) {
  27796. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  27797. return false;
  27798. }
  27799. }
  27800. }
  27801. }
  27802. else {
  27803. if (!mat.isReady(this, hardwareInstancedRendering)) {
  27804. return false;
  27805. }
  27806. }
  27807. }
  27808. // Shadows
  27809. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  27810. var light = _c[_b];
  27811. var generator = light.getShadowGenerator();
  27812. if (generator) {
  27813. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  27814. var subMesh = _e[_d];
  27815. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  27816. return false;
  27817. }
  27818. }
  27819. }
  27820. }
  27821. // LOD
  27822. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  27823. var lod = _g[_f];
  27824. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  27825. return false;
  27826. }
  27827. }
  27828. return true;
  27829. };
  27830. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  27831. /**
  27832. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  27833. * This property is pertinent only for updatable parametric shapes.
  27834. */
  27835. get: function () {
  27836. return this._areNormalsFrozen;
  27837. },
  27838. enumerable: true,
  27839. configurable: true
  27840. });
  27841. /**
  27842. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  27843. * It has no effect at all on other shapes.
  27844. * It prevents the mesh normals from being recomputed on next `positions` array update.
  27845. * Returns the Mesh.
  27846. */
  27847. Mesh.prototype.freezeNormals = function () {
  27848. this._areNormalsFrozen = true;
  27849. return this;
  27850. };
  27851. /**
  27852. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  27853. * It has no effect at all on other shapes.
  27854. * It reactivates the mesh normals computation if it was previously frozen.
  27855. * Returns the Mesh.
  27856. */
  27857. Mesh.prototype.unfreezeNormals = function () {
  27858. this._areNormalsFrozen = false;
  27859. return this;
  27860. };
  27861. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  27862. /**
  27863. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  27864. */
  27865. set: function (count) {
  27866. this._overridenInstanceCount = count;
  27867. },
  27868. enumerable: true,
  27869. configurable: true
  27870. });
  27871. // Methods
  27872. Mesh.prototype._preActivate = function () {
  27873. var sceneRenderId = this.getScene().getRenderId();
  27874. if (this._preActivateId === sceneRenderId) {
  27875. return this;
  27876. }
  27877. this._preActivateId = sceneRenderId;
  27878. this._visibleInstances = null;
  27879. return this;
  27880. };
  27881. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  27882. if (this._visibleInstances) {
  27883. this._visibleInstances.intermediateDefaultRenderId = renderId;
  27884. }
  27885. return this;
  27886. };
  27887. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  27888. if (!this._visibleInstances) {
  27889. this._visibleInstances = {};
  27890. this._visibleInstances.defaultRenderId = renderId;
  27891. this._visibleInstances.selfDefaultRenderId = this._renderId;
  27892. }
  27893. if (!this._visibleInstances[renderId]) {
  27894. this._visibleInstances[renderId] = new Array();
  27895. }
  27896. this._visibleInstances[renderId].push(instance);
  27897. return this;
  27898. };
  27899. /**
  27900. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  27901. * This means the mesh underlying bounding box and sphere are recomputed.
  27902. * Returns the Mesh.
  27903. */
  27904. Mesh.prototype.refreshBoundingInfo = function () {
  27905. return this._refreshBoundingInfo(false);
  27906. };
  27907. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  27908. if (this._boundingInfo && this._boundingInfo.isLocked) {
  27909. return this;
  27910. }
  27911. var data = this._getPositionData(applySkeleton);
  27912. if (data) {
  27913. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  27914. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  27915. }
  27916. if (this.subMeshes) {
  27917. for (var index = 0; index < this.subMeshes.length; index++) {
  27918. this.subMeshes[index].refreshBoundingInfo();
  27919. }
  27920. }
  27921. this._updateBoundingInfo();
  27922. return this;
  27923. };
  27924. Mesh.prototype._getPositionData = function (applySkeleton) {
  27925. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27926. if (data && applySkeleton && this.skeleton) {
  27927. data = BABYLON.Tools.Slice(data);
  27928. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  27929. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  27930. if (matricesWeightsData && matricesIndicesData) {
  27931. var needExtras = this.numBoneInfluencers > 4;
  27932. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  27933. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  27934. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  27935. var tempVector = BABYLON.Tmp.Vector3[0];
  27936. var finalMatrix = BABYLON.Tmp.Matrix[0];
  27937. var tempMatrix = BABYLON.Tmp.Matrix[1];
  27938. var matWeightIdx = 0;
  27939. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  27940. finalMatrix.reset();
  27941. var inf;
  27942. var weight;
  27943. for (inf = 0; inf < 4; inf++) {
  27944. weight = matricesWeightsData[matWeightIdx + inf];
  27945. if (weight <= 0)
  27946. break;
  27947. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  27948. finalMatrix.addToSelf(tempMatrix);
  27949. }
  27950. if (needExtras) {
  27951. for (inf = 0; inf < 4; inf++) {
  27952. weight = matricesWeightsExtraData[matWeightIdx + inf];
  27953. if (weight <= 0)
  27954. break;
  27955. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  27956. finalMatrix.addToSelf(tempMatrix);
  27957. }
  27958. }
  27959. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  27960. tempVector.toArray(data, index);
  27961. }
  27962. }
  27963. }
  27964. return data;
  27965. };
  27966. Mesh.prototype._createGlobalSubMesh = function (force) {
  27967. var totalVertices = this.getTotalVertices();
  27968. if (!totalVertices || !this.getIndices()) {
  27969. return null;
  27970. }
  27971. // Check if we need to recreate the submeshes
  27972. if (this.subMeshes && this.subMeshes.length > 0) {
  27973. var ib = this.getIndices();
  27974. if (!ib) {
  27975. return null;
  27976. }
  27977. var totalIndices = ib.length;
  27978. var needToRecreate = false;
  27979. if (force) {
  27980. needToRecreate = true;
  27981. }
  27982. else {
  27983. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  27984. var submesh = _a[_i];
  27985. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  27986. needToRecreate = true;
  27987. break;
  27988. }
  27989. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  27990. needToRecreate = true;
  27991. break;
  27992. }
  27993. }
  27994. }
  27995. if (!needToRecreate) {
  27996. return this.subMeshes[0];
  27997. }
  27998. }
  27999. this.releaseSubMeshes();
  28000. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  28001. };
  28002. Mesh.prototype.subdivide = function (count) {
  28003. if (count < 1) {
  28004. return;
  28005. }
  28006. var totalIndices = this.getTotalIndices();
  28007. var subdivisionSize = (totalIndices / count) | 0;
  28008. var offset = 0;
  28009. // Ensure that subdivisionSize is a multiple of 3
  28010. while (subdivisionSize % 3 !== 0) {
  28011. subdivisionSize++;
  28012. }
  28013. this.releaseSubMeshes();
  28014. for (var index = 0; index < count; index++) {
  28015. if (offset >= totalIndices) {
  28016. break;
  28017. }
  28018. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  28019. offset += subdivisionSize;
  28020. }
  28021. this.synchronizeInstances();
  28022. };
  28023. /**
  28024. * Sets the vertex data of the mesh geometry for the requested `kind`.
  28025. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  28026. * The `data` are either a numeric array either a Float32Array.
  28027. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  28028. * 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).
  28029. * Note that a new underlying VertexBuffer object is created each call.
  28030. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  28031. *
  28032. * Possible `kind` values :
  28033. * - BABYLON.VertexBuffer.PositionKind
  28034. * - BABYLON.VertexBuffer.UVKind
  28035. * - BABYLON.VertexBuffer.UV2Kind
  28036. * - BABYLON.VertexBuffer.UV3Kind
  28037. * - BABYLON.VertexBuffer.UV4Kind
  28038. * - BABYLON.VertexBuffer.UV5Kind
  28039. * - BABYLON.VertexBuffer.UV6Kind
  28040. * - BABYLON.VertexBuffer.ColorKind
  28041. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28042. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28043. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28044. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28045. *
  28046. * Returns the Mesh.
  28047. */
  28048. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  28049. if (updatable === void 0) { updatable = false; }
  28050. if (!this._geometry) {
  28051. var vertexData = new BABYLON.VertexData();
  28052. vertexData.set(data, kind);
  28053. var scene = this.getScene();
  28054. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  28055. }
  28056. else {
  28057. this._geometry.setVerticesData(kind, data, updatable, stride);
  28058. }
  28059. return this;
  28060. };
  28061. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  28062. if (updatable === void 0) { updatable = true; }
  28063. var vb = this.getVertexBuffer(kind);
  28064. if (!vb || vb.isUpdatable() === updatable) {
  28065. return;
  28066. }
  28067. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  28068. };
  28069. /**
  28070. * Sets the mesh VertexBuffer.
  28071. * Returns the Mesh.
  28072. */
  28073. Mesh.prototype.setVerticesBuffer = function (buffer) {
  28074. if (!this._geometry) {
  28075. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  28076. }
  28077. this._geometry.setVerticesBuffer(buffer);
  28078. return this;
  28079. };
  28080. /**
  28081. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  28082. * If the mesh has no geometry, it is simply returned as it is.
  28083. * The `data` are either a numeric array either a Float32Array.
  28084. * No new underlying VertexBuffer object is created.
  28085. * 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.
  28086. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  28087. *
  28088. * Possible `kind` values :
  28089. * - BABYLON.VertexBuffer.PositionKind
  28090. * - BABYLON.VertexBuffer.UVKind
  28091. * - BABYLON.VertexBuffer.UV2Kind
  28092. * - BABYLON.VertexBuffer.UV3Kind
  28093. * - BABYLON.VertexBuffer.UV4Kind
  28094. * - BABYLON.VertexBuffer.UV5Kind
  28095. * - BABYLON.VertexBuffer.UV6Kind
  28096. * - BABYLON.VertexBuffer.ColorKind
  28097. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28098. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28099. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28100. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28101. *
  28102. * Returns the Mesh.
  28103. */
  28104. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  28105. if (!this._geometry) {
  28106. return this;
  28107. }
  28108. if (!makeItUnique) {
  28109. this._geometry.updateVerticesData(kind, data, updateExtends);
  28110. }
  28111. else {
  28112. this.makeGeometryUnique();
  28113. this.updateVerticesData(kind, data, updateExtends, false);
  28114. }
  28115. return this;
  28116. };
  28117. /**
  28118. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  28119. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  28120. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  28121. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  28122. * Returns the Mesh.
  28123. */
  28124. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  28125. if (computeNormals === void 0) { computeNormals = true; }
  28126. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28127. if (!positions) {
  28128. return this;
  28129. }
  28130. positionFunction(positions);
  28131. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  28132. if (computeNormals) {
  28133. var indices = this.getIndices();
  28134. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28135. if (!normals) {
  28136. return this;
  28137. }
  28138. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  28139. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  28140. }
  28141. return this;
  28142. };
  28143. /**
  28144. * Creates a un-shared specific occurence of the geometry for the mesh.
  28145. * Returns the Mesh.
  28146. */
  28147. Mesh.prototype.makeGeometryUnique = function () {
  28148. if (!this._geometry) {
  28149. return this;
  28150. }
  28151. var oldGeometry = this._geometry;
  28152. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  28153. oldGeometry.releaseForMesh(this, true);
  28154. geometry.applyToMesh(this);
  28155. return this;
  28156. };
  28157. /**
  28158. * Sets the mesh indices.
  28159. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  28160. * Type is Uint16Array by default unless the mesh has more than 65536 vertices.
  28161. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  28162. * This method creates a new index buffer each call.
  28163. * Returns the Mesh.
  28164. */
  28165. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  28166. if (totalVertices === void 0) { totalVertices = null; }
  28167. if (updatable === void 0) { updatable = false; }
  28168. if (!this._geometry) {
  28169. var vertexData = new BABYLON.VertexData();
  28170. vertexData.indices = indices;
  28171. var scene = this.getScene();
  28172. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  28173. }
  28174. else {
  28175. this._geometry.setIndices(indices, totalVertices, updatable);
  28176. }
  28177. return this;
  28178. };
  28179. /**
  28180. * Update the current index buffer
  28181. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  28182. * Returns the Mesh.
  28183. */
  28184. Mesh.prototype.updateIndices = function (indices, offset) {
  28185. if (!this._geometry) {
  28186. return this;
  28187. }
  28188. this._geometry.updateIndices(indices, offset);
  28189. return this;
  28190. };
  28191. /**
  28192. * Invert the geometry to move from a right handed system to a left handed one.
  28193. * Returns the Mesh.
  28194. */
  28195. Mesh.prototype.toLeftHanded = function () {
  28196. if (!this._geometry) {
  28197. return this;
  28198. }
  28199. this._geometry.toLeftHanded();
  28200. return this;
  28201. };
  28202. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  28203. if (!this._geometry) {
  28204. return this;
  28205. }
  28206. var engine = this.getScene().getEngine();
  28207. // Wireframe
  28208. var indexToBind;
  28209. if (this._unIndexed) {
  28210. indexToBind = null;
  28211. }
  28212. else {
  28213. switch (fillMode) {
  28214. case BABYLON.Material.PointFillMode:
  28215. indexToBind = null;
  28216. break;
  28217. case BABYLON.Material.WireFrameFillMode:
  28218. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  28219. break;
  28220. default:
  28221. case BABYLON.Material.TriangleFillMode:
  28222. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  28223. break;
  28224. }
  28225. }
  28226. // VBOs
  28227. this._geometry._bind(effect, indexToBind);
  28228. return this;
  28229. };
  28230. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  28231. if (alternate === void 0) { alternate = false; }
  28232. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  28233. return this;
  28234. }
  28235. this.onBeforeDrawObservable.notifyObservers(this);
  28236. var scene = this.getScene();
  28237. var engine = scene.getEngine();
  28238. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  28239. // or triangles as points
  28240. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  28241. }
  28242. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  28243. // Triangles as wireframe
  28244. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  28245. }
  28246. else {
  28247. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  28248. }
  28249. if (scene._isAlternateRenderingEnabled && !alternate) {
  28250. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  28251. if (!effect || !scene.activeCamera) {
  28252. return this;
  28253. }
  28254. scene._switchToAlternateCameraConfiguration(true);
  28255. this._effectiveMaterial.bindView(effect);
  28256. this._effectiveMaterial.bindViewProjection(effect);
  28257. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  28258. this._draw(subMesh, fillMode, instancesCount, true);
  28259. engine.setViewport(scene.activeCamera.viewport);
  28260. scene._switchToAlternateCameraConfiguration(false);
  28261. this._effectiveMaterial.bindView(effect);
  28262. this._effectiveMaterial.bindViewProjection(effect);
  28263. }
  28264. return this;
  28265. };
  28266. /**
  28267. * Registers for this mesh a javascript function called just before the rendering process.
  28268. * This function is passed the current mesh.
  28269. * Return the Mesh.
  28270. */
  28271. Mesh.prototype.registerBeforeRender = function (func) {
  28272. this.onBeforeRenderObservable.add(func);
  28273. return this;
  28274. };
  28275. /**
  28276. * Disposes a previously registered javascript function called before the rendering.
  28277. * This function is passed the current mesh.
  28278. * Returns the Mesh.
  28279. */
  28280. Mesh.prototype.unregisterBeforeRender = function (func) {
  28281. this.onBeforeRenderObservable.removeCallback(func);
  28282. return this;
  28283. };
  28284. /**
  28285. * Registers for this mesh a javascript function called just after the rendering is complete.
  28286. * This function is passed the current mesh.
  28287. * Returns the Mesh.
  28288. */
  28289. Mesh.prototype.registerAfterRender = function (func) {
  28290. this.onAfterRenderObservable.add(func);
  28291. return this;
  28292. };
  28293. /**
  28294. * Disposes a previously registered javascript function called after the rendering.
  28295. * This function is passed the current mesh.
  28296. * Return the Mesh.
  28297. */
  28298. Mesh.prototype.unregisterAfterRender = function (func) {
  28299. this.onAfterRenderObservable.removeCallback(func);
  28300. return this;
  28301. };
  28302. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  28303. var scene = this.getScene();
  28304. this._batchCache.mustReturn = false;
  28305. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  28306. this._batchCache.visibleInstances[subMeshId] = null;
  28307. if (this._visibleInstances) {
  28308. var currentRenderId = scene.getRenderId();
  28309. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  28310. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  28311. var selfRenderId = this._renderId;
  28312. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  28313. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  28314. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  28315. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  28316. }
  28317. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  28318. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  28319. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  28320. this._batchCache.mustReturn = true;
  28321. return this._batchCache;
  28322. }
  28323. if (currentRenderId !== selfRenderId) {
  28324. this._batchCache.renderSelf[subMeshId] = false;
  28325. }
  28326. }
  28327. this._renderIdForInstances[subMeshId] = currentRenderId;
  28328. }
  28329. return this._batchCache;
  28330. };
  28331. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  28332. var visibleInstances = batch.visibleInstances[subMesh._id];
  28333. if (!visibleInstances) {
  28334. return this;
  28335. }
  28336. var matricesCount = visibleInstances.length + 1;
  28337. var bufferSize = matricesCount * 16 * 4;
  28338. var currentInstancesBufferSize = this._instancesBufferSize;
  28339. var instancesBuffer = this._instancesBuffer;
  28340. while (this._instancesBufferSize < bufferSize) {
  28341. this._instancesBufferSize *= 2;
  28342. }
  28343. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  28344. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  28345. }
  28346. var offset = 0;
  28347. var instancesCount = 0;
  28348. var world = this.getWorldMatrix();
  28349. if (batch.renderSelf[subMesh._id]) {
  28350. world.copyToArray(this._instancesData, offset);
  28351. offset += 16;
  28352. instancesCount++;
  28353. }
  28354. if (visibleInstances) {
  28355. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  28356. var instance = visibleInstances[instanceIndex];
  28357. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  28358. offset += 16;
  28359. instancesCount++;
  28360. }
  28361. }
  28362. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  28363. if (instancesBuffer) {
  28364. instancesBuffer.dispose();
  28365. }
  28366. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  28367. this._instancesBuffer = instancesBuffer;
  28368. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  28369. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  28370. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  28371. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  28372. }
  28373. else {
  28374. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  28375. }
  28376. this._bind(subMesh, effect, fillMode);
  28377. this._draw(subMesh, fillMode, instancesCount);
  28378. engine.unbindInstanceAttributes();
  28379. return this;
  28380. };
  28381. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  28382. var scene = this.getScene();
  28383. var engine = scene.getEngine();
  28384. if (hardwareInstancedRendering) {
  28385. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  28386. }
  28387. else {
  28388. if (batch.renderSelf[subMesh._id]) {
  28389. // Draw
  28390. if (onBeforeDraw) {
  28391. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  28392. }
  28393. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  28394. }
  28395. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  28396. if (visibleInstancesForSubMesh) {
  28397. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  28398. var instance = visibleInstancesForSubMesh[instanceIndex];
  28399. // World
  28400. var world = instance.getWorldMatrix();
  28401. if (onBeforeDraw) {
  28402. onBeforeDraw(true, world, effectiveMaterial);
  28403. }
  28404. // Draw
  28405. this._draw(subMesh, fillMode);
  28406. }
  28407. }
  28408. }
  28409. return this;
  28410. };
  28411. /**
  28412. * Triggers the draw call for the mesh.
  28413. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  28414. * Returns the Mesh.
  28415. */
  28416. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  28417. this.checkOcclusionQuery();
  28418. if (this._isOccluded) {
  28419. return this;
  28420. }
  28421. var scene = this.getScene();
  28422. // Managing instances
  28423. var batch = this._getInstancesRenderList(subMesh._id);
  28424. if (batch.mustReturn) {
  28425. return this;
  28426. }
  28427. // Checking geometry state
  28428. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  28429. return this;
  28430. }
  28431. this.onBeforeRenderObservable.notifyObservers(this);
  28432. var engine = scene.getEngine();
  28433. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  28434. // Material
  28435. var material = subMesh.getMaterial();
  28436. if (!material) {
  28437. return this;
  28438. }
  28439. this._effectiveMaterial = material;
  28440. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  28441. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  28442. return this;
  28443. }
  28444. }
  28445. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  28446. return this;
  28447. }
  28448. // Alpha mode
  28449. if (enableAlphaMode) {
  28450. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  28451. }
  28452. // Outline - step 1
  28453. var savedDepthWrite = engine.getDepthWrite();
  28454. if (this.renderOutline) {
  28455. engine.setDepthWrite(false);
  28456. scene.getOutlineRenderer().render(subMesh, batch);
  28457. engine.setDepthWrite(savedDepthWrite);
  28458. }
  28459. var effect;
  28460. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  28461. effect = subMesh.effect;
  28462. }
  28463. else {
  28464. effect = this._effectiveMaterial.getEffect();
  28465. }
  28466. if (!effect) {
  28467. return this;
  28468. }
  28469. var sideOrientation = this.overrideMaterialSideOrientation;
  28470. if (sideOrientation == null) {
  28471. sideOrientation = this._effectiveMaterial.sideOrientation;
  28472. if (this._getWorldMatrixDeterminant() < 0) {
  28473. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  28474. }
  28475. }
  28476. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  28477. if (this._effectiveMaterial.forceDepthWrite) {
  28478. engine.setDepthWrite(true);
  28479. }
  28480. // Bind
  28481. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  28482. if (!hardwareInstancedRendering) {
  28483. this._bind(subMesh, effect, fillMode);
  28484. }
  28485. var world = this.getWorldMatrix();
  28486. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  28487. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  28488. }
  28489. else {
  28490. this._effectiveMaterial.bind(world, this);
  28491. }
  28492. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  28493. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  28494. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  28495. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  28496. }
  28497. // Draw
  28498. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  28499. // Unbind
  28500. this._effectiveMaterial.unbind();
  28501. // Outline - step 2
  28502. if (this.renderOutline && savedDepthWrite) {
  28503. engine.setDepthWrite(true);
  28504. engine.setColorWrite(false);
  28505. scene.getOutlineRenderer().render(subMesh, batch);
  28506. engine.setColorWrite(true);
  28507. }
  28508. // Overlay
  28509. if (this.renderOverlay) {
  28510. var currentMode = engine.getAlphaMode();
  28511. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  28512. scene.getOutlineRenderer().render(subMesh, batch, true);
  28513. engine.setAlphaMode(currentMode);
  28514. }
  28515. this.onAfterRenderObservable.notifyObservers(this);
  28516. return this;
  28517. };
  28518. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  28519. if (isInstance && effectiveMaterial) {
  28520. effectiveMaterial.bindOnlyWorldMatrix(world);
  28521. }
  28522. };
  28523. /**
  28524. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  28525. */
  28526. Mesh.prototype.getEmittedParticleSystems = function () {
  28527. var results = new Array();
  28528. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  28529. var particleSystem = this.getScene().particleSystems[index];
  28530. if (particleSystem.emitter === this) {
  28531. results.push(particleSystem);
  28532. }
  28533. }
  28534. return results;
  28535. };
  28536. /**
  28537. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  28538. */
  28539. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  28540. var results = new Array();
  28541. var descendants = this.getDescendants();
  28542. descendants.push(this);
  28543. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  28544. var particleSystem = this.getScene().particleSystems[index];
  28545. var emitter = particleSystem.emitter;
  28546. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  28547. results.push(particleSystem);
  28548. }
  28549. }
  28550. return results;
  28551. };
  28552. Mesh.prototype._checkDelayState = function () {
  28553. var scene = this.getScene();
  28554. if (this._geometry) {
  28555. this._geometry.load(scene);
  28556. }
  28557. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  28558. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  28559. this._queueLoad(scene);
  28560. }
  28561. return this;
  28562. };
  28563. Mesh.prototype._queueLoad = function (scene) {
  28564. var _this = this;
  28565. scene._addPendingData(this);
  28566. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  28567. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  28568. if (data instanceof ArrayBuffer) {
  28569. _this._delayLoadingFunction(data, _this);
  28570. }
  28571. else {
  28572. _this._delayLoadingFunction(JSON.parse(data), _this);
  28573. }
  28574. _this.instances.forEach(function (instance) {
  28575. instance._syncSubMeshes();
  28576. });
  28577. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  28578. scene._removePendingData(_this);
  28579. }, function () { }, scene.database, getBinaryData);
  28580. return this;
  28581. };
  28582. /**
  28583. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  28584. */
  28585. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  28586. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  28587. return false;
  28588. }
  28589. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  28590. return false;
  28591. }
  28592. this._checkDelayState();
  28593. return true;
  28594. };
  28595. /**
  28596. * Sets the mesh material by the material or multiMaterial `id` property.
  28597. * The material `id` is a string identifying the material or the multiMaterial.
  28598. * This method returns the Mesh.
  28599. */
  28600. Mesh.prototype.setMaterialByID = function (id) {
  28601. var materials = this.getScene().materials;
  28602. var index;
  28603. for (index = materials.length - 1; index > -1; index--) {
  28604. if (materials[index].id === id) {
  28605. this.material = materials[index];
  28606. return this;
  28607. }
  28608. }
  28609. // Multi
  28610. var multiMaterials = this.getScene().multiMaterials;
  28611. for (index = multiMaterials.length - 1; index > -1; index--) {
  28612. if (multiMaterials[index].id === id) {
  28613. this.material = multiMaterials[index];
  28614. return this;
  28615. }
  28616. }
  28617. return this;
  28618. };
  28619. /**
  28620. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  28621. */
  28622. Mesh.prototype.getAnimatables = function () {
  28623. var results = new Array();
  28624. if (this.material) {
  28625. results.push(this.material);
  28626. }
  28627. if (this.skeleton) {
  28628. results.push(this.skeleton);
  28629. }
  28630. return results;
  28631. };
  28632. /**
  28633. * Modifies the mesh geometry according to the passed transformation matrix.
  28634. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  28635. * The mesh normals are modified accordingly the same transformation.
  28636. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  28637. * Note that, under the hood, this method sets a new VertexBuffer each call.
  28638. * Returns the Mesh.
  28639. */
  28640. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  28641. // Position
  28642. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  28643. return this;
  28644. }
  28645. var submeshes = this.subMeshes.splice(0);
  28646. this._resetPointsArrayCache();
  28647. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28648. var temp = new Array();
  28649. var index;
  28650. for (index = 0; index < data.length; index += 3) {
  28651. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  28652. }
  28653. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  28654. // Normals
  28655. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  28656. return this;
  28657. }
  28658. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28659. temp = [];
  28660. for (index = 0; index < data.length; index += 3) {
  28661. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  28662. }
  28663. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  28664. // flip faces?
  28665. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  28666. this.flipFaces();
  28667. }
  28668. // Restore submeshes
  28669. this.releaseSubMeshes();
  28670. this.subMeshes = submeshes;
  28671. return this;
  28672. };
  28673. /**
  28674. * Modifies the mesh geometry according to its own current World Matrix.
  28675. * The mesh World Matrix is then reset.
  28676. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  28677. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  28678. * Note that, under the hood, this method sets a new VertexBuffer each call.
  28679. * Returns the Mesh.
  28680. */
  28681. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  28682. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  28683. this.scaling.copyFromFloats(1, 1, 1);
  28684. this.position.copyFromFloats(0, 0, 0);
  28685. this.rotation.copyFromFloats(0, 0, 0);
  28686. //only if quaternion is already set
  28687. if (this.rotationQuaternion) {
  28688. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  28689. }
  28690. this._worldMatrix = BABYLON.Matrix.Identity();
  28691. return this;
  28692. };
  28693. Object.defineProperty(Mesh.prototype, "_positions", {
  28694. // Cache
  28695. get: function () {
  28696. if (this._geometry) {
  28697. return this._geometry._positions;
  28698. }
  28699. return null;
  28700. },
  28701. enumerable: true,
  28702. configurable: true
  28703. });
  28704. Mesh.prototype._resetPointsArrayCache = function () {
  28705. if (this._geometry) {
  28706. this._geometry._resetPointsArrayCache();
  28707. }
  28708. return this;
  28709. };
  28710. Mesh.prototype._generatePointsArray = function () {
  28711. if (this._geometry) {
  28712. return this._geometry._generatePointsArray();
  28713. }
  28714. return false;
  28715. };
  28716. /**
  28717. * Returns a new Mesh object generated from the current mesh properties.
  28718. * This method must not get confused with createInstance().
  28719. * The parameter `name` is a string, the name given to the new mesh.
  28720. * The optional parameter `newParent` can be any Node object (default `null`).
  28721. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  28722. * 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.
  28723. */
  28724. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  28725. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  28726. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  28727. };
  28728. /**
  28729. * Disposes the Mesh.
  28730. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  28731. * Returns nothing.
  28732. */
  28733. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  28734. var _this = this;
  28735. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  28736. this.morphTargetManager = null;
  28737. if (this._geometry) {
  28738. this._geometry.releaseForMesh(this, true);
  28739. }
  28740. // Sources
  28741. var meshes = this.getScene().meshes;
  28742. meshes.forEach(function (abstractMesh) {
  28743. var mesh = abstractMesh;
  28744. if (mesh._source && mesh._source === _this) {
  28745. mesh._source = null;
  28746. }
  28747. });
  28748. this._source = null;
  28749. // Instances
  28750. if (this._instancesBuffer) {
  28751. this._instancesBuffer.dispose();
  28752. this._instancesBuffer = null;
  28753. }
  28754. while (this.instances.length) {
  28755. this.instances[0].dispose();
  28756. }
  28757. // Effect layers.
  28758. var effectLayers = this.getScene().effectLayers;
  28759. for (var i = 0; i < effectLayers.length; i++) {
  28760. var effectLayer = effectLayers[i];
  28761. if (effectLayer) {
  28762. effectLayer._disposeMesh(this);
  28763. }
  28764. }
  28765. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  28766. };
  28767. /**
  28768. * Modifies the mesh geometry according to a displacement map.
  28769. * 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.
  28770. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  28771. * This method returns nothing.
  28772. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  28773. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  28774. * 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.
  28775. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  28776. * The parameter `uvScale` is an optional vector2 used to scale UV.
  28777. *
  28778. * Returns the Mesh.
  28779. */
  28780. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  28781. var _this = this;
  28782. var scene = this.getScene();
  28783. var onload = function (img) {
  28784. // Getting height map data
  28785. var canvas = document.createElement("canvas");
  28786. var context = canvas.getContext("2d");
  28787. var heightMapWidth = img.width;
  28788. var heightMapHeight = img.height;
  28789. canvas.width = heightMapWidth;
  28790. canvas.height = heightMapHeight;
  28791. context.drawImage(img, 0, 0);
  28792. // Create VertexData from map data
  28793. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  28794. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  28795. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  28796. //execute success callback, if set
  28797. if (onSuccess) {
  28798. onSuccess(_this);
  28799. }
  28800. };
  28801. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  28802. return this;
  28803. };
  28804. /**
  28805. * Modifies the mesh geometry according to a displacementMap buffer.
  28806. * 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.
  28807. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  28808. * This method returns nothing.
  28809. * 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.
  28810. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  28811. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  28812. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  28813. * The parameter `uvScale` is an optional vector2 used to scale UV.
  28814. *
  28815. * Returns the Mesh.
  28816. */
  28817. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  28818. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  28819. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  28820. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  28821. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  28822. return this;
  28823. }
  28824. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28825. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28826. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  28827. var position = BABYLON.Vector3.Zero();
  28828. var normal = BABYLON.Vector3.Zero();
  28829. var uv = BABYLON.Vector2.Zero();
  28830. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  28831. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  28832. for (var index = 0; index < positions.length; index += 3) {
  28833. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  28834. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  28835. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  28836. // Compute height
  28837. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  28838. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  28839. var pos = (u + v * heightMapWidth) * 4;
  28840. var r = buffer[pos] / 255.0;
  28841. var g = buffer[pos + 1] / 255.0;
  28842. var b = buffer[pos + 2] / 255.0;
  28843. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  28844. normal.normalize();
  28845. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  28846. position = position.add(normal);
  28847. position.toArray(positions, index);
  28848. }
  28849. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  28850. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  28851. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  28852. return this;
  28853. };
  28854. /**
  28855. * Modify the mesh to get a flat shading rendering.
  28856. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  28857. * This method returns the Mesh.
  28858. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  28859. */
  28860. Mesh.prototype.convertToFlatShadedMesh = function () {
  28861. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  28862. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  28863. var kinds = this.getVerticesDataKinds();
  28864. var vbs = {};
  28865. var data = {};
  28866. var newdata = {};
  28867. var updatableNormals = false;
  28868. var kindIndex;
  28869. var kind;
  28870. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28871. kind = kinds[kindIndex];
  28872. var vertexBuffer = this.getVertexBuffer(kind);
  28873. if (kind === BABYLON.VertexBuffer.NormalKind) {
  28874. updatableNormals = vertexBuffer.isUpdatable();
  28875. kinds.splice(kindIndex, 1);
  28876. kindIndex--;
  28877. continue;
  28878. }
  28879. vbs[kind] = vertexBuffer;
  28880. data[kind] = vbs[kind].getData();
  28881. newdata[kind] = [];
  28882. }
  28883. // Save previous submeshes
  28884. var previousSubmeshes = this.subMeshes.slice(0);
  28885. var indices = this.getIndices();
  28886. var totalIndices = this.getTotalIndices();
  28887. // Generating unique vertices per face
  28888. var index;
  28889. for (index = 0; index < totalIndices; index++) {
  28890. var vertexIndex = indices[index];
  28891. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28892. kind = kinds[kindIndex];
  28893. var stride = vbs[kind].getStrideSize();
  28894. for (var offset = 0; offset < stride; offset++) {
  28895. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  28896. }
  28897. }
  28898. }
  28899. // Updating faces & normal
  28900. var normals = [];
  28901. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  28902. for (index = 0; index < totalIndices; index += 3) {
  28903. indices[index] = index;
  28904. indices[index + 1] = index + 1;
  28905. indices[index + 2] = index + 2;
  28906. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  28907. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  28908. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  28909. var p1p2 = p1.subtract(p2);
  28910. var p3p2 = p3.subtract(p2);
  28911. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  28912. // Store same normals for every vertex
  28913. for (var localIndex = 0; localIndex < 3; localIndex++) {
  28914. normals.push(normal.x);
  28915. normals.push(normal.y);
  28916. normals.push(normal.z);
  28917. }
  28918. }
  28919. this.setIndices(indices);
  28920. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  28921. // Updating vertex buffers
  28922. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28923. kind = kinds[kindIndex];
  28924. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  28925. }
  28926. // Updating submeshes
  28927. this.releaseSubMeshes();
  28928. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  28929. var previousOne = previousSubmeshes[submeshIndex];
  28930. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  28931. }
  28932. this.synchronizeInstances();
  28933. return this;
  28934. };
  28935. /**
  28936. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  28937. * In other words, more vertices, no more indices and a single bigger VBO.
  28938. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  28939. * Returns the Mesh.
  28940. */
  28941. Mesh.prototype.convertToUnIndexedMesh = function () {
  28942. /// <summary>Remove indices by unfolding faces into buffers</summary>
  28943. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  28944. var kinds = this.getVerticesDataKinds();
  28945. var vbs = {};
  28946. var data = {};
  28947. var newdata = {};
  28948. var kindIndex;
  28949. var kind;
  28950. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28951. kind = kinds[kindIndex];
  28952. var vertexBuffer = this.getVertexBuffer(kind);
  28953. vbs[kind] = vertexBuffer;
  28954. data[kind] = vbs[kind].getData();
  28955. newdata[kind] = [];
  28956. }
  28957. // Save previous submeshes
  28958. var previousSubmeshes = this.subMeshes.slice(0);
  28959. var indices = this.getIndices();
  28960. var totalIndices = this.getTotalIndices();
  28961. // Generating unique vertices per face
  28962. var index;
  28963. for (index = 0; index < totalIndices; index++) {
  28964. var vertexIndex = indices[index];
  28965. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28966. kind = kinds[kindIndex];
  28967. var stride = vbs[kind].getStrideSize();
  28968. for (var offset = 0; offset < stride; offset++) {
  28969. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  28970. }
  28971. }
  28972. }
  28973. // Updating indices
  28974. for (index = 0; index < totalIndices; index += 3) {
  28975. indices[index] = index;
  28976. indices[index + 1] = index + 1;
  28977. indices[index + 2] = index + 2;
  28978. }
  28979. this.setIndices(indices);
  28980. // Updating vertex buffers
  28981. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28982. kind = kinds[kindIndex];
  28983. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  28984. }
  28985. // Updating submeshes
  28986. this.releaseSubMeshes();
  28987. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  28988. var previousOne = previousSubmeshes[submeshIndex];
  28989. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  28990. }
  28991. this._unIndexed = true;
  28992. this.synchronizeInstances();
  28993. return this;
  28994. };
  28995. /**
  28996. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  28997. * This method returns the Mesh.
  28998. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  28999. */
  29000. Mesh.prototype.flipFaces = function (flipNormals) {
  29001. if (flipNormals === void 0) { flipNormals = false; }
  29002. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  29003. var i;
  29004. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  29005. for (i = 0; i < vertex_data.normals.length; i++) {
  29006. vertex_data.normals[i] *= -1;
  29007. }
  29008. }
  29009. if (vertex_data.indices) {
  29010. var temp;
  29011. for (i = 0; i < vertex_data.indices.length; i += 3) {
  29012. // reassign indices
  29013. temp = vertex_data.indices[i + 1];
  29014. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  29015. vertex_data.indices[i + 2] = temp;
  29016. }
  29017. }
  29018. vertex_data.applyToMesh(this);
  29019. return this;
  29020. };
  29021. // Instances
  29022. /**
  29023. * Creates a new InstancedMesh object from the mesh model.
  29024. * An instance shares the same properties and the same material than its model.
  29025. * Only these properties of each instance can then be set individually :
  29026. * - position
  29027. * - rotation
  29028. * - rotationQuaternion
  29029. * - setPivotMatrix
  29030. * - scaling
  29031. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  29032. * Warning : this method is not supported for Line mesh and LineSystem
  29033. */
  29034. Mesh.prototype.createInstance = function (name) {
  29035. return new BABYLON.InstancedMesh(name, this);
  29036. };
  29037. /**
  29038. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  29039. * After this call, all the mesh instances have the same submeshes than the current mesh.
  29040. * This method returns the Mesh.
  29041. */
  29042. Mesh.prototype.synchronizeInstances = function () {
  29043. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  29044. var instance = this.instances[instanceIndex];
  29045. instance._syncSubMeshes();
  29046. }
  29047. return this;
  29048. };
  29049. /**
  29050. * Simplify the mesh according to the given array of settings.
  29051. * Function will return immediately and will simplify async. It returns the Mesh.
  29052. * @param settings a collection of simplification settings.
  29053. * @param parallelProcessing should all levels calculate parallel or one after the other.
  29054. * @param type the type of simplification to run.
  29055. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  29056. */
  29057. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  29058. if (parallelProcessing === void 0) { parallelProcessing = true; }
  29059. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  29060. this.getScene().simplificationQueue.addTask({
  29061. settings: settings,
  29062. parallelProcessing: parallelProcessing,
  29063. mesh: this,
  29064. simplificationType: simplificationType,
  29065. successCallback: successCallback
  29066. });
  29067. return this;
  29068. };
  29069. /**
  29070. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  29071. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  29072. * This should be used together with the simplification to avoid disappearing triangles.
  29073. * Returns the Mesh.
  29074. * @param successCallback an optional success callback to be called after the optimization finished.
  29075. */
  29076. Mesh.prototype.optimizeIndices = function (successCallback) {
  29077. var _this = this;
  29078. var indices = this.getIndices();
  29079. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29080. if (!positions || !indices) {
  29081. return this;
  29082. }
  29083. var vectorPositions = new Array();
  29084. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  29085. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  29086. }
  29087. var dupes = new Array();
  29088. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  29089. var realPos = vectorPositions.length - 1 - iteration;
  29090. var testedPosition = vectorPositions[realPos];
  29091. for (var j = 0; j < realPos; ++j) {
  29092. var againstPosition = vectorPositions[j];
  29093. if (testedPosition.equals(againstPosition)) {
  29094. dupes[realPos] = j;
  29095. break;
  29096. }
  29097. }
  29098. }, function () {
  29099. for (var i = 0; i < indices.length; ++i) {
  29100. indices[i] = dupes[indices[i]] || indices[i];
  29101. }
  29102. //indices are now reordered
  29103. var originalSubMeshes = _this.subMeshes.slice(0);
  29104. _this.setIndices(indices);
  29105. _this.subMeshes = originalSubMeshes;
  29106. if (successCallback) {
  29107. successCallback(_this);
  29108. }
  29109. });
  29110. return this;
  29111. };
  29112. Mesh.prototype.serialize = function (serializationObject) {
  29113. serializationObject.name = this.name;
  29114. serializationObject.id = this.id;
  29115. serializationObject.type = this.getClassName();
  29116. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  29117. serializationObject.tags = BABYLON.Tags.GetTags(this);
  29118. }
  29119. serializationObject.position = this.position.asArray();
  29120. if (this.rotationQuaternion) {
  29121. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  29122. }
  29123. else if (this.rotation) {
  29124. serializationObject.rotation = this.rotation.asArray();
  29125. }
  29126. serializationObject.scaling = this.scaling.asArray();
  29127. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  29128. serializationObject.isEnabled = this.isEnabled(false);
  29129. serializationObject.isVisible = this.isVisible;
  29130. serializationObject.infiniteDistance = this.infiniteDistance;
  29131. serializationObject.pickable = this.isPickable;
  29132. serializationObject.receiveShadows = this.receiveShadows;
  29133. serializationObject.billboardMode = this.billboardMode;
  29134. serializationObject.visibility = this.visibility;
  29135. serializationObject.checkCollisions = this.checkCollisions;
  29136. serializationObject.isBlocker = this.isBlocker;
  29137. // Parent
  29138. if (this.parent) {
  29139. serializationObject.parentId = this.parent.id;
  29140. }
  29141. // Geometry
  29142. serializationObject.isUnIndexed = this.isUnIndexed;
  29143. var geometry = this._geometry;
  29144. if (geometry) {
  29145. var geometryId = geometry.id;
  29146. serializationObject.geometryId = geometryId;
  29147. // SubMeshes
  29148. serializationObject.subMeshes = [];
  29149. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  29150. var subMesh = this.subMeshes[subIndex];
  29151. serializationObject.subMeshes.push({
  29152. materialIndex: subMesh.materialIndex,
  29153. verticesStart: subMesh.verticesStart,
  29154. verticesCount: subMesh.verticesCount,
  29155. indexStart: subMesh.indexStart,
  29156. indexCount: subMesh.indexCount
  29157. });
  29158. }
  29159. }
  29160. // Material
  29161. if (this.material) {
  29162. serializationObject.materialId = this.material.id;
  29163. }
  29164. else {
  29165. this.material = null;
  29166. }
  29167. // Morph targets
  29168. if (this.morphTargetManager) {
  29169. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  29170. }
  29171. // Skeleton
  29172. if (this.skeleton) {
  29173. serializationObject.skeletonId = this.skeleton.id;
  29174. }
  29175. // Physics
  29176. //TODO implement correct serialization for physics impostors.
  29177. var impostor = this.getPhysicsImpostor();
  29178. if (impostor) {
  29179. serializationObject.physicsMass = impostor.getParam("mass");
  29180. serializationObject.physicsFriction = impostor.getParam("friction");
  29181. serializationObject.physicsRestitution = impostor.getParam("mass");
  29182. serializationObject.physicsImpostor = impostor.type;
  29183. }
  29184. // Metadata
  29185. if (this.metadata) {
  29186. serializationObject.metadata = this.metadata;
  29187. }
  29188. // Instances
  29189. serializationObject.instances = [];
  29190. for (var index = 0; index < this.instances.length; index++) {
  29191. var instance = this.instances[index];
  29192. var serializationInstance = {
  29193. name: instance.name,
  29194. id: instance.id,
  29195. position: instance.position.asArray(),
  29196. scaling: instance.scaling.asArray()
  29197. };
  29198. if (instance.rotationQuaternion) {
  29199. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  29200. }
  29201. else if (instance.rotation) {
  29202. serializationInstance.rotation = instance.rotation.asArray();
  29203. }
  29204. serializationObject.instances.push(serializationInstance);
  29205. // Animations
  29206. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  29207. serializationInstance.ranges = instance.serializeAnimationRanges();
  29208. }
  29209. //
  29210. // Animations
  29211. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  29212. serializationObject.ranges = this.serializeAnimationRanges();
  29213. // Layer mask
  29214. serializationObject.layerMask = this.layerMask;
  29215. // Alpha
  29216. serializationObject.alphaIndex = this.alphaIndex;
  29217. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  29218. // Overlay
  29219. serializationObject.overlayAlpha = this.overlayAlpha;
  29220. serializationObject.overlayColor = this.overlayColor.asArray();
  29221. serializationObject.renderOverlay = this.renderOverlay;
  29222. // Fog
  29223. serializationObject.applyFog = this.applyFog;
  29224. // Action Manager
  29225. if (this.actionManager) {
  29226. serializationObject.actions = this.actionManager.serialize(this.name);
  29227. }
  29228. };
  29229. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  29230. if (!this.geometry) {
  29231. return;
  29232. }
  29233. this._markSubMeshesAsAttributesDirty();
  29234. var morphTargetManager = this._morphTargetManager;
  29235. if (morphTargetManager && morphTargetManager.vertexCount) {
  29236. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  29237. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  29238. this.morphTargetManager = null;
  29239. return;
  29240. }
  29241. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  29242. var morphTarget = morphTargetManager.getActiveTarget(index);
  29243. var positions = morphTarget.getPositions();
  29244. if (!positions) {
  29245. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  29246. return;
  29247. }
  29248. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  29249. var normals = morphTarget.getNormals();
  29250. if (normals) {
  29251. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  29252. }
  29253. var tangents = morphTarget.getTangents();
  29254. if (tangents) {
  29255. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  29256. }
  29257. }
  29258. }
  29259. else {
  29260. var index = 0;
  29261. // Positions
  29262. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  29263. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  29264. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  29265. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  29266. }
  29267. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  29268. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  29269. }
  29270. index++;
  29271. }
  29272. }
  29273. };
  29274. // Statics
  29275. /**
  29276. * Returns a new Mesh object parsed from the source provided.
  29277. * The parameter `parsedMesh` is the source.
  29278. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  29279. */
  29280. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  29281. var mesh;
  29282. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  29283. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  29284. }
  29285. else {
  29286. mesh = new Mesh(parsedMesh.name, scene);
  29287. }
  29288. mesh.id = parsedMesh.id;
  29289. if (BABYLON.Tags) {
  29290. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  29291. }
  29292. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  29293. if (parsedMesh.metadata !== undefined) {
  29294. mesh.metadata = parsedMesh.metadata;
  29295. }
  29296. if (parsedMesh.rotationQuaternion) {
  29297. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  29298. }
  29299. else if (parsedMesh.rotation) {
  29300. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  29301. }
  29302. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  29303. if (parsedMesh.localMatrix) {
  29304. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  29305. }
  29306. else if (parsedMesh.pivotMatrix) {
  29307. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  29308. }
  29309. mesh.setEnabled(parsedMesh.isEnabled);
  29310. mesh.isVisible = parsedMesh.isVisible;
  29311. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  29312. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  29313. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  29314. if (parsedMesh.applyFog !== undefined) {
  29315. mesh.applyFog = parsedMesh.applyFog;
  29316. }
  29317. if (parsedMesh.pickable !== undefined) {
  29318. mesh.isPickable = parsedMesh.pickable;
  29319. }
  29320. if (parsedMesh.alphaIndex !== undefined) {
  29321. mesh.alphaIndex = parsedMesh.alphaIndex;
  29322. }
  29323. mesh.receiveShadows = parsedMesh.receiveShadows;
  29324. mesh.billboardMode = parsedMesh.billboardMode;
  29325. if (parsedMesh.visibility !== undefined) {
  29326. mesh.visibility = parsedMesh.visibility;
  29327. }
  29328. mesh.checkCollisions = parsedMesh.checkCollisions;
  29329. if (parsedMesh.isBlocker !== undefined) {
  29330. mesh.isBlocker = parsedMesh.isBlocker;
  29331. }
  29332. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  29333. // freezeWorldMatrix
  29334. if (parsedMesh.freezeWorldMatrix) {
  29335. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  29336. }
  29337. // Parent
  29338. if (parsedMesh.parentId) {
  29339. mesh._waitingParentId = parsedMesh.parentId;
  29340. }
  29341. // Actions
  29342. if (parsedMesh.actions !== undefined) {
  29343. mesh._waitingActions = parsedMesh.actions;
  29344. }
  29345. // Overlay
  29346. if (parsedMesh.overlayAlpha !== undefined) {
  29347. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  29348. }
  29349. if (parsedMesh.overlayColor !== undefined) {
  29350. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  29351. }
  29352. if (parsedMesh.renderOverlay !== undefined) {
  29353. mesh.renderOverlay = parsedMesh.renderOverlay;
  29354. }
  29355. // Geometry
  29356. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  29357. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  29358. if (parsedMesh.delayLoadingFile) {
  29359. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  29360. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  29361. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  29362. if (parsedMesh._binaryInfo) {
  29363. mesh._binaryInfo = parsedMesh._binaryInfo;
  29364. }
  29365. mesh._delayInfo = [];
  29366. if (parsedMesh.hasUVs) {
  29367. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  29368. }
  29369. if (parsedMesh.hasUVs2) {
  29370. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  29371. }
  29372. if (parsedMesh.hasUVs3) {
  29373. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  29374. }
  29375. if (parsedMesh.hasUVs4) {
  29376. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  29377. }
  29378. if (parsedMesh.hasUVs5) {
  29379. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  29380. }
  29381. if (parsedMesh.hasUVs6) {
  29382. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  29383. }
  29384. if (parsedMesh.hasColors) {
  29385. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  29386. }
  29387. if (parsedMesh.hasMatricesIndices) {
  29388. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  29389. }
  29390. if (parsedMesh.hasMatricesWeights) {
  29391. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  29392. }
  29393. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  29394. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  29395. mesh._checkDelayState();
  29396. }
  29397. }
  29398. else {
  29399. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  29400. }
  29401. // Material
  29402. if (parsedMesh.materialId) {
  29403. mesh.setMaterialByID(parsedMesh.materialId);
  29404. }
  29405. else {
  29406. mesh.material = null;
  29407. }
  29408. // Morph targets
  29409. if (parsedMesh.morphTargetManagerId > -1) {
  29410. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  29411. }
  29412. // Skeleton
  29413. if (parsedMesh.skeletonId > -1) {
  29414. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  29415. if (parsedMesh.numBoneInfluencers) {
  29416. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  29417. }
  29418. }
  29419. // Animations
  29420. if (parsedMesh.animations) {
  29421. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  29422. var parsedAnimation = parsedMesh.animations[animationIndex];
  29423. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  29424. }
  29425. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  29426. }
  29427. if (parsedMesh.autoAnimate) {
  29428. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  29429. }
  29430. // Layer Mask
  29431. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  29432. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  29433. }
  29434. else {
  29435. mesh.layerMask = 0x0FFFFFFF;
  29436. }
  29437. // Physics
  29438. if (parsedMesh.physicsImpostor) {
  29439. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  29440. mass: parsedMesh.physicsMass,
  29441. friction: parsedMesh.physicsFriction,
  29442. restitution: parsedMesh.physicsRestitution
  29443. }, scene);
  29444. }
  29445. // Instances
  29446. if (parsedMesh.instances) {
  29447. for (var index = 0; index < parsedMesh.instances.length; index++) {
  29448. var parsedInstance = parsedMesh.instances[index];
  29449. var instance = mesh.createInstance(parsedInstance.name);
  29450. if (parsedInstance.id) {
  29451. instance.id = parsedInstance.id;
  29452. }
  29453. if (BABYLON.Tags) {
  29454. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  29455. }
  29456. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  29457. if (parsedInstance.parentId) {
  29458. instance._waitingParentId = parsedInstance.parentId;
  29459. }
  29460. if (parsedInstance.rotationQuaternion) {
  29461. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  29462. }
  29463. else if (parsedInstance.rotation) {
  29464. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  29465. }
  29466. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  29467. instance.checkCollisions = mesh.checkCollisions;
  29468. if (parsedMesh.animations) {
  29469. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  29470. parsedAnimation = parsedMesh.animations[animationIndex];
  29471. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  29472. }
  29473. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  29474. }
  29475. }
  29476. }
  29477. return mesh;
  29478. };
  29479. /**
  29480. * Creates a ribbon mesh.
  29481. * Please consider using the same method from the MeshBuilder class instead.
  29482. * 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.
  29483. *
  29484. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  29485. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  29486. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  29487. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  29488. * 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.
  29489. * 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.
  29490. * 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
  29491. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29492. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29493. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29494. */
  29495. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  29496. if (closeArray === void 0) { closeArray = false; }
  29497. if (updatable === void 0) { updatable = false; }
  29498. return BABYLON.MeshBuilder.CreateRibbon(name, {
  29499. pathArray: pathArray,
  29500. closeArray: closeArray,
  29501. closePath: closePath,
  29502. offset: offset,
  29503. updatable: updatable,
  29504. sideOrientation: sideOrientation,
  29505. instance: instance
  29506. }, scene);
  29507. };
  29508. /**
  29509. * Creates a plane polygonal mesh. By default, this is a disc.
  29510. * Please consider using the same method from the MeshBuilder class instead.
  29511. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  29512. * 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.
  29513. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29514. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29515. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29516. */
  29517. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  29518. if (scene === void 0) { scene = null; }
  29519. var options = {
  29520. radius: radius,
  29521. tessellation: tessellation,
  29522. sideOrientation: sideOrientation,
  29523. updatable: updatable
  29524. };
  29525. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  29526. };
  29527. /**
  29528. * Creates a box mesh.
  29529. * Please consider using the same method from the MeshBuilder class instead.
  29530. * The parameter `size` sets the size (float) of each box side (default 1).
  29531. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29532. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29533. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29534. */
  29535. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  29536. if (scene === void 0) { scene = null; }
  29537. var options = {
  29538. size: size,
  29539. sideOrientation: sideOrientation,
  29540. updatable: updatable
  29541. };
  29542. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  29543. };
  29544. /**
  29545. * Creates a sphere mesh.
  29546. * Please consider using the same method from the MeshBuilder class instead.
  29547. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  29548. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  29549. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29550. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29551. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29552. */
  29553. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  29554. var options = {
  29555. segments: segments,
  29556. diameterX: diameter,
  29557. diameterY: diameter,
  29558. diameterZ: diameter,
  29559. sideOrientation: sideOrientation,
  29560. updatable: updatable
  29561. };
  29562. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  29563. };
  29564. /**
  29565. * Creates a cylinder or a cone mesh.
  29566. * Please consider using the same method from the MeshBuilder class instead.
  29567. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  29568. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  29569. * 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.
  29570. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  29571. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  29572. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29573. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29574. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29575. */
  29576. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  29577. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  29578. if (scene !== undefined) {
  29579. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  29580. updatable = scene;
  29581. }
  29582. scene = subdivisions;
  29583. subdivisions = 1;
  29584. }
  29585. var options = {
  29586. height: height,
  29587. diameterTop: diameterTop,
  29588. diameterBottom: diameterBottom,
  29589. tessellation: tessellation,
  29590. subdivisions: subdivisions,
  29591. sideOrientation: sideOrientation,
  29592. updatable: updatable
  29593. };
  29594. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  29595. };
  29596. // Torus (Code from SharpDX.org)
  29597. /**
  29598. * Creates a torus mesh.
  29599. * Please consider using the same method from the MeshBuilder class instead.
  29600. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  29601. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  29602. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  29603. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29604. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29605. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29606. */
  29607. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  29608. var options = {
  29609. diameter: diameter,
  29610. thickness: thickness,
  29611. tessellation: tessellation,
  29612. sideOrientation: sideOrientation,
  29613. updatable: updatable
  29614. };
  29615. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  29616. };
  29617. /**
  29618. * Creates a torus knot mesh.
  29619. * Please consider using the same method from the MeshBuilder class instead.
  29620. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  29621. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  29622. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  29623. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  29624. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29625. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29626. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29627. */
  29628. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  29629. var options = {
  29630. radius: radius,
  29631. tube: tube,
  29632. radialSegments: radialSegments,
  29633. tubularSegments: tubularSegments,
  29634. p: p,
  29635. q: q,
  29636. sideOrientation: sideOrientation,
  29637. updatable: updatable
  29638. };
  29639. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  29640. };
  29641. /**
  29642. * Creates a line mesh.
  29643. * Please consider using the same method from the MeshBuilder class instead.
  29644. * 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.
  29645. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  29646. * The parameter `points` is an array successive Vector3.
  29647. * 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
  29648. * When updating an instance, remember that only point positions can change, not the number of points.
  29649. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29650. */
  29651. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  29652. if (scene === void 0) { scene = null; }
  29653. if (updatable === void 0) { updatable = false; }
  29654. if (instance === void 0) { instance = null; }
  29655. var options = {
  29656. points: points,
  29657. updatable: updatable,
  29658. instance: instance
  29659. };
  29660. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  29661. };
  29662. /**
  29663. * Creates a dashed line mesh.
  29664. * Please consider using the same method from the MeshBuilder class instead.
  29665. * 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.
  29666. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  29667. * The parameter `points` is an array successive Vector3.
  29668. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  29669. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  29670. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  29671. * 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
  29672. * When updating an instance, remember that only point positions can change, not the number of points.
  29673. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29674. */
  29675. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  29676. if (scene === void 0) { scene = null; }
  29677. var options = {
  29678. points: points,
  29679. dashSize: dashSize,
  29680. gapSize: gapSize,
  29681. dashNb: dashNb,
  29682. updatable: updatable,
  29683. instance: instance
  29684. };
  29685. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  29686. };
  29687. /**
  29688. * Creates a polygon mesh.
  29689. * Please consider using the same method from the MeshBuilder class instead.
  29690. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  29691. * 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.
  29692. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29693. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29694. * Remember you can only change the shape positions, not their number when updating a polygon.
  29695. */
  29696. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  29697. var options = {
  29698. shape: shape,
  29699. holes: holes,
  29700. updatable: updatable,
  29701. sideOrientation: sideOrientation
  29702. };
  29703. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  29704. };
  29705. /**
  29706. * Creates an extruded polygon mesh, with depth in the Y direction.
  29707. * Please consider using the same method from the MeshBuilder class instead.
  29708. */
  29709. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  29710. var options = {
  29711. shape: shape,
  29712. holes: holes,
  29713. depth: depth,
  29714. updatable: updatable,
  29715. sideOrientation: sideOrientation
  29716. };
  29717. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  29718. };
  29719. /**
  29720. * Creates an extruded shape mesh.
  29721. * 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.
  29722. * Please consider using the same method from the MeshBuilder class instead.
  29723. *
  29724. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  29725. * 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
  29726. * extruded along the Z axis.
  29727. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  29728. * 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.
  29729. * The parameter `scale` (float, default 1) is the value to scale the shape.
  29730. * 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
  29731. * 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
  29732. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  29733. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29734. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29735. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29736. */
  29737. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  29738. if (scene === void 0) { scene = null; }
  29739. var options = {
  29740. shape: shape,
  29741. path: path,
  29742. scale: scale,
  29743. rotation: rotation,
  29744. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  29745. sideOrientation: sideOrientation,
  29746. instance: instance,
  29747. updatable: updatable
  29748. };
  29749. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  29750. };
  29751. /**
  29752. * Creates an custom extruded shape mesh.
  29753. * 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.
  29754. * Please consider using the same method from the MeshBuilder class instead.
  29755. *
  29756. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  29757. * 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
  29758. * extruded along the Z axis.
  29759. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  29760. * 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
  29761. * and the distance of this point from the begining of the path :
  29762. * ```javascript
  29763. * var rotationFunction = function(i, distance) {
  29764. * // do things
  29765. * return rotationValue; }
  29766. * ```
  29767. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  29768. * 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
  29769. * and the distance of this point from the begining of the path :
  29770. * ```javascript
  29771. * var scaleFunction = function(i, distance) {
  29772. * // do things
  29773. * return scaleValue;}
  29774. * ```
  29775. * It must returns a float value that will be the scale value applied to the shape on each path point.
  29776. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  29777. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  29778. * 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
  29779. * 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
  29780. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  29781. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29782. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29783. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29784. */
  29785. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  29786. var options = {
  29787. shape: shape,
  29788. path: path,
  29789. scaleFunction: scaleFunction,
  29790. rotationFunction: rotationFunction,
  29791. ribbonCloseArray: ribbonCloseArray,
  29792. ribbonClosePath: ribbonClosePath,
  29793. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  29794. sideOrientation: sideOrientation,
  29795. instance: instance,
  29796. updatable: updatable
  29797. };
  29798. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  29799. };
  29800. /**
  29801. * Creates lathe mesh.
  29802. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  29803. * Please consider using the same method from the MeshBuilder class instead.
  29804. * 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
  29805. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  29806. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  29807. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  29808. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29809. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29810. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29811. */
  29812. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  29813. var options = {
  29814. shape: shape,
  29815. radius: radius,
  29816. tessellation: tessellation,
  29817. sideOrientation: sideOrientation,
  29818. updatable: updatable
  29819. };
  29820. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  29821. };
  29822. /**
  29823. * Creates a plane mesh.
  29824. * Please consider using the same method from the MeshBuilder class instead.
  29825. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  29826. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29827. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29828. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29829. */
  29830. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  29831. var options = {
  29832. size: size,
  29833. width: size,
  29834. height: size,
  29835. sideOrientation: sideOrientation,
  29836. updatable: updatable
  29837. };
  29838. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  29839. };
  29840. /**
  29841. * Creates a ground mesh.
  29842. * Please consider using the same method from the MeshBuilder class instead.
  29843. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  29844. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  29845. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29846. */
  29847. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  29848. var options = {
  29849. width: width,
  29850. height: height,
  29851. subdivisions: subdivisions,
  29852. updatable: updatable
  29853. };
  29854. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  29855. };
  29856. /**
  29857. * Creates a tiled ground mesh.
  29858. * Please consider using the same method from the MeshBuilder class instead.
  29859. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  29860. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  29861. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  29862. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  29863. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  29864. * numbers of subdivisions on the ground width and height of each tile.
  29865. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29866. */
  29867. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  29868. var options = {
  29869. xmin: xmin,
  29870. zmin: zmin,
  29871. xmax: xmax,
  29872. zmax: zmax,
  29873. subdivisions: subdivisions,
  29874. precision: precision,
  29875. updatable: updatable
  29876. };
  29877. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  29878. };
  29879. /**
  29880. * Creates a ground mesh from a height map.
  29881. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  29882. * Please consider using the same method from the MeshBuilder class instead.
  29883. * The parameter `url` sets the URL of the height map image resource.
  29884. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  29885. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  29886. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  29887. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  29888. * 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).
  29889. * This function is passed the newly built mesh :
  29890. * ```javascript
  29891. * function(mesh) { // do things
  29892. * return; }
  29893. * ```
  29894. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29895. */
  29896. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  29897. var options = {
  29898. width: width,
  29899. height: height,
  29900. subdivisions: subdivisions,
  29901. minHeight: minHeight,
  29902. maxHeight: maxHeight,
  29903. updatable: updatable,
  29904. onReady: onReady
  29905. };
  29906. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  29907. };
  29908. /**
  29909. * Creates a tube mesh.
  29910. * 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.
  29911. * Please consider using the same method from the MeshBuilder class instead.
  29912. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  29913. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  29914. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  29915. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  29916. * 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.
  29917. * It must return a radius value (positive float) :
  29918. * ```javascript
  29919. * var radiusFunction = function(i, distance) {
  29920. * // do things
  29921. * return radius; }
  29922. * ```
  29923. * 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
  29924. * 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
  29925. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29926. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29927. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29928. */
  29929. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  29930. var options = {
  29931. path: path,
  29932. radius: radius,
  29933. tessellation: tessellation,
  29934. radiusFunction: radiusFunction,
  29935. arc: 1,
  29936. cap: cap,
  29937. updatable: updatable,
  29938. sideOrientation: sideOrientation,
  29939. instance: instance
  29940. };
  29941. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  29942. };
  29943. /**
  29944. * Creates a polyhedron mesh.
  29945. * Please consider using the same method from the MeshBuilder class instead.
  29946. * 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
  29947. * to choose the wanted type.
  29948. * The parameter `size` (positive float, default 1) sets the polygon size.
  29949. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  29950. * 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`.
  29951. * 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
  29952. * 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)`).
  29953. * 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
  29954. * 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.
  29955. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29956. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29957. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29958. */
  29959. Mesh.CreatePolyhedron = function (name, options, scene) {
  29960. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  29961. };
  29962. /**
  29963. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  29964. * Please consider using the same method from the MeshBuilder class instead.
  29965. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  29966. * 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`).
  29967. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  29968. * 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.
  29969. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29970. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29971. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29972. */
  29973. Mesh.CreateIcoSphere = function (name, options, scene) {
  29974. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  29975. };
  29976. /**
  29977. * Creates a decal mesh.
  29978. * Please consider using the same method from the MeshBuilder class instead.
  29979. * 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.
  29980. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  29981. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  29982. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  29983. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  29984. */
  29985. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  29986. var options = {
  29987. position: position,
  29988. normal: normal,
  29989. size: size,
  29990. angle: angle
  29991. };
  29992. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  29993. };
  29994. // Skeletons
  29995. /**
  29996. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  29997. */
  29998. Mesh.prototype.setPositionsForCPUSkinning = function () {
  29999. if (!this._sourcePositions) {
  30000. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30001. if (!source) {
  30002. return this._sourcePositions;
  30003. }
  30004. this._sourcePositions = new Float32Array(source);
  30005. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  30006. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  30007. }
  30008. }
  30009. return this._sourcePositions;
  30010. };
  30011. /**
  30012. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  30013. */
  30014. Mesh.prototype.setNormalsForCPUSkinning = function () {
  30015. if (!this._sourceNormals) {
  30016. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  30017. if (!source) {
  30018. return this._sourceNormals;
  30019. }
  30020. this._sourceNormals = new Float32Array(source);
  30021. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  30022. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  30023. }
  30024. }
  30025. return this._sourceNormals;
  30026. };
  30027. /**
  30028. * Updates the vertex buffer by applying transformation from the bones.
  30029. * Returns the Mesh.
  30030. *
  30031. * @param {skeleton} skeleton to apply
  30032. */
  30033. Mesh.prototype.applySkeleton = function (skeleton) {
  30034. if (!this.geometry) {
  30035. return this;
  30036. }
  30037. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  30038. return this;
  30039. }
  30040. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  30041. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  30042. return this;
  30043. }
  30044. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  30045. return this;
  30046. }
  30047. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  30048. return this;
  30049. }
  30050. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  30051. return this;
  30052. }
  30053. if (!this._sourcePositions) {
  30054. var submeshes = this.subMeshes.slice();
  30055. this.setPositionsForCPUSkinning();
  30056. this.subMeshes = submeshes;
  30057. }
  30058. if (!this._sourceNormals) {
  30059. this.setNormalsForCPUSkinning();
  30060. }
  30061. // positionsData checks for not being Float32Array will only pass at most once
  30062. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30063. if (!positionsData) {
  30064. return this;
  30065. }
  30066. if (!(positionsData instanceof Float32Array)) {
  30067. positionsData = new Float32Array(positionsData);
  30068. }
  30069. // normalsData checks for not being Float32Array will only pass at most once
  30070. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  30071. if (!normalsData) {
  30072. return this;
  30073. }
  30074. if (!(normalsData instanceof Float32Array)) {
  30075. normalsData = new Float32Array(normalsData);
  30076. }
  30077. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  30078. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  30079. if (!matricesWeightsData || !matricesIndicesData) {
  30080. return this;
  30081. }
  30082. var needExtras = this.numBoneInfluencers > 4;
  30083. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  30084. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  30085. var skeletonMatrices = skeleton.getTransformMatrices(this);
  30086. var tempVector3 = BABYLON.Vector3.Zero();
  30087. var finalMatrix = new BABYLON.Matrix();
  30088. var tempMatrix = new BABYLON.Matrix();
  30089. var matWeightIdx = 0;
  30090. var inf;
  30091. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  30092. var weight;
  30093. for (inf = 0; inf < 4; inf++) {
  30094. weight = matricesWeightsData[matWeightIdx + inf];
  30095. if (weight > 0) {
  30096. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  30097. finalMatrix.addToSelf(tempMatrix);
  30098. }
  30099. else
  30100. break;
  30101. }
  30102. if (needExtras) {
  30103. for (inf = 0; inf < 4; inf++) {
  30104. weight = matricesWeightsExtraData[matWeightIdx + inf];
  30105. if (weight > 0) {
  30106. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  30107. finalMatrix.addToSelf(tempMatrix);
  30108. }
  30109. else
  30110. break;
  30111. }
  30112. }
  30113. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  30114. tempVector3.toArray(positionsData, index);
  30115. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  30116. tempVector3.toArray(normalsData, index);
  30117. finalMatrix.reset();
  30118. }
  30119. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  30120. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  30121. return this;
  30122. };
  30123. // Tools
  30124. /**
  30125. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  30126. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  30127. */
  30128. Mesh.MinMax = function (meshes) {
  30129. var minVector = null;
  30130. var maxVector = null;
  30131. meshes.forEach(function (mesh, index, array) {
  30132. var boundingInfo = mesh.getBoundingInfo();
  30133. var boundingBox = boundingInfo.boundingBox;
  30134. if (!minVector || !maxVector) {
  30135. minVector = boundingBox.minimumWorld;
  30136. maxVector = boundingBox.maximumWorld;
  30137. }
  30138. else {
  30139. minVector.minimizeInPlace(boundingBox.minimumWorld);
  30140. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  30141. }
  30142. });
  30143. if (!minVector || !maxVector) {
  30144. return {
  30145. min: BABYLON.Vector3.Zero(),
  30146. max: BABYLON.Vector3.Zero()
  30147. };
  30148. }
  30149. return {
  30150. min: minVector,
  30151. max: maxVector
  30152. };
  30153. };
  30154. /**
  30155. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  30156. */
  30157. Mesh.Center = function (meshesOrMinMaxVector) {
  30158. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  30159. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  30160. };
  30161. /**
  30162. * Merge the array of meshes into a single mesh for performance reasons.
  30163. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  30164. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  30165. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  30166. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  30167. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  30168. */
  30169. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  30170. if (disposeSource === void 0) { disposeSource = true; }
  30171. var index;
  30172. if (!allow32BitsIndices) {
  30173. var totalVertices = 0;
  30174. // Counting vertices
  30175. for (index = 0; index < meshes.length; index++) {
  30176. if (meshes[index]) {
  30177. totalVertices += meshes[index].getTotalVertices();
  30178. if (totalVertices > 65536) {
  30179. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  30180. return null;
  30181. }
  30182. }
  30183. }
  30184. }
  30185. // Merge
  30186. var vertexData = null;
  30187. var otherVertexData;
  30188. var indiceArray = new Array();
  30189. var source = null;
  30190. for (index = 0; index < meshes.length; index++) {
  30191. if (meshes[index]) {
  30192. meshes[index].computeWorldMatrix(true);
  30193. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  30194. otherVertexData.transform(meshes[index].getWorldMatrix());
  30195. if (vertexData) {
  30196. vertexData.merge(otherVertexData);
  30197. }
  30198. else {
  30199. vertexData = otherVertexData;
  30200. source = meshes[index];
  30201. }
  30202. if (subdivideWithSubMeshes) {
  30203. indiceArray.push(meshes[index].getTotalIndices());
  30204. }
  30205. }
  30206. }
  30207. source = source;
  30208. if (!meshSubclass) {
  30209. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  30210. }
  30211. vertexData.applyToMesh(meshSubclass);
  30212. // Setting properties
  30213. meshSubclass.material = source.material;
  30214. meshSubclass.checkCollisions = source.checkCollisions;
  30215. // Cleaning
  30216. if (disposeSource) {
  30217. for (index = 0; index < meshes.length; index++) {
  30218. if (meshes[index]) {
  30219. meshes[index].dispose();
  30220. }
  30221. }
  30222. }
  30223. // Subdivide
  30224. if (subdivideWithSubMeshes) {
  30225. //-- Suppresions du submesh global
  30226. meshSubclass.releaseSubMeshes();
  30227. index = 0;
  30228. var offset = 0;
  30229. //-- aplique la subdivision en fonction du tableau d'indices
  30230. while (index < indiceArray.length) {
  30231. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  30232. offset += indiceArray[index];
  30233. index++;
  30234. }
  30235. }
  30236. return meshSubclass;
  30237. };
  30238. // Consts
  30239. Mesh._FRONTSIDE = 0;
  30240. Mesh._BACKSIDE = 1;
  30241. Mesh._DOUBLESIDE = 2;
  30242. Mesh._DEFAULTSIDE = 0;
  30243. Mesh._NO_CAP = 0;
  30244. Mesh._CAP_START = 1;
  30245. Mesh._CAP_END = 2;
  30246. Mesh._CAP_ALL = 3;
  30247. return Mesh;
  30248. }(BABYLON.AbstractMesh));
  30249. BABYLON.Mesh = Mesh;
  30250. })(BABYLON || (BABYLON = {}));
  30251. //# sourceMappingURL=babylon.mesh.js.map
  30252. var BABYLON;
  30253. (function (BABYLON) {
  30254. var BaseSubMesh = /** @class */ (function () {
  30255. function BaseSubMesh() {
  30256. }
  30257. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  30258. get: function () {
  30259. return this._materialEffect;
  30260. },
  30261. enumerable: true,
  30262. configurable: true
  30263. });
  30264. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  30265. if (defines === void 0) { defines = null; }
  30266. if (this._materialEffect === effect) {
  30267. if (!effect) {
  30268. this._materialDefines = null;
  30269. }
  30270. return;
  30271. }
  30272. this._materialDefines = defines;
  30273. this._materialEffect = effect;
  30274. };
  30275. return BaseSubMesh;
  30276. }());
  30277. BABYLON.BaseSubMesh = BaseSubMesh;
  30278. var SubMesh = /** @class */ (function (_super) {
  30279. __extends(SubMesh, _super);
  30280. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  30281. if (createBoundingBox === void 0) { createBoundingBox = true; }
  30282. var _this = _super.call(this) || this;
  30283. _this.materialIndex = materialIndex;
  30284. _this.verticesStart = verticesStart;
  30285. _this.verticesCount = verticesCount;
  30286. _this.indexStart = indexStart;
  30287. _this.indexCount = indexCount;
  30288. _this._renderId = 0;
  30289. _this._mesh = mesh;
  30290. _this._renderingMesh = renderingMesh || mesh;
  30291. mesh.subMeshes.push(_this);
  30292. _this._trianglePlanes = [];
  30293. _this._id = mesh.subMeshes.length - 1;
  30294. if (createBoundingBox) {
  30295. _this.refreshBoundingInfo();
  30296. mesh.computeWorldMatrix(true);
  30297. }
  30298. return _this;
  30299. }
  30300. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  30301. if (createBoundingBox === void 0) { createBoundingBox = true; }
  30302. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  30303. };
  30304. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  30305. get: function () {
  30306. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  30307. },
  30308. enumerable: true,
  30309. configurable: true
  30310. });
  30311. /**
  30312. * Returns the submesh BoudingInfo object.
  30313. */
  30314. SubMesh.prototype.getBoundingInfo = function () {
  30315. if (this.IsGlobal) {
  30316. return this._mesh.getBoundingInfo();
  30317. }
  30318. return this._boundingInfo;
  30319. };
  30320. /**
  30321. * Sets the submesh BoundingInfo.
  30322. * Return the SubMesh.
  30323. */
  30324. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  30325. this._boundingInfo = boundingInfo;
  30326. return this;
  30327. };
  30328. /**
  30329. * Returns the mesh of the current submesh.
  30330. */
  30331. SubMesh.prototype.getMesh = function () {
  30332. return this._mesh;
  30333. };
  30334. /**
  30335. * Returns the rendering mesh of the submesh.
  30336. */
  30337. SubMesh.prototype.getRenderingMesh = function () {
  30338. return this._renderingMesh;
  30339. };
  30340. /**
  30341. * Returns the submesh material.
  30342. */
  30343. SubMesh.prototype.getMaterial = function () {
  30344. var rootMaterial = this._renderingMesh.material;
  30345. if (rootMaterial === null || rootMaterial === undefined) {
  30346. return this._mesh.getScene().defaultMaterial;
  30347. }
  30348. else if (rootMaterial.getSubMaterial) {
  30349. var multiMaterial = rootMaterial;
  30350. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  30351. if (this._currentMaterial !== effectiveMaterial) {
  30352. this._currentMaterial = effectiveMaterial;
  30353. this._materialDefines = null;
  30354. }
  30355. return effectiveMaterial;
  30356. }
  30357. return rootMaterial;
  30358. };
  30359. // Methods
  30360. /**
  30361. * Sets a new updated BoundingInfo object to the submesh.
  30362. * Returns the SubMesh.
  30363. */
  30364. SubMesh.prototype.refreshBoundingInfo = function () {
  30365. this._lastColliderWorldVertices = null;
  30366. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  30367. return this;
  30368. }
  30369. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30370. if (!data) {
  30371. this._boundingInfo = this._mesh.getBoundingInfo();
  30372. return this;
  30373. }
  30374. var indices = this._renderingMesh.getIndices();
  30375. var extend;
  30376. //is this the only submesh?
  30377. if (this.indexStart === 0 && this.indexCount === indices.length) {
  30378. var boundingInfo = this._renderingMesh.getBoundingInfo();
  30379. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  30380. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  30381. }
  30382. else {
  30383. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  30384. }
  30385. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  30386. return this;
  30387. };
  30388. SubMesh.prototype._checkCollision = function (collider) {
  30389. var boundingInfo = this._renderingMesh.getBoundingInfo();
  30390. return boundingInfo._checkCollision(collider);
  30391. };
  30392. /**
  30393. * Updates the submesh BoundingInfo.
  30394. * Returns the Submesh.
  30395. */
  30396. SubMesh.prototype.updateBoundingInfo = function (world) {
  30397. var boundingInfo = this.getBoundingInfo();
  30398. if (!boundingInfo) {
  30399. this.refreshBoundingInfo();
  30400. boundingInfo = this.getBoundingInfo();
  30401. }
  30402. boundingInfo.update(world);
  30403. return this;
  30404. };
  30405. /**
  30406. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  30407. * Boolean returned.
  30408. */
  30409. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  30410. var boundingInfo = this.getBoundingInfo();
  30411. if (!boundingInfo) {
  30412. return false;
  30413. }
  30414. return boundingInfo.isInFrustum(frustumPlanes);
  30415. };
  30416. /**
  30417. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  30418. * Boolean returned.
  30419. */
  30420. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  30421. var boundingInfo = this.getBoundingInfo();
  30422. if (!boundingInfo) {
  30423. return false;
  30424. }
  30425. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  30426. };
  30427. /**
  30428. * Renders the submesh.
  30429. * Returns it.
  30430. */
  30431. SubMesh.prototype.render = function (enableAlphaMode) {
  30432. this._renderingMesh.render(this, enableAlphaMode);
  30433. return this;
  30434. };
  30435. /**
  30436. * Returns a new Index Buffer.
  30437. * Type returned : WebGLBuffer.
  30438. */
  30439. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  30440. if (!this._linesIndexBuffer) {
  30441. var linesIndices = [];
  30442. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  30443. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  30444. }
  30445. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  30446. this.linesIndexCount = linesIndices.length;
  30447. }
  30448. return this._linesIndexBuffer;
  30449. };
  30450. /**
  30451. * True is the passed Ray intersects the submesh bounding box.
  30452. * Boolean returned.
  30453. */
  30454. SubMesh.prototype.canIntersects = function (ray) {
  30455. var boundingInfo = this.getBoundingInfo();
  30456. if (!boundingInfo) {
  30457. return false;
  30458. }
  30459. return ray.intersectsBox(boundingInfo.boundingBox);
  30460. };
  30461. /**
  30462. * Returns an object IntersectionInfo.
  30463. */
  30464. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  30465. var intersectInfo = null;
  30466. // LineMesh first as it's also a Mesh...
  30467. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  30468. var lineMesh = this._mesh;
  30469. // Line test
  30470. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  30471. var p0 = positions[indices[index]];
  30472. var p1 = positions[indices[index + 1]];
  30473. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  30474. if (length < 0) {
  30475. continue;
  30476. }
  30477. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  30478. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  30479. if (fastCheck) {
  30480. break;
  30481. }
  30482. }
  30483. }
  30484. }
  30485. else {
  30486. // Triangles test
  30487. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  30488. var p0 = positions[indices[index]];
  30489. var p1 = positions[indices[index + 1]];
  30490. var p2 = positions[indices[index + 2]];
  30491. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  30492. if (currentIntersectInfo) {
  30493. if (currentIntersectInfo.distance < 0) {
  30494. continue;
  30495. }
  30496. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  30497. intersectInfo = currentIntersectInfo;
  30498. intersectInfo.faceId = index / 3;
  30499. if (fastCheck) {
  30500. break;
  30501. }
  30502. }
  30503. }
  30504. }
  30505. }
  30506. return intersectInfo;
  30507. };
  30508. SubMesh.prototype._rebuild = function () {
  30509. if (this._linesIndexBuffer) {
  30510. this._linesIndexBuffer = null;
  30511. }
  30512. };
  30513. // Clone
  30514. /**
  30515. * Creates a new Submesh from the passed Mesh.
  30516. */
  30517. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  30518. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  30519. if (!this.IsGlobal) {
  30520. var boundingInfo = this.getBoundingInfo();
  30521. if (!boundingInfo) {
  30522. return result;
  30523. }
  30524. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  30525. }
  30526. return result;
  30527. };
  30528. // Dispose
  30529. /**
  30530. * Disposes the Submesh.
  30531. * Returns nothing.
  30532. */
  30533. SubMesh.prototype.dispose = function () {
  30534. if (this._linesIndexBuffer) {
  30535. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  30536. this._linesIndexBuffer = null;
  30537. }
  30538. // Remove from mesh
  30539. var index = this._mesh.subMeshes.indexOf(this);
  30540. this._mesh.subMeshes.splice(index, 1);
  30541. };
  30542. // Statics
  30543. /**
  30544. * Creates a new Submesh from the passed parameters :
  30545. * - materialIndex (integer) : the index of the main mesh material.
  30546. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  30547. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  30548. * - mesh (Mesh) : the main mesh to create the submesh from.
  30549. * - renderingMesh (optional Mesh) : rendering mesh.
  30550. */
  30551. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  30552. var minVertexIndex = Number.MAX_VALUE;
  30553. var maxVertexIndex = -Number.MAX_VALUE;
  30554. renderingMesh = (renderingMesh || mesh);
  30555. var indices = renderingMesh.getIndices();
  30556. for (var index = startIndex; index < startIndex + indexCount; index++) {
  30557. var vertexIndex = indices[index];
  30558. if (vertexIndex < minVertexIndex)
  30559. minVertexIndex = vertexIndex;
  30560. if (vertexIndex > maxVertexIndex)
  30561. maxVertexIndex = vertexIndex;
  30562. }
  30563. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  30564. };
  30565. return SubMesh;
  30566. }(BaseSubMesh));
  30567. BABYLON.SubMesh = SubMesh;
  30568. })(BABYLON || (BABYLON = {}));
  30569. //# sourceMappingURL=babylon.subMesh.js.map
  30570. var __assign = (this && this.__assign) || Object.assign || function(t) {
  30571. for (var s, i = 1, n = arguments.length; i < n; i++) {
  30572. s = arguments[i];
  30573. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  30574. t[p] = s[p];
  30575. }
  30576. return t;
  30577. };
  30578. var BABYLON;
  30579. (function (BABYLON) {
  30580. /**
  30581. * Manages the defines for the Material.
  30582. */
  30583. var MaterialDefines = /** @class */ (function () {
  30584. function MaterialDefines() {
  30585. this._isDirty = true;
  30586. this._areLightsDirty = true;
  30587. this._areAttributesDirty = true;
  30588. this._areTexturesDirty = true;
  30589. this._areFresnelDirty = true;
  30590. this._areMiscDirty = true;
  30591. this._areImageProcessingDirty = true;
  30592. this._normals = false;
  30593. this._uvs = false;
  30594. this._needNormals = false;
  30595. this._needUVs = false;
  30596. }
  30597. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  30598. /**
  30599. * Specifies if the material needs to be re-calculated.
  30600. */
  30601. get: function () {
  30602. return this._isDirty;
  30603. },
  30604. enumerable: true,
  30605. configurable: true
  30606. });
  30607. /**
  30608. * Marks the material to indicate that it has been re-calculated.
  30609. */
  30610. MaterialDefines.prototype.markAsProcessed = function () {
  30611. this._isDirty = false;
  30612. this._areAttributesDirty = false;
  30613. this._areTexturesDirty = false;
  30614. this._areFresnelDirty = false;
  30615. this._areLightsDirty = false;
  30616. this._areMiscDirty = false;
  30617. this._areImageProcessingDirty = false;
  30618. };
  30619. /**
  30620. * Marks the material to indicate that it needs to be re-calculated.
  30621. */
  30622. MaterialDefines.prototype.markAsUnprocessed = function () {
  30623. this._isDirty = true;
  30624. };
  30625. /**
  30626. * Marks the material to indicate all of its defines need to be re-calculated.
  30627. */
  30628. MaterialDefines.prototype.markAllAsDirty = function () {
  30629. this._areTexturesDirty = true;
  30630. this._areAttributesDirty = true;
  30631. this._areLightsDirty = true;
  30632. this._areFresnelDirty = true;
  30633. this._areMiscDirty = true;
  30634. this._areImageProcessingDirty = true;
  30635. this._isDirty = true;
  30636. };
  30637. /**
  30638. * Marks the material to indicate that image processing needs to be re-calculated.
  30639. */
  30640. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  30641. this._areImageProcessingDirty = true;
  30642. this._isDirty = true;
  30643. };
  30644. /**
  30645. * Marks the material to indicate the lights need to be re-calculated.
  30646. */
  30647. MaterialDefines.prototype.markAsLightDirty = function () {
  30648. this._areLightsDirty = true;
  30649. this._isDirty = true;
  30650. };
  30651. /**
  30652. * Marks the attribute state as changed.
  30653. */
  30654. MaterialDefines.prototype.markAsAttributesDirty = function () {
  30655. this._areAttributesDirty = true;
  30656. this._isDirty = true;
  30657. };
  30658. /**
  30659. * Marks the texture state as changed.
  30660. */
  30661. MaterialDefines.prototype.markAsTexturesDirty = function () {
  30662. this._areTexturesDirty = true;
  30663. this._isDirty = true;
  30664. };
  30665. /**
  30666. * Marks the fresnel state as changed.
  30667. */
  30668. MaterialDefines.prototype.markAsFresnelDirty = function () {
  30669. this._areFresnelDirty = true;
  30670. this._isDirty = true;
  30671. };
  30672. /**
  30673. * Marks the misc state as changed.
  30674. */
  30675. MaterialDefines.prototype.markAsMiscDirty = function () {
  30676. this._areMiscDirty = true;
  30677. this._isDirty = true;
  30678. };
  30679. /**
  30680. * Rebuilds the material defines.
  30681. */
  30682. MaterialDefines.prototype.rebuild = function () {
  30683. if (this._keys) {
  30684. delete this._keys;
  30685. }
  30686. this._keys = [];
  30687. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  30688. var key = _a[_i];
  30689. if (key[0] === "_") {
  30690. continue;
  30691. }
  30692. this._keys.push(key);
  30693. }
  30694. };
  30695. /**
  30696. * Specifies if two material defines are equal.
  30697. * @param other - A material define instance to compare to.
  30698. * @returns - Boolean indicating if the material defines are equal (true) or not (false).
  30699. */
  30700. MaterialDefines.prototype.isEqual = function (other) {
  30701. if (this._keys.length !== other._keys.length) {
  30702. return false;
  30703. }
  30704. for (var index = 0; index < this._keys.length; index++) {
  30705. var prop = this._keys[index];
  30706. if (this[prop] !== other[prop]) {
  30707. return false;
  30708. }
  30709. }
  30710. return true;
  30711. };
  30712. /**
  30713. * Clones this instance's defines to another instance.
  30714. * @param other - material defines to clone values to.
  30715. */
  30716. MaterialDefines.prototype.cloneTo = function (other) {
  30717. if (this._keys.length !== other._keys.length) {
  30718. other._keys = this._keys.slice(0);
  30719. }
  30720. for (var index = 0; index < this._keys.length; index++) {
  30721. var prop = this._keys[index];
  30722. other[prop] = this[prop];
  30723. }
  30724. };
  30725. /**
  30726. * Resets the material define values.
  30727. */
  30728. MaterialDefines.prototype.reset = function () {
  30729. for (var index = 0; index < this._keys.length; index++) {
  30730. var prop = this._keys[index];
  30731. if (typeof (this[prop]) === "number") {
  30732. this[prop] = 0;
  30733. }
  30734. else {
  30735. this[prop] = false;
  30736. }
  30737. }
  30738. };
  30739. /**
  30740. * Converts the material define values to a string.
  30741. * @returns - String of material define information.
  30742. */
  30743. MaterialDefines.prototype.toString = function () {
  30744. var result = "";
  30745. for (var index = 0; index < this._keys.length; index++) {
  30746. var prop = this._keys[index];
  30747. var value = this[prop];
  30748. if (typeof (value) === "number") {
  30749. result += "#define " + prop + " " + this[prop] + "\n";
  30750. }
  30751. else if (value) {
  30752. result += "#define " + prop + "\n";
  30753. }
  30754. }
  30755. return result;
  30756. };
  30757. return MaterialDefines;
  30758. }());
  30759. BABYLON.MaterialDefines = MaterialDefines;
  30760. /**
  30761. * This offers the main features of a material in BJS.
  30762. */
  30763. var Material = /** @class */ (function () {
  30764. /**
  30765. * Creates a material instance.
  30766. * @param name - The name of the material.
  30767. * @param scene - The BJS scene to reference.
  30768. * @param doNotAdd - Specifies if the material should be added to the scene.
  30769. */
  30770. function Material(name, scene, doNotAdd) {
  30771. /**
  30772. * Specifies if the ready state should be checked on each call.
  30773. */
  30774. this.checkReadyOnEveryCall = false;
  30775. /**
  30776. * Specifies if the ready state should be checked once.
  30777. */
  30778. this.checkReadyOnlyOnce = false;
  30779. /**
  30780. * The state of the material.
  30781. */
  30782. this.state = "";
  30783. /**
  30784. * The alpha value of the material.
  30785. */
  30786. this._alpha = 1.0;
  30787. /**
  30788. * Specifies if back face culling is enabled.
  30789. */
  30790. this._backFaceCulling = true;
  30791. /**
  30792. * Specifies if the material should be serialized.
  30793. */
  30794. this.doNotSerialize = false;
  30795. /**
  30796. * Specifies if the effect should be stored on sub meshes.
  30797. */
  30798. this.storeEffectOnSubMeshes = false;
  30799. /**
  30800. * An event triggered when the material is disposed.
  30801. * @type {BABYLON.Observable}
  30802. */
  30803. this.onDisposeObservable = new BABYLON.Observable();
  30804. /**
  30805. * An event triggered when the material is bound.
  30806. * @type {BABYLON.Observable}
  30807. */
  30808. this.onBindObservable = new BABYLON.Observable();
  30809. /**
  30810. * An event triggered when the material is unbound.
  30811. * @type {BABYLON.Observable}
  30812. */
  30813. this.onUnBindObservable = new BABYLON.Observable();
  30814. /**
  30815. * Stores the value of the alpha mode.
  30816. */
  30817. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  30818. /**
  30819. * Stores the state of the need depth pre-pass value.
  30820. */
  30821. this._needDepthPrePass = false;
  30822. /**
  30823. * Specifies if depth writing should be disabled.
  30824. */
  30825. this.disableDepthWrite = false;
  30826. /**
  30827. * Specifies if depth writing should be forced.
  30828. */
  30829. this.forceDepthWrite = false;
  30830. /**
  30831. * Specifies if there should be a separate pass for culling.
  30832. */
  30833. this.separateCullingPass = false;
  30834. /**
  30835. * Stores the state specifing if fog should be enabled.
  30836. */
  30837. this._fogEnabled = true;
  30838. /**
  30839. * Stores the size of points.
  30840. */
  30841. this.pointSize = 1.0;
  30842. /**
  30843. * Stores the z offset value.
  30844. */
  30845. this.zOffset = 0;
  30846. /**
  30847. * Specifies if the material was previously ready.
  30848. */
  30849. this._wasPreviouslyReady = false;
  30850. /**
  30851. * Stores the fill mode state.
  30852. */
  30853. this._fillMode = Material.TriangleFillMode;
  30854. this.name = name;
  30855. this.id = name || BABYLON.Tools.RandomId();
  30856. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  30857. if (this._scene.useRightHandedSystem) {
  30858. this.sideOrientation = Material.ClockWiseSideOrientation;
  30859. }
  30860. else {
  30861. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  30862. }
  30863. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  30864. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  30865. if (!doNotAdd) {
  30866. this._scene.materials.push(this);
  30867. }
  30868. }
  30869. Object.defineProperty(Material, "TriangleFillMode", {
  30870. /**
  30871. * Returns the triangle fill mode.
  30872. */
  30873. get: function () {
  30874. return Material._TriangleFillMode;
  30875. },
  30876. enumerable: true,
  30877. configurable: true
  30878. });
  30879. Object.defineProperty(Material, "WireFrameFillMode", {
  30880. /**
  30881. * Returns the wireframe mode.
  30882. */
  30883. get: function () {
  30884. return Material._WireFrameFillMode;
  30885. },
  30886. enumerable: true,
  30887. configurable: true
  30888. });
  30889. Object.defineProperty(Material, "PointFillMode", {
  30890. /**
  30891. * Returns the point fill mode.
  30892. */
  30893. get: function () {
  30894. return Material._PointFillMode;
  30895. },
  30896. enumerable: true,
  30897. configurable: true
  30898. });
  30899. Object.defineProperty(Material, "PointListDrawMode", {
  30900. /**
  30901. * Returns the point list draw mode.
  30902. */
  30903. get: function () {
  30904. return Material._PointListDrawMode;
  30905. },
  30906. enumerable: true,
  30907. configurable: true
  30908. });
  30909. Object.defineProperty(Material, "LineListDrawMode", {
  30910. /**
  30911. * Returns the line list draw mode.
  30912. */
  30913. get: function () {
  30914. return Material._LineListDrawMode;
  30915. },
  30916. enumerable: true,
  30917. configurable: true
  30918. });
  30919. Object.defineProperty(Material, "LineLoopDrawMode", {
  30920. /**
  30921. * Returns the line loop draw mode.
  30922. */
  30923. get: function () {
  30924. return Material._LineLoopDrawMode;
  30925. },
  30926. enumerable: true,
  30927. configurable: true
  30928. });
  30929. Object.defineProperty(Material, "LineStripDrawMode", {
  30930. /**
  30931. * Returns the line strip draw mode.
  30932. */
  30933. get: function () {
  30934. return Material._LineStripDrawMode;
  30935. },
  30936. enumerable: true,
  30937. configurable: true
  30938. });
  30939. Object.defineProperty(Material, "TriangleStripDrawMode", {
  30940. /**
  30941. * Returns the triangle strip draw mode.
  30942. */
  30943. get: function () {
  30944. return Material._TriangleStripDrawMode;
  30945. },
  30946. enumerable: true,
  30947. configurable: true
  30948. });
  30949. Object.defineProperty(Material, "TriangleFanDrawMode", {
  30950. /**
  30951. * Returns the triangle fan draw mode.
  30952. */
  30953. get: function () {
  30954. return Material._TriangleFanDrawMode;
  30955. },
  30956. enumerable: true,
  30957. configurable: true
  30958. });
  30959. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  30960. /**
  30961. * Returns the clock-wise side orientation.
  30962. */
  30963. get: function () {
  30964. return Material._ClockWiseSideOrientation;
  30965. },
  30966. enumerable: true,
  30967. configurable: true
  30968. });
  30969. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  30970. /**
  30971. * Returns the counter clock-wise side orientation.
  30972. */
  30973. get: function () {
  30974. return Material._CounterClockWiseSideOrientation;
  30975. },
  30976. enumerable: true,
  30977. configurable: true
  30978. });
  30979. Object.defineProperty(Material, "TextureDirtyFlag", {
  30980. /**
  30981. * Returns the dirty texture flag value.
  30982. */
  30983. get: function () {
  30984. return Material._TextureDirtyFlag;
  30985. },
  30986. enumerable: true,
  30987. configurable: true
  30988. });
  30989. Object.defineProperty(Material, "LightDirtyFlag", {
  30990. /**
  30991. * Returns the dirty light flag value.
  30992. */
  30993. get: function () {
  30994. return Material._LightDirtyFlag;
  30995. },
  30996. enumerable: true,
  30997. configurable: true
  30998. });
  30999. Object.defineProperty(Material, "FresnelDirtyFlag", {
  31000. /**
  31001. * Returns the dirty fresnel flag value.
  31002. */
  31003. get: function () {
  31004. return Material._FresnelDirtyFlag;
  31005. },
  31006. enumerable: true,
  31007. configurable: true
  31008. });
  31009. Object.defineProperty(Material, "AttributesDirtyFlag", {
  31010. /**
  31011. * Returns the dirty attributes flag value.
  31012. */
  31013. get: function () {
  31014. return Material._AttributesDirtyFlag;
  31015. },
  31016. enumerable: true,
  31017. configurable: true
  31018. });
  31019. Object.defineProperty(Material, "MiscDirtyFlag", {
  31020. /**
  31021. * Returns the dirty misc flag value.
  31022. */
  31023. get: function () {
  31024. return Material._MiscDirtyFlag;
  31025. },
  31026. enumerable: true,
  31027. configurable: true
  31028. });
  31029. Object.defineProperty(Material.prototype, "alpha", {
  31030. /**
  31031. * Gets the alpha value of the material.
  31032. */
  31033. get: function () {
  31034. return this._alpha;
  31035. },
  31036. /**
  31037. * Sets the alpha value of the material.
  31038. */
  31039. set: function (value) {
  31040. if (this._alpha === value) {
  31041. return;
  31042. }
  31043. this._alpha = value;
  31044. this.markAsDirty(Material.MiscDirtyFlag);
  31045. },
  31046. enumerable: true,
  31047. configurable: true
  31048. });
  31049. Object.defineProperty(Material.prototype, "backFaceCulling", {
  31050. /**
  31051. * Gets the back-face culling state.
  31052. */
  31053. get: function () {
  31054. return this._backFaceCulling;
  31055. },
  31056. /**
  31057. * Sets the back-face culling state.
  31058. */
  31059. set: function (value) {
  31060. if (this._backFaceCulling === value) {
  31061. return;
  31062. }
  31063. this._backFaceCulling = value;
  31064. this.markAsDirty(Material.TextureDirtyFlag);
  31065. },
  31066. enumerable: true,
  31067. configurable: true
  31068. });
  31069. Object.defineProperty(Material.prototype, "onDispose", {
  31070. /**
  31071. * Called during a dispose event.
  31072. */
  31073. set: function (callback) {
  31074. if (this._onDisposeObserver) {
  31075. this.onDisposeObservable.remove(this._onDisposeObserver);
  31076. }
  31077. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  31078. },
  31079. enumerable: true,
  31080. configurable: true
  31081. });
  31082. Object.defineProperty(Material.prototype, "onBind", {
  31083. /**
  31084. * Called during a bind event.
  31085. */
  31086. set: function (callback) {
  31087. if (this._onBindObserver) {
  31088. this.onBindObservable.remove(this._onBindObserver);
  31089. }
  31090. this._onBindObserver = this.onBindObservable.add(callback);
  31091. },
  31092. enumerable: true,
  31093. configurable: true
  31094. });
  31095. Object.defineProperty(Material.prototype, "alphaMode", {
  31096. /**
  31097. * Gets the value of the alpha mode.
  31098. */
  31099. get: function () {
  31100. return this._alphaMode;
  31101. },
  31102. /**
  31103. * Sets the value of the alpha mode.
  31104. */
  31105. set: function (value) {
  31106. if (this._alphaMode === value) {
  31107. return;
  31108. }
  31109. this._alphaMode = value;
  31110. this.markAsDirty(Material.TextureDirtyFlag);
  31111. },
  31112. enumerable: true,
  31113. configurable: true
  31114. });
  31115. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  31116. /**
  31117. * Gets the depth pre-pass value.
  31118. */
  31119. get: function () {
  31120. return this._needDepthPrePass;
  31121. },
  31122. /**
  31123. * Sets the need depth pre-pass value.
  31124. */
  31125. set: function (value) {
  31126. if (this._needDepthPrePass === value) {
  31127. return;
  31128. }
  31129. this._needDepthPrePass = value;
  31130. if (this._needDepthPrePass) {
  31131. this.checkReadyOnEveryCall = true;
  31132. }
  31133. },
  31134. enumerable: true,
  31135. configurable: true
  31136. });
  31137. Object.defineProperty(Material.prototype, "fogEnabled", {
  31138. /**
  31139. * Gets the value of the fog enabled state.
  31140. */
  31141. get: function () {
  31142. return this._fogEnabled;
  31143. },
  31144. /**
  31145. * Sets the state for enabling fog.
  31146. */
  31147. set: function (value) {
  31148. if (this._fogEnabled === value) {
  31149. return;
  31150. }
  31151. this._fogEnabled = value;
  31152. this.markAsDirty(Material.MiscDirtyFlag);
  31153. },
  31154. enumerable: true,
  31155. configurable: true
  31156. });
  31157. Object.defineProperty(Material.prototype, "wireframe", {
  31158. /**
  31159. * Gets a value specifying if wireframe mode is enabled.
  31160. */
  31161. get: function () {
  31162. return this._fillMode === Material.WireFrameFillMode;
  31163. },
  31164. /**
  31165. * Sets the state of wireframe mode.
  31166. */
  31167. set: function (value) {
  31168. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  31169. },
  31170. enumerable: true,
  31171. configurable: true
  31172. });
  31173. Object.defineProperty(Material.prototype, "pointsCloud", {
  31174. /**
  31175. * Gets the value specifying if point clouds are enabled.
  31176. */
  31177. get: function () {
  31178. return this._fillMode === Material.PointFillMode;
  31179. },
  31180. /**
  31181. * Sets the state of point cloud mode.
  31182. */
  31183. set: function (value) {
  31184. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  31185. },
  31186. enumerable: true,
  31187. configurable: true
  31188. });
  31189. Object.defineProperty(Material.prototype, "fillMode", {
  31190. /**
  31191. * Gets the material fill mode.
  31192. */
  31193. get: function () {
  31194. return this._fillMode;
  31195. },
  31196. /**
  31197. * Sets the material fill mode.
  31198. */
  31199. set: function (value) {
  31200. if (this._fillMode === value) {
  31201. return;
  31202. }
  31203. this._fillMode = value;
  31204. this.markAsDirty(Material.MiscDirtyFlag);
  31205. },
  31206. enumerable: true,
  31207. configurable: true
  31208. });
  31209. /**
  31210. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  31211. * subclasses should override adding information pertainent to themselves.
  31212. * @returns - String with material information.
  31213. */
  31214. Material.prototype.toString = function (fullDetails) {
  31215. var ret = "Name: " + this.name;
  31216. if (fullDetails) {
  31217. }
  31218. return ret;
  31219. };
  31220. /**
  31221. * Gets the class name of the material.
  31222. * @returns - String with the class name of the material.
  31223. */
  31224. Material.prototype.getClassName = function () {
  31225. return "Material";
  31226. };
  31227. Object.defineProperty(Material.prototype, "isFrozen", {
  31228. /**
  31229. * Specifies if updates for the material been locked.
  31230. */
  31231. get: function () {
  31232. return this.checkReadyOnlyOnce;
  31233. },
  31234. enumerable: true,
  31235. configurable: true
  31236. });
  31237. /**
  31238. * Locks updates for the material.
  31239. */
  31240. Material.prototype.freeze = function () {
  31241. this.checkReadyOnlyOnce = true;
  31242. };
  31243. /**
  31244. * Unlocks updates for the material.
  31245. */
  31246. Material.prototype.unfreeze = function () {
  31247. this.checkReadyOnlyOnce = false;
  31248. };
  31249. /**
  31250. * Specifies if the material is ready to be used.
  31251. * @param mesh - BJS mesh.
  31252. * @param useInstances - Specifies if instances should be used.
  31253. * @returns - Boolean indicating if the material is ready to be used.
  31254. */
  31255. Material.prototype.isReady = function (mesh, useInstances) {
  31256. return true;
  31257. };
  31258. /**
  31259. * Specifies that the submesh is ready to be used.
  31260. * @param mesh - BJS mesh.
  31261. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  31262. * @param useInstances - Specifies that instances should be used.
  31263. * @returns - boolean indicating that the submesh is ready or not.
  31264. */
  31265. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  31266. return false;
  31267. };
  31268. /**
  31269. * Returns the material effect.
  31270. * @returns - Nullable material effect.
  31271. */
  31272. Material.prototype.getEffect = function () {
  31273. return this._effect;
  31274. };
  31275. /**
  31276. * Returns the BJS scene.
  31277. * @returns - BJS Scene.
  31278. */
  31279. Material.prototype.getScene = function () {
  31280. return this._scene;
  31281. };
  31282. /**
  31283. * Specifies if the material will require alpha blending
  31284. * @returns - Boolean specifying if alpha blending is needed.
  31285. */
  31286. Material.prototype.needAlphaBlending = function () {
  31287. return (this.alpha < 1.0);
  31288. };
  31289. /**
  31290. * Specifies if the mesh will require alpha blending.
  31291. * @param mesh - BJS mesh.
  31292. * @returns - Boolean specifying if alpha blending is needed for the mesh.
  31293. */
  31294. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  31295. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  31296. };
  31297. /**
  31298. * Specifies if this material should be rendered in alpha test mode.
  31299. * @returns - Boolean specifying if an alpha test is needed.
  31300. */
  31301. Material.prototype.needAlphaTesting = function () {
  31302. return false;
  31303. };
  31304. /**
  31305. * Gets the texture used for the alpha test.
  31306. * @returns - Nullable alpha test texture.
  31307. */
  31308. Material.prototype.getAlphaTestTexture = function () {
  31309. return null;
  31310. };
  31311. /**
  31312. * Marks the material to indicate that it needs to be re-calculated.
  31313. */
  31314. Material.prototype.markDirty = function () {
  31315. this._wasPreviouslyReady = false;
  31316. };
  31317. Material.prototype._preBind = function (effect, overrideOrientation) {
  31318. if (overrideOrientation === void 0) { overrideOrientation = null; }
  31319. var engine = this._scene.getEngine();
  31320. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  31321. var reverse = orientation === Material.ClockWiseSideOrientation;
  31322. engine.enableEffect(effect ? effect : this._effect);
  31323. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  31324. return reverse;
  31325. };
  31326. /**
  31327. * Binds the material to the mesh.
  31328. * @param world - World transformation matrix.
  31329. * @param mesh - Mesh to bind the material to.
  31330. */
  31331. Material.prototype.bind = function (world, mesh) {
  31332. };
  31333. /**
  31334. * Binds the submesh to the material.
  31335. * @param world - World transformation matrix.
  31336. * @param mesh - Mesh containing the submesh.
  31337. * @param subMesh - Submesh to bind the material to.
  31338. */
  31339. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  31340. };
  31341. /**
  31342. * Binds the world matrix to the material.
  31343. * @param world - World transformation matrix.
  31344. */
  31345. Material.prototype.bindOnlyWorldMatrix = function (world) {
  31346. };
  31347. /**
  31348. * Binds the scene's uniform buffer to the effect.
  31349. * @param effect - Effect to bind to the scene uniform buffer.
  31350. * @param sceneUbo - Scene uniform buffer.
  31351. */
  31352. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  31353. sceneUbo.bindToEffect(effect, "Scene");
  31354. };
  31355. /**
  31356. * Binds the view matrix to the effect.
  31357. * @param effect - Effect to bind the view matrix to.
  31358. */
  31359. Material.prototype.bindView = function (effect) {
  31360. if (!this._useUBO) {
  31361. effect.setMatrix("view", this.getScene().getViewMatrix());
  31362. }
  31363. else {
  31364. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  31365. }
  31366. };
  31367. /**
  31368. * Binds the view projection matrix to the effect.
  31369. * @param effect - Effect to bind the view projection matrix to.
  31370. */
  31371. Material.prototype.bindViewProjection = function (effect) {
  31372. if (!this._useUBO) {
  31373. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  31374. }
  31375. else {
  31376. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  31377. }
  31378. };
  31379. /**
  31380. * Specifies if material alpha testing should be turned on for the mesh.
  31381. * @param mesh - BJS mesh.
  31382. */
  31383. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  31384. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  31385. };
  31386. /**
  31387. * Processes to execute after binding the material to a mesh.
  31388. * @param mesh - BJS mesh.
  31389. */
  31390. Material.prototype._afterBind = function (mesh) {
  31391. this._scene._cachedMaterial = this;
  31392. if (mesh) {
  31393. this._scene._cachedVisibility = mesh.visibility;
  31394. }
  31395. else {
  31396. this._scene._cachedVisibility = 1;
  31397. }
  31398. if (mesh) {
  31399. this.onBindObservable.notifyObservers(mesh);
  31400. }
  31401. if (this.disableDepthWrite) {
  31402. var engine = this._scene.getEngine();
  31403. this._cachedDepthWriteState = engine.getDepthWrite();
  31404. engine.setDepthWrite(false);
  31405. }
  31406. };
  31407. /**
  31408. * Unbinds the material from the mesh.
  31409. */
  31410. Material.prototype.unbind = function () {
  31411. this.onUnBindObservable.notifyObservers(this);
  31412. if (this.disableDepthWrite) {
  31413. var engine = this._scene.getEngine();
  31414. engine.setDepthWrite(this._cachedDepthWriteState);
  31415. }
  31416. };
  31417. /**
  31418. * Gets the active textures from the material.
  31419. * @returns - Array of textures.
  31420. */
  31421. Material.prototype.getActiveTextures = function () {
  31422. return [];
  31423. };
  31424. /**
  31425. * Specifies if the material uses a texture.
  31426. * @param texture - Texture to check against the material.
  31427. * @returns - Boolean specifying if the material uses the texture.
  31428. */
  31429. Material.prototype.hasTexture = function (texture) {
  31430. return false;
  31431. };
  31432. /**
  31433. * Makes a duplicate of the material, and gives it a new name.
  31434. * @param name - Name to call the duplicated material.
  31435. * @returns - Nullable cloned material
  31436. */
  31437. Material.prototype.clone = function (name) {
  31438. return null;
  31439. };
  31440. /**
  31441. * Gets the meshes bound to the material.
  31442. * @returns - Array of meshes bound to the material.
  31443. */
  31444. Material.prototype.getBindedMeshes = function () {
  31445. var result = new Array();
  31446. for (var index = 0; index < this._scene.meshes.length; index++) {
  31447. var mesh = this._scene.meshes[index];
  31448. if (mesh.material === this) {
  31449. result.push(mesh);
  31450. }
  31451. }
  31452. return result;
  31453. };
  31454. /**
  31455. * Force shader compilation
  31456. * @param mesh - BJS mesh.
  31457. * @param onCompiled - function to execute once the material is compiled.
  31458. * @param options - options to pass to this function.
  31459. */
  31460. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  31461. var _this = this;
  31462. var localOptions = __assign({ clipPlane: false }, options);
  31463. var subMesh = new BABYLON.BaseSubMesh();
  31464. var scene = this.getScene();
  31465. var checkReady = function () {
  31466. if (!_this._scene || !_this._scene.getEngine()) {
  31467. return;
  31468. }
  31469. if (subMesh._materialDefines) {
  31470. subMesh._materialDefines._renderId = -1;
  31471. }
  31472. var clipPlaneState = scene.clipPlane;
  31473. if (localOptions.clipPlane) {
  31474. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  31475. }
  31476. if (_this.storeEffectOnSubMeshes) {
  31477. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  31478. if (onCompiled) {
  31479. onCompiled(_this);
  31480. }
  31481. }
  31482. else {
  31483. setTimeout(checkReady, 16);
  31484. }
  31485. }
  31486. else {
  31487. if (_this.isReady(mesh)) {
  31488. if (onCompiled) {
  31489. onCompiled(_this);
  31490. }
  31491. }
  31492. else {
  31493. setTimeout(checkReady, 16);
  31494. }
  31495. }
  31496. if (localOptions.clipPlane) {
  31497. scene.clipPlane = clipPlaneState;
  31498. }
  31499. };
  31500. checkReady();
  31501. };
  31502. /**
  31503. * Force shader compilation.
  31504. * @param mesh The mesh that will use this material
  31505. * @param options Additional options for compiling the shaders
  31506. * @returns A promise that resolves when the compilation completes
  31507. */
  31508. Material.prototype.forceCompilationAsync = function (mesh, options) {
  31509. var _this = this;
  31510. return new Promise(function (resolve) {
  31511. _this.forceCompilation(mesh, function () {
  31512. resolve();
  31513. }, options);
  31514. });
  31515. };
  31516. /**
  31517. * Marks a define in the material to indicate that it needs to be re-computed.
  31518. * @param flag - Material define flag.
  31519. */
  31520. Material.prototype.markAsDirty = function (flag) {
  31521. if (flag & Material.TextureDirtyFlag) {
  31522. this._markAllSubMeshesAsTexturesDirty();
  31523. }
  31524. if (flag & Material.LightDirtyFlag) {
  31525. this._markAllSubMeshesAsLightsDirty();
  31526. }
  31527. if (flag & Material.FresnelDirtyFlag) {
  31528. this._markAllSubMeshesAsFresnelDirty();
  31529. }
  31530. if (flag & Material.AttributesDirtyFlag) {
  31531. this._markAllSubMeshesAsAttributesDirty();
  31532. }
  31533. if (flag & Material.MiscDirtyFlag) {
  31534. this._markAllSubMeshesAsMiscDirty();
  31535. }
  31536. this.getScene().resetCachedMaterial();
  31537. };
  31538. /**
  31539. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated.
  31540. * @param func - function which checks material defines against the submeshes.
  31541. */
  31542. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  31543. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  31544. var mesh = _a[_i];
  31545. if (!mesh.subMeshes) {
  31546. continue;
  31547. }
  31548. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  31549. var subMesh = _c[_b];
  31550. if (subMesh.getMaterial() !== this) {
  31551. continue;
  31552. }
  31553. if (!subMesh._materialDefines) {
  31554. continue;
  31555. }
  31556. func(subMesh._materialDefines);
  31557. }
  31558. }
  31559. };
  31560. /**
  31561. * Indicates that image processing needs to be re-calculated for all submeshes.
  31562. */
  31563. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  31564. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  31565. };
  31566. /**
  31567. * Indicates that textures need to be re-calculated for all submeshes.
  31568. */
  31569. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  31570. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  31571. };
  31572. /**
  31573. * Indicates that fresnel needs to be re-calculated for all submeshes.
  31574. */
  31575. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  31576. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  31577. };
  31578. /**
  31579. * Indicates that fresnel and misc need to be re-calculated for all submeshes.
  31580. */
  31581. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  31582. this._markAllSubMeshesAsDirty(function (defines) {
  31583. defines.markAsFresnelDirty();
  31584. defines.markAsMiscDirty();
  31585. });
  31586. };
  31587. /**
  31588. * Indicates that lights need to be re-calculated for all submeshes.
  31589. */
  31590. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  31591. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  31592. };
  31593. /**
  31594. * Indicates that attributes need to be re-calculated for all submeshes.
  31595. */
  31596. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  31597. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  31598. };
  31599. /**
  31600. * Indicates that misc needs to be re-calculated for all submeshes.
  31601. */
  31602. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  31603. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  31604. };
  31605. /**
  31606. * Indicates that textures and misc need to be re-calculated for all submeshes.
  31607. */
  31608. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  31609. this._markAllSubMeshesAsDirty(function (defines) {
  31610. defines.markAsTexturesDirty();
  31611. defines.markAsMiscDirty();
  31612. });
  31613. };
  31614. /**
  31615. * Disposes the material.
  31616. * @param forceDisposeEffect - Specifies if effects should be force disposed.
  31617. * @param forceDisposeTextures - Specifies if textures should be force disposed.
  31618. */
  31619. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  31620. // Animations
  31621. this.getScene().stopAnimation(this);
  31622. // Remove from scene
  31623. var index = this._scene.materials.indexOf(this);
  31624. if (index >= 0) {
  31625. this._scene.materials.splice(index, 1);
  31626. }
  31627. // Remove from meshes
  31628. for (index = 0; index < this._scene.meshes.length; index++) {
  31629. var mesh = this._scene.meshes[index];
  31630. if (mesh.material === this) {
  31631. mesh.material = null;
  31632. if (mesh.geometry) {
  31633. var geometry = (mesh.geometry);
  31634. if (this.storeEffectOnSubMeshes) {
  31635. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  31636. var subMesh = _a[_i];
  31637. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  31638. if (forceDisposeEffect && subMesh._materialEffect) {
  31639. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  31640. }
  31641. }
  31642. }
  31643. else {
  31644. geometry._releaseVertexArrayObject(this._effect);
  31645. }
  31646. }
  31647. }
  31648. }
  31649. this._uniformBuffer.dispose();
  31650. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  31651. if (forceDisposeEffect && this._effect) {
  31652. if (!this.storeEffectOnSubMeshes) {
  31653. this._scene.getEngine()._releaseEffect(this._effect);
  31654. }
  31655. this._effect = null;
  31656. }
  31657. // Callback
  31658. this.onDisposeObservable.notifyObservers(this);
  31659. this.onDisposeObservable.clear();
  31660. this.onBindObservable.clear();
  31661. this.onUnBindObservable.clear();
  31662. };
  31663. /**
  31664. * Serializes this material.
  31665. * @returns - serialized material object.
  31666. */
  31667. Material.prototype.serialize = function () {
  31668. return BABYLON.SerializationHelper.Serialize(this);
  31669. };
  31670. /**
  31671. * Creates a MultiMaterial from parse MultiMaterial data.
  31672. * @param parsedMultiMaterial - Parsed MultiMaterial data.
  31673. * @param scene - BJS scene.
  31674. * @returns - MultiMaterial.
  31675. */
  31676. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  31677. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  31678. multiMaterial.id = parsedMultiMaterial.id;
  31679. if (BABYLON.Tags) {
  31680. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  31681. }
  31682. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  31683. var subMatId = parsedMultiMaterial.materials[matIndex];
  31684. if (subMatId) {
  31685. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  31686. }
  31687. else {
  31688. multiMaterial.subMaterials.push(null);
  31689. }
  31690. }
  31691. return multiMaterial;
  31692. };
  31693. /**
  31694. * Creates a material from parsed material data.
  31695. * @param parsedMaterial - Parsed material data.
  31696. * @param scene - BJS scene.
  31697. * @param rootUrl - Root URL containing the material information.
  31698. * @returns - Parsed material.
  31699. */
  31700. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  31701. if (!parsedMaterial.customType) {
  31702. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  31703. }
  31704. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  31705. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  31706. if (!BABYLON.LegacyPBRMaterial) {
  31707. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  31708. return;
  31709. }
  31710. }
  31711. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  31712. return materialType.Parse(parsedMaterial, scene, rootUrl);
  31713. ;
  31714. };
  31715. // Triangle views
  31716. Material._TriangleFillMode = 0;
  31717. Material._WireFrameFillMode = 1;
  31718. Material._PointFillMode = 2;
  31719. // Draw modes
  31720. Material._PointListDrawMode = 3;
  31721. Material._LineListDrawMode = 4;
  31722. Material._LineLoopDrawMode = 5;
  31723. Material._LineStripDrawMode = 6;
  31724. Material._TriangleStripDrawMode = 7;
  31725. Material._TriangleFanDrawMode = 8;
  31726. /**
  31727. * Stores the clock-wise side orientation.
  31728. */
  31729. Material._ClockWiseSideOrientation = 0;
  31730. /**
  31731. * Stores the counter clock-wise side orientation.
  31732. */
  31733. Material._CounterClockWiseSideOrientation = 1;
  31734. /**
  31735. * The dirty texture flag value.
  31736. */
  31737. Material._TextureDirtyFlag = 1;
  31738. /**
  31739. * The dirty light flag value.
  31740. */
  31741. Material._LightDirtyFlag = 2;
  31742. /**
  31743. * The dirty fresnel flag value.
  31744. */
  31745. Material._FresnelDirtyFlag = 4;
  31746. /**
  31747. * The dirty attribute flag value.
  31748. */
  31749. Material._AttributesDirtyFlag = 8;
  31750. /**
  31751. * The dirty misc flag value.
  31752. */
  31753. Material._MiscDirtyFlag = 16;
  31754. __decorate([
  31755. BABYLON.serialize()
  31756. ], Material.prototype, "id", void 0);
  31757. __decorate([
  31758. BABYLON.serialize()
  31759. ], Material.prototype, "name", void 0);
  31760. __decorate([
  31761. BABYLON.serialize()
  31762. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  31763. __decorate([
  31764. BABYLON.serialize()
  31765. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  31766. __decorate([
  31767. BABYLON.serialize()
  31768. ], Material.prototype, "state", void 0);
  31769. __decorate([
  31770. BABYLON.serialize("alpha")
  31771. ], Material.prototype, "_alpha", void 0);
  31772. __decorate([
  31773. BABYLON.serialize("backFaceCulling")
  31774. ], Material.prototype, "_backFaceCulling", void 0);
  31775. __decorate([
  31776. BABYLON.serialize()
  31777. ], Material.prototype, "sideOrientation", void 0);
  31778. __decorate([
  31779. BABYLON.serialize("alphaMode")
  31780. ], Material.prototype, "_alphaMode", void 0);
  31781. __decorate([
  31782. BABYLON.serialize()
  31783. ], Material.prototype, "_needDepthPrePass", void 0);
  31784. __decorate([
  31785. BABYLON.serialize()
  31786. ], Material.prototype, "disableDepthWrite", void 0);
  31787. __decorate([
  31788. BABYLON.serialize()
  31789. ], Material.prototype, "forceDepthWrite", void 0);
  31790. __decorate([
  31791. BABYLON.serialize()
  31792. ], Material.prototype, "separateCullingPass", void 0);
  31793. __decorate([
  31794. BABYLON.serialize("fogEnabled")
  31795. ], Material.prototype, "_fogEnabled", void 0);
  31796. __decorate([
  31797. BABYLON.serialize()
  31798. ], Material.prototype, "pointSize", void 0);
  31799. __decorate([
  31800. BABYLON.serialize()
  31801. ], Material.prototype, "zOffset", void 0);
  31802. __decorate([
  31803. BABYLON.serialize()
  31804. ], Material.prototype, "wireframe", null);
  31805. __decorate([
  31806. BABYLON.serialize()
  31807. ], Material.prototype, "pointsCloud", null);
  31808. __decorate([
  31809. BABYLON.serialize()
  31810. ], Material.prototype, "fillMode", null);
  31811. return Material;
  31812. }());
  31813. BABYLON.Material = Material;
  31814. })(BABYLON || (BABYLON = {}));
  31815. //# sourceMappingURL=babylon.material.js.map
  31816. var BABYLON;
  31817. (function (BABYLON) {
  31818. var UniformBuffer = /** @class */ (function () {
  31819. /**
  31820. * Uniform buffer objects.
  31821. *
  31822. * Handles blocks of uniform on the GPU.
  31823. *
  31824. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  31825. *
  31826. * For more information, please refer to :
  31827. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  31828. */
  31829. function UniformBuffer(engine, data, dynamic) {
  31830. this._engine = engine;
  31831. this._noUBO = !engine.supportsUniformBuffers;
  31832. this._dynamic = dynamic;
  31833. this._data = data || [];
  31834. this._uniformLocations = {};
  31835. this._uniformSizes = {};
  31836. this._uniformLocationPointer = 0;
  31837. this._needSync = false;
  31838. if (this._noUBO) {
  31839. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  31840. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  31841. this.updateFloat = this._updateFloatForEffect;
  31842. this.updateFloat2 = this._updateFloat2ForEffect;
  31843. this.updateFloat3 = this._updateFloat3ForEffect;
  31844. this.updateFloat4 = this._updateFloat4ForEffect;
  31845. this.updateMatrix = this._updateMatrixForEffect;
  31846. this.updateVector3 = this._updateVector3ForEffect;
  31847. this.updateVector4 = this._updateVector4ForEffect;
  31848. this.updateColor3 = this._updateColor3ForEffect;
  31849. this.updateColor4 = this._updateColor4ForEffect;
  31850. }
  31851. else {
  31852. this._engine._uniformBuffers.push(this);
  31853. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  31854. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  31855. this.updateFloat = this._updateFloatForUniform;
  31856. this.updateFloat2 = this._updateFloat2ForUniform;
  31857. this.updateFloat3 = this._updateFloat3ForUniform;
  31858. this.updateFloat4 = this._updateFloat4ForUniform;
  31859. this.updateMatrix = this._updateMatrixForUniform;
  31860. this.updateVector3 = this._updateVector3ForUniform;
  31861. this.updateVector4 = this._updateVector4ForUniform;
  31862. this.updateColor3 = this._updateColor3ForUniform;
  31863. this.updateColor4 = this._updateColor4ForUniform;
  31864. }
  31865. }
  31866. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  31867. // Properties
  31868. /**
  31869. * Indicates if the buffer is using the WebGL2 UBO implementation,
  31870. * or just falling back on setUniformXXX calls.
  31871. */
  31872. get: function () {
  31873. return !this._noUBO;
  31874. },
  31875. enumerable: true,
  31876. configurable: true
  31877. });
  31878. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  31879. /**
  31880. * Indicates if the WebGL underlying uniform buffer is in sync
  31881. * with the javascript cache data.
  31882. */
  31883. get: function () {
  31884. return !this._needSync;
  31885. },
  31886. enumerable: true,
  31887. configurable: true
  31888. });
  31889. /**
  31890. * Indicates if the WebGL underlying uniform buffer is dynamic.
  31891. * Also, a dynamic UniformBuffer will disable cache verification and always
  31892. * update the underlying WebGL uniform buffer to the GPU.
  31893. */
  31894. UniformBuffer.prototype.isDynamic = function () {
  31895. return this._dynamic !== undefined;
  31896. };
  31897. /**
  31898. * The data cache on JS side.
  31899. */
  31900. UniformBuffer.prototype.getData = function () {
  31901. return this._bufferData;
  31902. };
  31903. /**
  31904. * The underlying WebGL Uniform buffer.
  31905. */
  31906. UniformBuffer.prototype.getBuffer = function () {
  31907. return this._buffer;
  31908. };
  31909. /**
  31910. * std140 layout specifies how to align data within an UBO structure.
  31911. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  31912. * for specs.
  31913. */
  31914. UniformBuffer.prototype._fillAlignment = function (size) {
  31915. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  31916. // and 4x4 matrices
  31917. // TODO : change if other types are used
  31918. var alignment;
  31919. if (size <= 2) {
  31920. alignment = size;
  31921. }
  31922. else {
  31923. alignment = 4;
  31924. }
  31925. if ((this._uniformLocationPointer % alignment) !== 0) {
  31926. var oldPointer = this._uniformLocationPointer;
  31927. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  31928. var diff = this._uniformLocationPointer - oldPointer;
  31929. for (var i = 0; i < diff; i++) {
  31930. this._data.push(0);
  31931. }
  31932. }
  31933. };
  31934. /**
  31935. * Adds an uniform in the buffer.
  31936. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  31937. * for the layout to be correct !
  31938. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31939. * @param {number|number[]} size Data size, or data directly.
  31940. */
  31941. UniformBuffer.prototype.addUniform = function (name, size) {
  31942. if (this._noUBO) {
  31943. return;
  31944. }
  31945. if (this._uniformLocations[name] !== undefined) {
  31946. // Already existing uniform
  31947. return;
  31948. }
  31949. // This function must be called in the order of the shader layout !
  31950. // size can be the size of the uniform, or data directly
  31951. var data;
  31952. if (size instanceof Array) {
  31953. data = size;
  31954. size = data.length;
  31955. }
  31956. else {
  31957. size = size;
  31958. data = [];
  31959. // Fill with zeros
  31960. for (var i = 0; i < size; i++) {
  31961. data.push(0);
  31962. }
  31963. }
  31964. this._fillAlignment(size);
  31965. this._uniformSizes[name] = size;
  31966. this._uniformLocations[name] = this._uniformLocationPointer;
  31967. this._uniformLocationPointer += size;
  31968. for (var i = 0; i < size; i++) {
  31969. this._data.push(data[i]);
  31970. }
  31971. this._needSync = true;
  31972. };
  31973. /**
  31974. * Wrapper for addUniform.
  31975. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31976. * @param {Matrix} mat A 4x4 matrix.
  31977. */
  31978. UniformBuffer.prototype.addMatrix = function (name, mat) {
  31979. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  31980. };
  31981. /**
  31982. * Wrapper for addUniform.
  31983. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31984. * @param {number} x
  31985. * @param {number} y
  31986. */
  31987. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  31988. var temp = [x, y];
  31989. this.addUniform(name, temp);
  31990. };
  31991. /**
  31992. * Wrapper for addUniform.
  31993. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31994. * @param {number} x
  31995. * @param {number} y
  31996. * @param {number} z
  31997. */
  31998. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  31999. var temp = [x, y, z];
  32000. this.addUniform(name, temp);
  32001. };
  32002. /**
  32003. * Wrapper for addUniform.
  32004. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32005. * @param {Color3} color
  32006. */
  32007. UniformBuffer.prototype.addColor3 = function (name, color) {
  32008. var temp = new Array();
  32009. color.toArray(temp);
  32010. this.addUniform(name, temp);
  32011. };
  32012. /**
  32013. * Wrapper for addUniform.
  32014. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32015. * @param {Color3} color
  32016. * @param {number} alpha
  32017. */
  32018. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  32019. var temp = new Array();
  32020. color.toArray(temp);
  32021. temp.push(alpha);
  32022. this.addUniform(name, temp);
  32023. };
  32024. /**
  32025. * Wrapper for addUniform.
  32026. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32027. * @param {Vector3} vector
  32028. */
  32029. UniformBuffer.prototype.addVector3 = function (name, vector) {
  32030. var temp = new Array();
  32031. vector.toArray(temp);
  32032. this.addUniform(name, temp);
  32033. };
  32034. /**
  32035. * Wrapper for addUniform.
  32036. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32037. */
  32038. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  32039. this.addUniform(name, 12);
  32040. };
  32041. /**
  32042. * Wrapper for addUniform.
  32043. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32044. */
  32045. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  32046. this.addUniform(name, 8);
  32047. };
  32048. /**
  32049. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  32050. */
  32051. UniformBuffer.prototype.create = function () {
  32052. if (this._noUBO) {
  32053. return;
  32054. }
  32055. if (this._buffer) {
  32056. return; // nothing to do
  32057. }
  32058. // See spec, alignment must be filled as a vec4
  32059. this._fillAlignment(4);
  32060. this._bufferData = new Float32Array(this._data);
  32061. this._rebuild();
  32062. this._needSync = true;
  32063. };
  32064. UniformBuffer.prototype._rebuild = function () {
  32065. if (this._noUBO) {
  32066. return;
  32067. }
  32068. if (this._dynamic) {
  32069. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  32070. }
  32071. else {
  32072. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  32073. }
  32074. };
  32075. /**
  32076. * Updates the WebGL Uniform Buffer on the GPU.
  32077. * If the `dynamic` flag is set to true, no cache comparison is done.
  32078. * Otherwise, the buffer will be updated only if the cache differs.
  32079. */
  32080. UniformBuffer.prototype.update = function () {
  32081. if (!this._buffer) {
  32082. this.create();
  32083. return;
  32084. }
  32085. if (!this._dynamic && !this._needSync) {
  32086. return;
  32087. }
  32088. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  32089. this._needSync = false;
  32090. };
  32091. /**
  32092. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  32093. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  32094. * @param {number[]|Float32Array} data Flattened data
  32095. * @param {number} size Size of the data.
  32096. */
  32097. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  32098. var location = this._uniformLocations[uniformName];
  32099. if (location === undefined) {
  32100. if (this._buffer) {
  32101. // Cannot add an uniform if the buffer is already created
  32102. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  32103. return;
  32104. }
  32105. this.addUniform(uniformName, size);
  32106. location = this._uniformLocations[uniformName];
  32107. }
  32108. if (!this._buffer) {
  32109. this.create();
  32110. }
  32111. if (!this._dynamic) {
  32112. // Cache for static uniform buffers
  32113. var changed = false;
  32114. for (var i = 0; i < size; i++) {
  32115. if (this._bufferData[location + i] !== data[i]) {
  32116. changed = true;
  32117. this._bufferData[location + i] = data[i];
  32118. }
  32119. }
  32120. this._needSync = this._needSync || changed;
  32121. }
  32122. else {
  32123. // No cache for dynamic
  32124. for (var i = 0; i < size; i++) {
  32125. this._bufferData[location + i] = data[i];
  32126. }
  32127. }
  32128. };
  32129. // Update methods
  32130. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  32131. // To match std140, matrix must be realigned
  32132. for (var i = 0; i < 3; i++) {
  32133. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  32134. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  32135. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  32136. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  32137. }
  32138. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  32139. };
  32140. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  32141. this._currentEffect.setMatrix3x3(name, matrix);
  32142. };
  32143. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  32144. this._currentEffect.setMatrix2x2(name, matrix);
  32145. };
  32146. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  32147. // To match std140, matrix must be realigned
  32148. for (var i = 0; i < 2; i++) {
  32149. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  32150. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  32151. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  32152. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  32153. }
  32154. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  32155. };
  32156. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  32157. this._currentEffect.setFloat(name, x);
  32158. };
  32159. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  32160. UniformBuffer._tempBuffer[0] = x;
  32161. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  32162. };
  32163. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  32164. if (suffix === void 0) { suffix = ""; }
  32165. this._currentEffect.setFloat2(name + suffix, x, y);
  32166. };
  32167. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  32168. if (suffix === void 0) { suffix = ""; }
  32169. UniformBuffer._tempBuffer[0] = x;
  32170. UniformBuffer._tempBuffer[1] = y;
  32171. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  32172. };
  32173. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  32174. if (suffix === void 0) { suffix = ""; }
  32175. this._currentEffect.setFloat3(name + suffix, x, y, z);
  32176. };
  32177. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  32178. if (suffix === void 0) { suffix = ""; }
  32179. UniformBuffer._tempBuffer[0] = x;
  32180. UniformBuffer._tempBuffer[1] = y;
  32181. UniformBuffer._tempBuffer[2] = z;
  32182. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  32183. };
  32184. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  32185. if (suffix === void 0) { suffix = ""; }
  32186. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  32187. };
  32188. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  32189. if (suffix === void 0) { suffix = ""; }
  32190. UniformBuffer._tempBuffer[0] = x;
  32191. UniformBuffer._tempBuffer[1] = y;
  32192. UniformBuffer._tempBuffer[2] = z;
  32193. UniformBuffer._tempBuffer[3] = w;
  32194. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  32195. };
  32196. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  32197. this._currentEffect.setMatrix(name, mat);
  32198. };
  32199. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  32200. this.updateUniform(name, mat.toArray(), 16);
  32201. };
  32202. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  32203. this._currentEffect.setVector3(name, vector);
  32204. };
  32205. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  32206. vector.toArray(UniformBuffer._tempBuffer);
  32207. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  32208. };
  32209. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  32210. this._currentEffect.setVector4(name, vector);
  32211. };
  32212. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  32213. vector.toArray(UniformBuffer._tempBuffer);
  32214. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  32215. };
  32216. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  32217. if (suffix === void 0) { suffix = ""; }
  32218. this._currentEffect.setColor3(name + suffix, color);
  32219. };
  32220. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  32221. if (suffix === void 0) { suffix = ""; }
  32222. color.toArray(UniformBuffer._tempBuffer);
  32223. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  32224. };
  32225. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  32226. if (suffix === void 0) { suffix = ""; }
  32227. this._currentEffect.setColor4(name + suffix, color, alpha);
  32228. };
  32229. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  32230. if (suffix === void 0) { suffix = ""; }
  32231. color.toArray(UniformBuffer._tempBuffer);
  32232. UniformBuffer._tempBuffer[3] = alpha;
  32233. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  32234. };
  32235. /**
  32236. * Sets a sampler uniform on the effect.
  32237. * @param {string} name Name of the sampler.
  32238. * @param {Texture} texture
  32239. */
  32240. UniformBuffer.prototype.setTexture = function (name, texture) {
  32241. this._currentEffect.setTexture(name, texture);
  32242. };
  32243. /**
  32244. * Directly updates the value of the uniform in the cache AND on the GPU.
  32245. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  32246. * @param {number[]|Float32Array} data Flattened data
  32247. */
  32248. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  32249. this.updateUniform(uniformName, data, data.length);
  32250. this.update();
  32251. };
  32252. /**
  32253. * Binds this uniform buffer to an effect.
  32254. * @param {Effect} effect
  32255. * @param {string} name Name of the uniform block in the shader.
  32256. */
  32257. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  32258. this._currentEffect = effect;
  32259. if (this._noUBO || !this._buffer) {
  32260. return;
  32261. }
  32262. effect.bindUniformBuffer(this._buffer, name);
  32263. };
  32264. /**
  32265. * Disposes the uniform buffer.
  32266. */
  32267. UniformBuffer.prototype.dispose = function () {
  32268. if (this._noUBO) {
  32269. return;
  32270. }
  32271. var index = this._engine._uniformBuffers.indexOf(this);
  32272. if (index !== -1) {
  32273. this._engine._uniformBuffers.splice(index, 1);
  32274. }
  32275. if (!this._buffer) {
  32276. return;
  32277. }
  32278. if (this._engine._releaseBuffer(this._buffer)) {
  32279. this._buffer = null;
  32280. }
  32281. };
  32282. // Pool for avoiding memory leaks
  32283. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  32284. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  32285. return UniformBuffer;
  32286. }());
  32287. BABYLON.UniformBuffer = UniformBuffer;
  32288. })(BABYLON || (BABYLON = {}));
  32289. //# sourceMappingURL=babylon.uniformBuffer.js.map
  32290. var BABYLON;
  32291. (function (BABYLON) {
  32292. var VertexData = /** @class */ (function () {
  32293. function VertexData() {
  32294. }
  32295. VertexData.prototype.set = function (data, kind) {
  32296. switch (kind) {
  32297. case BABYLON.VertexBuffer.PositionKind:
  32298. this.positions = data;
  32299. break;
  32300. case BABYLON.VertexBuffer.NormalKind:
  32301. this.normals = data;
  32302. break;
  32303. case BABYLON.VertexBuffer.TangentKind:
  32304. this.tangents = data;
  32305. break;
  32306. case BABYLON.VertexBuffer.UVKind:
  32307. this.uvs = data;
  32308. break;
  32309. case BABYLON.VertexBuffer.UV2Kind:
  32310. this.uvs2 = data;
  32311. break;
  32312. case BABYLON.VertexBuffer.UV3Kind:
  32313. this.uvs3 = data;
  32314. break;
  32315. case BABYLON.VertexBuffer.UV4Kind:
  32316. this.uvs4 = data;
  32317. break;
  32318. case BABYLON.VertexBuffer.UV5Kind:
  32319. this.uvs5 = data;
  32320. break;
  32321. case BABYLON.VertexBuffer.UV6Kind:
  32322. this.uvs6 = data;
  32323. break;
  32324. case BABYLON.VertexBuffer.ColorKind:
  32325. this.colors = data;
  32326. break;
  32327. case BABYLON.VertexBuffer.MatricesIndicesKind:
  32328. this.matricesIndices = data;
  32329. break;
  32330. case BABYLON.VertexBuffer.MatricesWeightsKind:
  32331. this.matricesWeights = data;
  32332. break;
  32333. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  32334. this.matricesIndicesExtra = data;
  32335. break;
  32336. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  32337. this.matricesWeightsExtra = data;
  32338. break;
  32339. }
  32340. };
  32341. /**
  32342. * Associates the vertexData to the passed Mesh.
  32343. * Sets it as updatable or not (default `false`).
  32344. * Returns the VertexData.
  32345. */
  32346. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  32347. this._applyTo(mesh, updatable);
  32348. return this;
  32349. };
  32350. /**
  32351. * Associates the vertexData to the passed Geometry.
  32352. * Sets it as updatable or not (default `false`).
  32353. * Returns the VertexData.
  32354. */
  32355. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  32356. this._applyTo(geometry, updatable);
  32357. return this;
  32358. };
  32359. /**
  32360. * Updates the associated mesh.
  32361. * Returns the VertexData.
  32362. */
  32363. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  32364. this._update(mesh);
  32365. return this;
  32366. };
  32367. /**
  32368. * Updates the associated geometry.
  32369. * Returns the VertexData.
  32370. */
  32371. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  32372. this._update(geometry);
  32373. return this;
  32374. };
  32375. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  32376. if (updatable === void 0) { updatable = false; }
  32377. if (this.positions) {
  32378. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  32379. }
  32380. if (this.normals) {
  32381. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  32382. }
  32383. if (this.tangents) {
  32384. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  32385. }
  32386. if (this.uvs) {
  32387. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  32388. }
  32389. if (this.uvs2) {
  32390. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  32391. }
  32392. if (this.uvs3) {
  32393. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  32394. }
  32395. if (this.uvs4) {
  32396. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  32397. }
  32398. if (this.uvs5) {
  32399. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  32400. }
  32401. if (this.uvs6) {
  32402. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  32403. }
  32404. if (this.colors) {
  32405. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  32406. }
  32407. if (this.matricesIndices) {
  32408. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  32409. }
  32410. if (this.matricesWeights) {
  32411. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  32412. }
  32413. if (this.matricesIndicesExtra) {
  32414. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  32415. }
  32416. if (this.matricesWeightsExtra) {
  32417. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  32418. }
  32419. if (this.indices) {
  32420. meshOrGeometry.setIndices(this.indices, null, updatable);
  32421. }
  32422. return this;
  32423. };
  32424. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  32425. if (this.positions) {
  32426. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  32427. }
  32428. if (this.normals) {
  32429. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  32430. }
  32431. if (this.tangents) {
  32432. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  32433. }
  32434. if (this.uvs) {
  32435. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  32436. }
  32437. if (this.uvs2) {
  32438. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  32439. }
  32440. if (this.uvs3) {
  32441. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  32442. }
  32443. if (this.uvs4) {
  32444. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  32445. }
  32446. if (this.uvs5) {
  32447. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  32448. }
  32449. if (this.uvs6) {
  32450. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  32451. }
  32452. if (this.colors) {
  32453. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  32454. }
  32455. if (this.matricesIndices) {
  32456. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  32457. }
  32458. if (this.matricesWeights) {
  32459. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  32460. }
  32461. if (this.matricesIndicesExtra) {
  32462. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  32463. }
  32464. if (this.matricesWeightsExtra) {
  32465. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  32466. }
  32467. if (this.indices) {
  32468. meshOrGeometry.setIndices(this.indices, null);
  32469. }
  32470. return this;
  32471. };
  32472. /**
  32473. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  32474. * Returns the VertexData.
  32475. */
  32476. VertexData.prototype.transform = function (matrix) {
  32477. var transformed = BABYLON.Vector3.Zero();
  32478. var index;
  32479. if (this.positions) {
  32480. var position = BABYLON.Vector3.Zero();
  32481. for (index = 0; index < this.positions.length; index += 3) {
  32482. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  32483. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  32484. this.positions[index] = transformed.x;
  32485. this.positions[index + 1] = transformed.y;
  32486. this.positions[index + 2] = transformed.z;
  32487. }
  32488. }
  32489. if (this.normals) {
  32490. var normal = BABYLON.Vector3.Zero();
  32491. for (index = 0; index < this.normals.length; index += 3) {
  32492. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  32493. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  32494. this.normals[index] = transformed.x;
  32495. this.normals[index + 1] = transformed.y;
  32496. this.normals[index + 2] = transformed.z;
  32497. }
  32498. }
  32499. if (this.tangents) {
  32500. var tangent = BABYLON.Vector4.Zero();
  32501. var tangentTransformed = BABYLON.Vector4.Zero();
  32502. for (index = 0; index < this.tangents.length; index += 4) {
  32503. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  32504. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  32505. this.tangents[index] = tangentTransformed.x;
  32506. this.tangents[index + 1] = tangentTransformed.y;
  32507. this.tangents[index + 2] = tangentTransformed.z;
  32508. this.tangents[index + 3] = tangentTransformed.w;
  32509. }
  32510. }
  32511. return this;
  32512. };
  32513. /**
  32514. * Merges the passed VertexData into the current one.
  32515. * Returns the modified VertexData.
  32516. */
  32517. VertexData.prototype.merge = function (other) {
  32518. this._validate();
  32519. other._validate();
  32520. if (!this.normals !== !other.normals ||
  32521. !this.tangents !== !other.tangents ||
  32522. !this.uvs !== !other.uvs ||
  32523. !this.uvs2 !== !other.uvs2 ||
  32524. !this.uvs3 !== !other.uvs3 ||
  32525. !this.uvs4 !== !other.uvs4 ||
  32526. !this.uvs5 !== !other.uvs5 ||
  32527. !this.uvs6 !== !other.uvs6 ||
  32528. !this.colors !== !other.colors ||
  32529. !this.matricesIndices !== !other.matricesIndices ||
  32530. !this.matricesWeights !== !other.matricesWeights ||
  32531. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  32532. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  32533. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  32534. }
  32535. if (other.indices) {
  32536. if (!this.indices) {
  32537. this.indices = [];
  32538. }
  32539. var offset = this.positions ? this.positions.length / 3 : 0;
  32540. for (var index = 0; index < other.indices.length; index++) {
  32541. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  32542. this.indices.push(other.indices[index] + offset);
  32543. }
  32544. }
  32545. this.positions = this._mergeElement(this.positions, other.positions);
  32546. this.normals = this._mergeElement(this.normals, other.normals);
  32547. this.tangents = this._mergeElement(this.tangents, other.tangents);
  32548. this.uvs = this._mergeElement(this.uvs, other.uvs);
  32549. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  32550. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  32551. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  32552. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  32553. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  32554. this.colors = this._mergeElement(this.colors, other.colors);
  32555. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  32556. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  32557. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  32558. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  32559. return this;
  32560. };
  32561. VertexData.prototype._mergeElement = function (source, other) {
  32562. if (!source) {
  32563. return other;
  32564. }
  32565. if (!other) {
  32566. return source;
  32567. }
  32568. var len = other.length + source.length;
  32569. var isSrcTypedArray = source instanceof Float32Array;
  32570. var isOthTypedArray = other instanceof Float32Array;
  32571. // use non-loop method when the source is Float32Array
  32572. if (isSrcTypedArray) {
  32573. var ret32 = new Float32Array(len);
  32574. ret32.set(source);
  32575. ret32.set(other, source.length);
  32576. return ret32;
  32577. // source is number[], when other is also use concat
  32578. }
  32579. else if (!isOthTypedArray) {
  32580. return source.concat(other);
  32581. // source is a number[], but other is a Float32Array, loop required
  32582. }
  32583. else {
  32584. var ret = source.slice(0); // copy source to a separate array
  32585. for (var i = 0, len = other.length; i < len; i++) {
  32586. ret.push(other[i]);
  32587. }
  32588. return ret;
  32589. }
  32590. };
  32591. VertexData.prototype._validate = function () {
  32592. if (!this.positions) {
  32593. throw new Error("Positions are required");
  32594. }
  32595. var getElementCount = function (kind, values) {
  32596. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  32597. if ((values.length % stride) !== 0) {
  32598. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  32599. }
  32600. return values.length / stride;
  32601. };
  32602. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  32603. var validateElementCount = function (kind, values) {
  32604. var elementCount = getElementCount(kind, values);
  32605. if (elementCount !== positionsElementCount) {
  32606. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  32607. }
  32608. };
  32609. if (this.normals)
  32610. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  32611. if (this.tangents)
  32612. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  32613. if (this.uvs)
  32614. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  32615. if (this.uvs2)
  32616. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  32617. if (this.uvs3)
  32618. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  32619. if (this.uvs4)
  32620. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  32621. if (this.uvs5)
  32622. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  32623. if (this.uvs6)
  32624. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  32625. if (this.colors)
  32626. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  32627. if (this.matricesIndices)
  32628. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  32629. if (this.matricesWeights)
  32630. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  32631. if (this.matricesIndicesExtra)
  32632. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  32633. if (this.matricesWeightsExtra)
  32634. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  32635. };
  32636. /**
  32637. * Serializes the VertexData.
  32638. * Returns a serialized object.
  32639. */
  32640. VertexData.prototype.serialize = function () {
  32641. var serializationObject = this.serialize();
  32642. if (this.positions) {
  32643. serializationObject.positions = this.positions;
  32644. }
  32645. if (this.normals) {
  32646. serializationObject.normals = this.normals;
  32647. }
  32648. if (this.tangents) {
  32649. serializationObject.tangents = this.tangents;
  32650. }
  32651. if (this.uvs) {
  32652. serializationObject.uvs = this.uvs;
  32653. }
  32654. if (this.uvs2) {
  32655. serializationObject.uvs2 = this.uvs2;
  32656. }
  32657. if (this.uvs3) {
  32658. serializationObject.uvs3 = this.uvs3;
  32659. }
  32660. if (this.uvs4) {
  32661. serializationObject.uvs4 = this.uvs4;
  32662. }
  32663. if (this.uvs5) {
  32664. serializationObject.uvs5 = this.uvs5;
  32665. }
  32666. if (this.uvs6) {
  32667. serializationObject.uvs6 = this.uvs6;
  32668. }
  32669. if (this.colors) {
  32670. serializationObject.colors = this.colors;
  32671. }
  32672. if (this.matricesIndices) {
  32673. serializationObject.matricesIndices = this.matricesIndices;
  32674. serializationObject.matricesIndices._isExpanded = true;
  32675. }
  32676. if (this.matricesWeights) {
  32677. serializationObject.matricesWeights = this.matricesWeights;
  32678. }
  32679. if (this.matricesIndicesExtra) {
  32680. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  32681. serializationObject.matricesIndicesExtra._isExpanded = true;
  32682. }
  32683. if (this.matricesWeightsExtra) {
  32684. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  32685. }
  32686. serializationObject.indices = this.indices;
  32687. return serializationObject;
  32688. };
  32689. // Statics
  32690. /**
  32691. * Returns the object VertexData associated to the passed mesh.
  32692. */
  32693. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  32694. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  32695. };
  32696. /**
  32697. * Returns the object VertexData associated to the passed geometry.
  32698. */
  32699. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  32700. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  32701. };
  32702. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  32703. var result = new VertexData();
  32704. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32705. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  32706. }
  32707. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32708. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  32709. }
  32710. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  32711. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  32712. }
  32713. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32714. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  32715. }
  32716. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  32717. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  32718. }
  32719. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  32720. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  32721. }
  32722. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  32723. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  32724. }
  32725. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  32726. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  32727. }
  32728. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  32729. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  32730. }
  32731. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  32732. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  32733. }
  32734. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  32735. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  32736. }
  32737. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  32738. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  32739. }
  32740. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  32741. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  32742. }
  32743. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  32744. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  32745. }
  32746. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  32747. return result;
  32748. };
  32749. /**
  32750. * Creates the vertexData of the Ribbon.
  32751. */
  32752. VertexData.CreateRibbon = function (options) {
  32753. var pathArray = options.pathArray;
  32754. var closeArray = options.closeArray || false;
  32755. var closePath = options.closePath || false;
  32756. var invertUV = options.invertUV || false;
  32757. var defaultOffset = Math.floor(pathArray[0].length / 2);
  32758. var offset = options.offset || defaultOffset;
  32759. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  32760. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32761. var customUV = options.uvs;
  32762. var customColors = options.colors;
  32763. var positions = [];
  32764. var indices = [];
  32765. var normals = [];
  32766. var uvs = [];
  32767. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  32768. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  32769. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  32770. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  32771. var minlg; // minimal length among all paths from pathArray
  32772. var lg = []; // array of path lengths : nb of vertex per path
  32773. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  32774. var p; // path iterator
  32775. var i; // point iterator
  32776. var j; // point iterator
  32777. // if single path in pathArray
  32778. if (pathArray.length < 2) {
  32779. var ar1 = [];
  32780. var ar2 = [];
  32781. for (i = 0; i < pathArray[0].length - offset; i++) {
  32782. ar1.push(pathArray[0][i]);
  32783. ar2.push(pathArray[0][i + offset]);
  32784. }
  32785. pathArray = [ar1, ar2];
  32786. }
  32787. // positions and horizontal distances (u)
  32788. var idc = 0;
  32789. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  32790. var path;
  32791. var l;
  32792. minlg = pathArray[0].length;
  32793. var vectlg;
  32794. var dist;
  32795. for (p = 0; p < pathArray.length; p++) {
  32796. uTotalDistance[p] = 0;
  32797. us[p] = [0];
  32798. path = pathArray[p];
  32799. l = path.length;
  32800. minlg = (minlg < l) ? minlg : l;
  32801. j = 0;
  32802. while (j < l) {
  32803. positions.push(path[j].x, path[j].y, path[j].z);
  32804. if (j > 0) {
  32805. vectlg = path[j].subtract(path[j - 1]).length();
  32806. dist = vectlg + uTotalDistance[p];
  32807. us[p].push(dist);
  32808. uTotalDistance[p] = dist;
  32809. }
  32810. j++;
  32811. }
  32812. if (closePath) {
  32813. j--;
  32814. positions.push(path[0].x, path[0].y, path[0].z);
  32815. vectlg = path[j].subtract(path[0]).length();
  32816. dist = vectlg + uTotalDistance[p];
  32817. us[p].push(dist);
  32818. uTotalDistance[p] = dist;
  32819. }
  32820. lg[p] = l + closePathCorr;
  32821. idx[p] = idc;
  32822. idc += (l + closePathCorr);
  32823. }
  32824. // vertical distances (v)
  32825. var path1;
  32826. var path2;
  32827. var vertex1 = null;
  32828. var vertex2 = null;
  32829. for (i = 0; i < minlg + closePathCorr; i++) {
  32830. vTotalDistance[i] = 0;
  32831. vs[i] = [0];
  32832. for (p = 0; p < pathArray.length - 1; p++) {
  32833. path1 = pathArray[p];
  32834. path2 = pathArray[p + 1];
  32835. if (i === minlg) {
  32836. vertex1 = path1[0];
  32837. vertex2 = path2[0];
  32838. }
  32839. else {
  32840. vertex1 = path1[i];
  32841. vertex2 = path2[i];
  32842. }
  32843. vectlg = vertex2.subtract(vertex1).length();
  32844. dist = vectlg + vTotalDistance[i];
  32845. vs[i].push(dist);
  32846. vTotalDistance[i] = dist;
  32847. }
  32848. if (closeArray && vertex2 && vertex1) {
  32849. path1 = pathArray[p];
  32850. path2 = pathArray[0];
  32851. if (i === minlg) {
  32852. vertex2 = path2[0];
  32853. }
  32854. vectlg = vertex2.subtract(vertex1).length();
  32855. dist = vectlg + vTotalDistance[i];
  32856. vTotalDistance[i] = dist;
  32857. }
  32858. }
  32859. // uvs
  32860. var u;
  32861. var v;
  32862. if (customUV) {
  32863. for (p = 0; p < customUV.length; p++) {
  32864. uvs.push(customUV[p].x, customUV[p].y);
  32865. }
  32866. }
  32867. else {
  32868. for (p = 0; p < pathArray.length; p++) {
  32869. for (i = 0; i < minlg + closePathCorr; i++) {
  32870. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  32871. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  32872. if (invertUV) {
  32873. uvs.push(v, u);
  32874. }
  32875. else {
  32876. uvs.push(u, v);
  32877. }
  32878. }
  32879. }
  32880. }
  32881. // indices
  32882. p = 0; // path index
  32883. var pi = 0; // positions array index
  32884. var l1 = lg[p] - 1; // path1 length
  32885. var l2 = lg[p + 1] - 1; // path2 length
  32886. var min = (l1 < l2) ? l1 : l2; // current path stop index
  32887. var shft = idx[1] - idx[0]; // shift
  32888. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  32889. while (pi <= min && p < path1nb) {
  32890. // 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
  32891. indices.push(pi, pi + shft, pi + 1);
  32892. indices.push(pi + shft + 1, pi + 1, pi + shft);
  32893. pi += 1;
  32894. if (pi === min) {
  32895. p++;
  32896. if (p === lg.length - 1) {
  32897. shft = idx[0] - idx[p];
  32898. l1 = lg[p] - 1;
  32899. l2 = lg[0] - 1;
  32900. }
  32901. else {
  32902. shft = idx[p + 1] - idx[p];
  32903. l1 = lg[p] - 1;
  32904. l2 = lg[p + 1] - 1;
  32905. }
  32906. pi = idx[p];
  32907. min = (l1 < l2) ? l1 + pi : l2 + pi;
  32908. }
  32909. }
  32910. // normals
  32911. VertexData.ComputeNormals(positions, indices, normals);
  32912. if (closePath) {
  32913. var indexFirst = 0;
  32914. var indexLast = 0;
  32915. for (p = 0; p < pathArray.length; p++) {
  32916. indexFirst = idx[p] * 3;
  32917. if (p + 1 < pathArray.length) {
  32918. indexLast = (idx[p + 1] - 1) * 3;
  32919. }
  32920. else {
  32921. indexLast = normals.length - 3;
  32922. }
  32923. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  32924. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  32925. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  32926. normals[indexLast] = normals[indexFirst];
  32927. normals[indexLast + 1] = normals[indexFirst + 1];
  32928. normals[indexLast + 2] = normals[indexFirst + 2];
  32929. }
  32930. }
  32931. // sides
  32932. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  32933. // Colors
  32934. var colors = null;
  32935. if (customColors) {
  32936. colors = new Float32Array(customColors.length * 4);
  32937. for (var c = 0; c < customColors.length; c++) {
  32938. colors[c * 4] = customColors[c].r;
  32939. colors[c * 4 + 1] = customColors[c].g;
  32940. colors[c * 4 + 2] = customColors[c].b;
  32941. colors[c * 4 + 3] = customColors[c].a;
  32942. }
  32943. }
  32944. // Result
  32945. var vertexData = new VertexData();
  32946. var positions32 = new Float32Array(positions);
  32947. var normals32 = new Float32Array(normals);
  32948. var uvs32 = new Float32Array(uvs);
  32949. vertexData.indices = indices;
  32950. vertexData.positions = positions32;
  32951. vertexData.normals = normals32;
  32952. vertexData.uvs = uvs32;
  32953. if (colors) {
  32954. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  32955. }
  32956. if (closePath) {
  32957. vertexData._idx = idx;
  32958. }
  32959. return vertexData;
  32960. };
  32961. /**
  32962. * Creates the VertexData of the Box.
  32963. */
  32964. VertexData.CreateBox = function (options) {
  32965. var normalsSource = [
  32966. new BABYLON.Vector3(0, 0, 1),
  32967. new BABYLON.Vector3(0, 0, -1),
  32968. new BABYLON.Vector3(1, 0, 0),
  32969. new BABYLON.Vector3(-1, 0, 0),
  32970. new BABYLON.Vector3(0, 1, 0),
  32971. new BABYLON.Vector3(0, -1, 0)
  32972. ];
  32973. var indices = [];
  32974. var positions = [];
  32975. var normals = [];
  32976. var uvs = [];
  32977. var width = options.width || options.size || 1;
  32978. var height = options.height || options.size || 1;
  32979. var depth = options.depth || options.size || 1;
  32980. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32981. var faceUV = options.faceUV || new Array(6);
  32982. var faceColors = options.faceColors;
  32983. var colors = [];
  32984. // default face colors and UV if undefined
  32985. for (var f = 0; f < 6; f++) {
  32986. if (faceUV[f] === undefined) {
  32987. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  32988. }
  32989. if (faceColors && faceColors[f] === undefined) {
  32990. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  32991. }
  32992. }
  32993. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  32994. // Create each face in turn.
  32995. for (var index = 0; index < normalsSource.length; index++) {
  32996. var normal = normalsSource[index];
  32997. // Get two vectors perpendicular to the face normal and to each other.
  32998. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  32999. var side2 = BABYLON.Vector3.Cross(normal, side1);
  33000. // Six indices (two triangles) per face.
  33001. var verticesLength = positions.length / 3;
  33002. indices.push(verticesLength);
  33003. indices.push(verticesLength + 1);
  33004. indices.push(verticesLength + 2);
  33005. indices.push(verticesLength);
  33006. indices.push(verticesLength + 2);
  33007. indices.push(verticesLength + 3);
  33008. // Four vertices per face.
  33009. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  33010. positions.push(vertex.x, vertex.y, vertex.z);
  33011. normals.push(normal.x, normal.y, normal.z);
  33012. uvs.push(faceUV[index].z, faceUV[index].w);
  33013. if (faceColors) {
  33014. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33015. }
  33016. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  33017. positions.push(vertex.x, vertex.y, vertex.z);
  33018. normals.push(normal.x, normal.y, normal.z);
  33019. uvs.push(faceUV[index].x, faceUV[index].w);
  33020. if (faceColors) {
  33021. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33022. }
  33023. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  33024. positions.push(vertex.x, vertex.y, vertex.z);
  33025. normals.push(normal.x, normal.y, normal.z);
  33026. uvs.push(faceUV[index].x, faceUV[index].y);
  33027. if (faceColors) {
  33028. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33029. }
  33030. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  33031. positions.push(vertex.x, vertex.y, vertex.z);
  33032. normals.push(normal.x, normal.y, normal.z);
  33033. uvs.push(faceUV[index].z, faceUV[index].y);
  33034. if (faceColors) {
  33035. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33036. }
  33037. }
  33038. // sides
  33039. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33040. // Result
  33041. var vertexData = new VertexData();
  33042. vertexData.indices = indices;
  33043. vertexData.positions = positions;
  33044. vertexData.normals = normals;
  33045. vertexData.uvs = uvs;
  33046. if (faceColors) {
  33047. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  33048. vertexData.colors = totalColors;
  33049. }
  33050. return vertexData;
  33051. };
  33052. /**
  33053. * Creates the VertexData of the Sphere.
  33054. */
  33055. VertexData.CreateSphere = function (options) {
  33056. var segments = options.segments || 32;
  33057. var diameterX = options.diameterX || options.diameter || 1;
  33058. var diameterY = options.diameterY || options.diameter || 1;
  33059. var diameterZ = options.diameterZ || options.diameter || 1;
  33060. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  33061. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  33062. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33063. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  33064. var totalZRotationSteps = 2 + segments;
  33065. var totalYRotationSteps = 2 * totalZRotationSteps;
  33066. var indices = [];
  33067. var positions = [];
  33068. var normals = [];
  33069. var uvs = [];
  33070. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  33071. var normalizedZ = zRotationStep / totalZRotationSteps;
  33072. var angleZ = normalizedZ * Math.PI * slice;
  33073. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  33074. var normalizedY = yRotationStep / totalYRotationSteps;
  33075. var angleY = normalizedY * Math.PI * 2 * arc;
  33076. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  33077. var rotationY = BABYLON.Matrix.RotationY(angleY);
  33078. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  33079. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  33080. var vertex = complete.multiply(radius);
  33081. var normal = complete.divide(radius).normalize();
  33082. positions.push(vertex.x, vertex.y, vertex.z);
  33083. normals.push(normal.x, normal.y, normal.z);
  33084. uvs.push(normalizedY, normalizedZ);
  33085. }
  33086. if (zRotationStep > 0) {
  33087. var verticesCount = positions.length / 3;
  33088. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  33089. indices.push((firstIndex));
  33090. indices.push((firstIndex + 1));
  33091. indices.push(firstIndex + totalYRotationSteps + 1);
  33092. indices.push((firstIndex + totalYRotationSteps + 1));
  33093. indices.push((firstIndex + 1));
  33094. indices.push((firstIndex + totalYRotationSteps + 2));
  33095. }
  33096. }
  33097. }
  33098. // Sides
  33099. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33100. // Result
  33101. var vertexData = new VertexData();
  33102. vertexData.indices = indices;
  33103. vertexData.positions = positions;
  33104. vertexData.normals = normals;
  33105. vertexData.uvs = uvs;
  33106. return vertexData;
  33107. };
  33108. /**
  33109. * Creates the VertexData of the Cylinder or Cone.
  33110. */
  33111. VertexData.CreateCylinder = function (options) {
  33112. var height = options.height || 2;
  33113. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  33114. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  33115. var tessellation = options.tessellation || 24;
  33116. var subdivisions = options.subdivisions || 1;
  33117. var hasRings = options.hasRings ? true : false;
  33118. var enclose = options.enclose ? true : false;
  33119. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  33120. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33121. var faceUV = options.faceUV || new Array(3);
  33122. var faceColors = options.faceColors;
  33123. // default face colors and UV if undefined
  33124. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  33125. var ringNb = (hasRings) ? subdivisions : 1;
  33126. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  33127. var f;
  33128. for (f = 0; f < surfaceNb; f++) {
  33129. if (faceColors && faceColors[f] === undefined) {
  33130. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33131. }
  33132. }
  33133. for (f = 0; f < surfaceNb; f++) {
  33134. if (faceUV && faceUV[f] === undefined) {
  33135. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33136. }
  33137. }
  33138. var indices = new Array();
  33139. var positions = new Array();
  33140. var normals = new Array();
  33141. var uvs = new Array();
  33142. var colors = new Array();
  33143. var angle_step = Math.PI * 2 * arc / tessellation;
  33144. var angle;
  33145. var h;
  33146. var radius;
  33147. var tan = (diameterBottom - diameterTop) / 2 / height;
  33148. var ringVertex = BABYLON.Vector3.Zero();
  33149. var ringNormal = BABYLON.Vector3.Zero();
  33150. var ringFirstVertex = BABYLON.Vector3.Zero();
  33151. var ringFirstNormal = BABYLON.Vector3.Zero();
  33152. var quadNormal = BABYLON.Vector3.Zero();
  33153. var Y = BABYLON.Axis.Y;
  33154. // positions, normals, uvs
  33155. var i;
  33156. var j;
  33157. var r;
  33158. var ringIdx = 1;
  33159. var s = 1; // surface index
  33160. var cs = 0;
  33161. var v = 0;
  33162. for (i = 0; i <= subdivisions; i++) {
  33163. h = i / subdivisions;
  33164. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  33165. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  33166. for (r = 0; r < ringIdx; r++) {
  33167. if (hasRings) {
  33168. s += r;
  33169. }
  33170. if (enclose) {
  33171. s += 2 * r;
  33172. }
  33173. for (j = 0; j <= tessellation; j++) {
  33174. angle = j * angle_step;
  33175. // position
  33176. ringVertex.x = Math.cos(-angle) * radius;
  33177. ringVertex.y = -height / 2 + h * height;
  33178. ringVertex.z = Math.sin(-angle) * radius;
  33179. // normal
  33180. if (diameterTop === 0 && i === subdivisions) {
  33181. // if no top cap, reuse former normals
  33182. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  33183. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  33184. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  33185. }
  33186. else {
  33187. ringNormal.x = ringVertex.x;
  33188. ringNormal.z = ringVertex.z;
  33189. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  33190. ringNormal.normalize();
  33191. }
  33192. // keep first ring vertex values for enclose
  33193. if (j === 0) {
  33194. ringFirstVertex.copyFrom(ringVertex);
  33195. ringFirstNormal.copyFrom(ringNormal);
  33196. }
  33197. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  33198. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  33199. if (hasRings) {
  33200. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  33201. }
  33202. else {
  33203. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  33204. }
  33205. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  33206. if (faceColors) {
  33207. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  33208. }
  33209. }
  33210. // if enclose, add four vertices and their dedicated normals
  33211. if (arc !== 1 && enclose) {
  33212. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  33213. positions.push(0, ringVertex.y, 0);
  33214. positions.push(0, ringVertex.y, 0);
  33215. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  33216. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  33217. quadNormal.normalize();
  33218. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  33219. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  33220. quadNormal.normalize();
  33221. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  33222. if (hasRings) {
  33223. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  33224. }
  33225. else {
  33226. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  33227. }
  33228. uvs.push(faceUV[s + 1].x, v);
  33229. uvs.push(faceUV[s + 1].z, v);
  33230. if (hasRings) {
  33231. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  33232. }
  33233. else {
  33234. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  33235. }
  33236. uvs.push(faceUV[s + 2].x, v);
  33237. uvs.push(faceUV[s + 2].z, v);
  33238. if (faceColors) {
  33239. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  33240. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  33241. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  33242. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  33243. }
  33244. }
  33245. if (cs !== s) {
  33246. cs = s;
  33247. }
  33248. }
  33249. }
  33250. // indices
  33251. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  33252. var s;
  33253. i = 0;
  33254. for (s = 0; s < subdivisions; s++) {
  33255. var i0 = 0;
  33256. var i1 = 0;
  33257. var i2 = 0;
  33258. var i3 = 0;
  33259. for (j = 0; j < tessellation; j++) {
  33260. i0 = i * (e + 1) + j;
  33261. i1 = (i + 1) * (e + 1) + j;
  33262. i2 = i * (e + 1) + (j + 1);
  33263. i3 = (i + 1) * (e + 1) + (j + 1);
  33264. indices.push(i0, i1, i2);
  33265. indices.push(i3, i2, i1);
  33266. }
  33267. if (arc !== 1 && enclose) {
  33268. indices.push(i0 + 2, i1 + 2, i2 + 2);
  33269. indices.push(i3 + 2, i2 + 2, i1 + 2);
  33270. indices.push(i0 + 4, i1 + 4, i2 + 4);
  33271. indices.push(i3 + 4, i2 + 4, i1 + 4);
  33272. }
  33273. i = (hasRings) ? (i + 2) : (i + 1);
  33274. }
  33275. // Caps
  33276. var createCylinderCap = function (isTop) {
  33277. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  33278. if (radius === 0) {
  33279. return;
  33280. }
  33281. // Cap positions, normals & uvs
  33282. var angle;
  33283. var circleVector;
  33284. var i;
  33285. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  33286. var c = null;
  33287. if (faceColors) {
  33288. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  33289. }
  33290. // cap center
  33291. var vbase = positions.length / 3;
  33292. var offset = isTop ? height / 2 : -height / 2;
  33293. var center = new BABYLON.Vector3(0, offset, 0);
  33294. positions.push(center.x, center.y, center.z);
  33295. normals.push(0, isTop ? 1 : -1, 0);
  33296. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  33297. if (c) {
  33298. colors.push(c.r, c.g, c.b, c.a);
  33299. }
  33300. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  33301. for (i = 0; i <= tessellation; i++) {
  33302. angle = Math.PI * 2 * i * arc / tessellation;
  33303. var cos = Math.cos(-angle);
  33304. var sin = Math.sin(-angle);
  33305. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  33306. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  33307. positions.push(circleVector.x, circleVector.y, circleVector.z);
  33308. normals.push(0, isTop ? 1 : -1, 0);
  33309. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  33310. if (c) {
  33311. colors.push(c.r, c.g, c.b, c.a);
  33312. }
  33313. }
  33314. // Cap indices
  33315. for (i = 0; i < tessellation; i++) {
  33316. if (!isTop) {
  33317. indices.push(vbase);
  33318. indices.push(vbase + (i + 1));
  33319. indices.push(vbase + (i + 2));
  33320. }
  33321. else {
  33322. indices.push(vbase);
  33323. indices.push(vbase + (i + 2));
  33324. indices.push(vbase + (i + 1));
  33325. }
  33326. }
  33327. };
  33328. // add caps to geometry
  33329. createCylinderCap(false);
  33330. createCylinderCap(true);
  33331. // Sides
  33332. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33333. var vertexData = new VertexData();
  33334. vertexData.indices = indices;
  33335. vertexData.positions = positions;
  33336. vertexData.normals = normals;
  33337. vertexData.uvs = uvs;
  33338. if (faceColors) {
  33339. vertexData.colors = colors;
  33340. }
  33341. return vertexData;
  33342. };
  33343. /**
  33344. * Creates the VertexData of the Torus.
  33345. */
  33346. VertexData.CreateTorus = function (options) {
  33347. var indices = [];
  33348. var positions = [];
  33349. var normals = [];
  33350. var uvs = [];
  33351. var diameter = options.diameter || 1;
  33352. var thickness = options.thickness || 0.5;
  33353. var tessellation = options.tessellation || 16;
  33354. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33355. var stride = tessellation + 1;
  33356. for (var i = 0; i <= tessellation; i++) {
  33357. var u = i / tessellation;
  33358. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  33359. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  33360. for (var j = 0; j <= tessellation; j++) {
  33361. var v = 1 - j / tessellation;
  33362. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  33363. var dx = Math.cos(innerAngle);
  33364. var dy = Math.sin(innerAngle);
  33365. // Create a vertex.
  33366. var normal = new BABYLON.Vector3(dx, dy, 0);
  33367. var position = normal.scale(thickness / 2);
  33368. var textureCoordinate = new BABYLON.Vector2(u, v);
  33369. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  33370. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  33371. positions.push(position.x, position.y, position.z);
  33372. normals.push(normal.x, normal.y, normal.z);
  33373. uvs.push(textureCoordinate.x, textureCoordinate.y);
  33374. // And create indices for two triangles.
  33375. var nextI = (i + 1) % stride;
  33376. var nextJ = (j + 1) % stride;
  33377. indices.push(i * stride + j);
  33378. indices.push(i * stride + nextJ);
  33379. indices.push(nextI * stride + j);
  33380. indices.push(i * stride + nextJ);
  33381. indices.push(nextI * stride + nextJ);
  33382. indices.push(nextI * stride + j);
  33383. }
  33384. }
  33385. // Sides
  33386. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33387. // Result
  33388. var vertexData = new VertexData();
  33389. vertexData.indices = indices;
  33390. vertexData.positions = positions;
  33391. vertexData.normals = normals;
  33392. vertexData.uvs = uvs;
  33393. return vertexData;
  33394. };
  33395. /**
  33396. * Creates the VertexData of the LineSystem.
  33397. */
  33398. VertexData.CreateLineSystem = function (options) {
  33399. var indices = [];
  33400. var positions = [];
  33401. var lines = options.lines;
  33402. var colors = options.colors;
  33403. var vertexColors = [];
  33404. var idx = 0;
  33405. for (var l = 0; l < lines.length; l++) {
  33406. var points = lines[l];
  33407. for (var index = 0; index < points.length; index++) {
  33408. positions.push(points[index].x, points[index].y, points[index].z);
  33409. if (colors) {
  33410. var color = colors[l];
  33411. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  33412. }
  33413. if (index > 0) {
  33414. indices.push(idx - 1);
  33415. indices.push(idx);
  33416. }
  33417. idx++;
  33418. }
  33419. }
  33420. var vertexData = new VertexData();
  33421. vertexData.indices = indices;
  33422. vertexData.positions = positions;
  33423. if (colors) {
  33424. vertexData.colors = vertexColors;
  33425. }
  33426. return vertexData;
  33427. };
  33428. /**
  33429. * Create the VertexData of the DashedLines.
  33430. */
  33431. VertexData.CreateDashedLines = function (options) {
  33432. var dashSize = options.dashSize || 3;
  33433. var gapSize = options.gapSize || 1;
  33434. var dashNb = options.dashNb || 200;
  33435. var points = options.points;
  33436. var positions = new Array();
  33437. var indices = new Array();
  33438. var curvect = BABYLON.Vector3.Zero();
  33439. var lg = 0;
  33440. var nb = 0;
  33441. var shft = 0;
  33442. var dashshft = 0;
  33443. var curshft = 0;
  33444. var idx = 0;
  33445. var i = 0;
  33446. for (i = 0; i < points.length - 1; i++) {
  33447. points[i + 1].subtractToRef(points[i], curvect);
  33448. lg += curvect.length();
  33449. }
  33450. shft = lg / dashNb;
  33451. dashshft = dashSize * shft / (dashSize + gapSize);
  33452. for (i = 0; i < points.length - 1; i++) {
  33453. points[i + 1].subtractToRef(points[i], curvect);
  33454. nb = Math.floor(curvect.length() / shft);
  33455. curvect.normalize();
  33456. for (var j = 0; j < nb; j++) {
  33457. curshft = shft * j;
  33458. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  33459. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  33460. indices.push(idx, idx + 1);
  33461. idx += 2;
  33462. }
  33463. }
  33464. // Result
  33465. var vertexData = new VertexData();
  33466. vertexData.positions = positions;
  33467. vertexData.indices = indices;
  33468. return vertexData;
  33469. };
  33470. /**
  33471. * Creates the VertexData of the Ground.
  33472. */
  33473. VertexData.CreateGround = function (options) {
  33474. var indices = [];
  33475. var positions = [];
  33476. var normals = [];
  33477. var uvs = [];
  33478. var row, col;
  33479. var width = options.width || 1;
  33480. var height = options.height || 1;
  33481. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  33482. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  33483. for (row = 0; row <= subdivisionsY; row++) {
  33484. for (col = 0; col <= subdivisionsX; col++) {
  33485. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  33486. var normal = new BABYLON.Vector3(0, 1.0, 0);
  33487. positions.push(position.x, position.y, position.z);
  33488. normals.push(normal.x, normal.y, normal.z);
  33489. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  33490. }
  33491. }
  33492. for (row = 0; row < subdivisionsY; row++) {
  33493. for (col = 0; col < subdivisionsX; col++) {
  33494. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  33495. indices.push(col + 1 + row * (subdivisionsX + 1));
  33496. indices.push(col + row * (subdivisionsX + 1));
  33497. indices.push(col + (row + 1) * (subdivisionsX + 1));
  33498. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  33499. indices.push(col + row * (subdivisionsX + 1));
  33500. }
  33501. }
  33502. // Result
  33503. var vertexData = new VertexData();
  33504. vertexData.indices = indices;
  33505. vertexData.positions = positions;
  33506. vertexData.normals = normals;
  33507. vertexData.uvs = uvs;
  33508. return vertexData;
  33509. };
  33510. /**
  33511. * Creates the VertexData of the TiledGround.
  33512. */
  33513. VertexData.CreateTiledGround = function (options) {
  33514. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  33515. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  33516. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  33517. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  33518. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  33519. var precision = options.precision || { w: 1, h: 1 };
  33520. var indices = new Array();
  33521. var positions = new Array();
  33522. var normals = new Array();
  33523. var uvs = new Array();
  33524. var row, col, tileRow, tileCol;
  33525. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  33526. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  33527. precision.w = (precision.w < 1) ? 1 : precision.w;
  33528. precision.h = (precision.h < 1) ? 1 : precision.h;
  33529. var tileSize = {
  33530. 'w': (xmax - xmin) / subdivisions.w,
  33531. 'h': (zmax - zmin) / subdivisions.h
  33532. };
  33533. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  33534. // Indices
  33535. var base = positions.length / 3;
  33536. var rowLength = precision.w + 1;
  33537. for (row = 0; row < precision.h; row++) {
  33538. for (col = 0; col < precision.w; col++) {
  33539. var square = [
  33540. base + col + row * rowLength,
  33541. base + (col + 1) + row * rowLength,
  33542. base + (col + 1) + (row + 1) * rowLength,
  33543. base + col + (row + 1) * rowLength
  33544. ];
  33545. indices.push(square[1]);
  33546. indices.push(square[2]);
  33547. indices.push(square[3]);
  33548. indices.push(square[0]);
  33549. indices.push(square[1]);
  33550. indices.push(square[3]);
  33551. }
  33552. }
  33553. // Position, normals and uvs
  33554. var position = BABYLON.Vector3.Zero();
  33555. var normal = new BABYLON.Vector3(0, 1.0, 0);
  33556. for (row = 0; row <= precision.h; row++) {
  33557. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  33558. for (col = 0; col <= precision.w; col++) {
  33559. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  33560. position.y = 0;
  33561. positions.push(position.x, position.y, position.z);
  33562. normals.push(normal.x, normal.y, normal.z);
  33563. uvs.push(col / precision.w, row / precision.h);
  33564. }
  33565. }
  33566. }
  33567. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  33568. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  33569. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  33570. }
  33571. }
  33572. // Result
  33573. var vertexData = new VertexData();
  33574. vertexData.indices = indices;
  33575. vertexData.positions = positions;
  33576. vertexData.normals = normals;
  33577. vertexData.uvs = uvs;
  33578. return vertexData;
  33579. };
  33580. /**
  33581. * Creates the VertexData of the Ground designed from a heightmap.
  33582. */
  33583. VertexData.CreateGroundFromHeightMap = function (options) {
  33584. var indices = [];
  33585. var positions = [];
  33586. var normals = [];
  33587. var uvs = [];
  33588. var row, col;
  33589. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  33590. // Vertices
  33591. for (row = 0; row <= options.subdivisions; row++) {
  33592. for (col = 0; col <= options.subdivisions; col++) {
  33593. 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));
  33594. // Compute height
  33595. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  33596. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  33597. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  33598. var r = options.buffer[pos] / 255.0;
  33599. var g = options.buffer[pos + 1] / 255.0;
  33600. var b = options.buffer[pos + 2] / 255.0;
  33601. var gradient = r * filter.r + g * filter.g + b * filter.b;
  33602. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  33603. // Add vertex
  33604. positions.push(position.x, position.y, position.z);
  33605. normals.push(0, 0, 0);
  33606. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  33607. }
  33608. }
  33609. // Indices
  33610. for (row = 0; row < options.subdivisions; row++) {
  33611. for (col = 0; col < options.subdivisions; col++) {
  33612. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  33613. indices.push(col + 1 + row * (options.subdivisions + 1));
  33614. indices.push(col + row * (options.subdivisions + 1));
  33615. indices.push(col + (row + 1) * (options.subdivisions + 1));
  33616. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  33617. indices.push(col + row * (options.subdivisions + 1));
  33618. }
  33619. }
  33620. // Normals
  33621. VertexData.ComputeNormals(positions, indices, normals);
  33622. // Result
  33623. var vertexData = new VertexData();
  33624. vertexData.indices = indices;
  33625. vertexData.positions = positions;
  33626. vertexData.normals = normals;
  33627. vertexData.uvs = uvs;
  33628. return vertexData;
  33629. };
  33630. /**
  33631. * Creates the VertexData of the Plane.
  33632. */
  33633. VertexData.CreatePlane = function (options) {
  33634. var indices = [];
  33635. var positions = [];
  33636. var normals = [];
  33637. var uvs = [];
  33638. var width = options.width || options.size || 1;
  33639. var height = options.height || options.size || 1;
  33640. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33641. // Vertices
  33642. var halfWidth = width / 2.0;
  33643. var halfHeight = height / 2.0;
  33644. positions.push(-halfWidth, -halfHeight, 0);
  33645. normals.push(0, 0, -1.0);
  33646. uvs.push(0.0, 0.0);
  33647. positions.push(halfWidth, -halfHeight, 0);
  33648. normals.push(0, 0, -1.0);
  33649. uvs.push(1.0, 0.0);
  33650. positions.push(halfWidth, halfHeight, 0);
  33651. normals.push(0, 0, -1.0);
  33652. uvs.push(1.0, 1.0);
  33653. positions.push(-halfWidth, halfHeight, 0);
  33654. normals.push(0, 0, -1.0);
  33655. uvs.push(0.0, 1.0);
  33656. // Indices
  33657. indices.push(0);
  33658. indices.push(1);
  33659. indices.push(2);
  33660. indices.push(0);
  33661. indices.push(2);
  33662. indices.push(3);
  33663. // Sides
  33664. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33665. // Result
  33666. var vertexData = new VertexData();
  33667. vertexData.indices = indices;
  33668. vertexData.positions = positions;
  33669. vertexData.normals = normals;
  33670. vertexData.uvs = uvs;
  33671. return vertexData;
  33672. };
  33673. /**
  33674. * Creates the VertexData of the Disc or regular Polygon.
  33675. */
  33676. VertexData.CreateDisc = function (options) {
  33677. var positions = new Array();
  33678. var indices = new Array();
  33679. var normals = new Array();
  33680. var uvs = new Array();
  33681. var radius = options.radius || 0.5;
  33682. var tessellation = options.tessellation || 64;
  33683. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  33684. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33685. // positions and uvs
  33686. positions.push(0, 0, 0); // disc center first
  33687. uvs.push(0.5, 0.5);
  33688. var theta = Math.PI * 2 * arc;
  33689. var step = theta / tessellation;
  33690. for (var a = 0; a < theta; a += step) {
  33691. var x = Math.cos(a);
  33692. var y = Math.sin(a);
  33693. var u = (x + 1) / 2;
  33694. var v = (1 - y) / 2;
  33695. positions.push(radius * x, radius * y, 0);
  33696. uvs.push(u, v);
  33697. }
  33698. if (arc === 1) {
  33699. positions.push(positions[3], positions[4], positions[5]); // close the circle
  33700. uvs.push(uvs[2], uvs[3]);
  33701. }
  33702. //indices
  33703. var vertexNb = positions.length / 3;
  33704. for (var i = 1; i < vertexNb - 1; i++) {
  33705. indices.push(i + 1, 0, i);
  33706. }
  33707. // result
  33708. VertexData.ComputeNormals(positions, indices, normals);
  33709. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33710. var vertexData = new VertexData();
  33711. vertexData.indices = indices;
  33712. vertexData.positions = positions;
  33713. vertexData.normals = normals;
  33714. vertexData.uvs = uvs;
  33715. return vertexData;
  33716. };
  33717. /**
  33718. * Re-creates the VertexData of the Polygon for sideOrientation.
  33719. */
  33720. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  33721. var faceUV = fUV || new Array(3);
  33722. var faceColors = fColors;
  33723. var colors = [];
  33724. // default face colors and UV if undefined
  33725. for (var f = 0; f < 3; f++) {
  33726. if (faceUV[f] === undefined) {
  33727. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33728. }
  33729. if (faceColors && faceColors[f] === undefined) {
  33730. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33731. }
  33732. }
  33733. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33734. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33735. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  33736. var indices = polygon.getIndices();
  33737. // set face colours and textures
  33738. var idx = 0;
  33739. var face = 0;
  33740. for (var index = 0; index < normals.length; index += 3) {
  33741. //Edge Face no. 1
  33742. if (Math.abs(normals[index + 1]) < 0.001) {
  33743. face = 1;
  33744. }
  33745. //Top Face no. 0
  33746. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  33747. face = 0;
  33748. }
  33749. //Bottom Face no. 2
  33750. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  33751. face = 2;
  33752. }
  33753. idx = index / 3;
  33754. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  33755. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  33756. if (faceColors) {
  33757. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  33758. }
  33759. }
  33760. // sides
  33761. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  33762. // Result
  33763. var vertexData = new VertexData();
  33764. vertexData.indices = indices;
  33765. vertexData.positions = positions;
  33766. vertexData.normals = normals;
  33767. vertexData.uvs = uvs;
  33768. if (faceColors) {
  33769. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  33770. vertexData.colors = totalColors;
  33771. }
  33772. return vertexData;
  33773. };
  33774. /**
  33775. * Creates the VertexData of the IcoSphere.
  33776. */
  33777. VertexData.CreateIcoSphere = function (options) {
  33778. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33779. var radius = options.radius || 1;
  33780. var flat = (options.flat === undefined) ? true : options.flat;
  33781. var subdivisions = options.subdivisions || 4;
  33782. var radiusX = options.radiusX || radius;
  33783. var radiusY = options.radiusY || radius;
  33784. var radiusZ = options.radiusZ || radius;
  33785. var t = (1 + Math.sqrt(5)) / 2;
  33786. // 12 vertex x,y,z
  33787. var ico_vertices = [
  33788. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  33789. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  33790. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  33791. ];
  33792. // index of 3 vertex makes a face of icopshere
  33793. var ico_indices = [
  33794. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  33795. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  33796. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  33797. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  33798. ];
  33799. // vertex for uv have aliased position, not for UV
  33800. var vertices_unalias_id = [
  33801. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  33802. // vertex alias
  33803. 0,
  33804. 2,
  33805. 3,
  33806. 3,
  33807. 3,
  33808. 4,
  33809. 7,
  33810. 8,
  33811. 9,
  33812. 9,
  33813. 10,
  33814. 11 // 23: B + 12
  33815. ];
  33816. // uv as integer step (not pixels !)
  33817. var ico_vertexuv = [
  33818. 5, 1, 3, 1, 6, 4, 0, 0,
  33819. 5, 3, 4, 2, 2, 2, 4, 0,
  33820. 2, 0, 1, 1, 6, 0, 6, 2,
  33821. // vertex alias (for same vertex on different faces)
  33822. 0, 4,
  33823. 3, 3,
  33824. 4, 4,
  33825. 3, 1,
  33826. 4, 2,
  33827. 4, 4,
  33828. 0, 2,
  33829. 1, 1,
  33830. 2, 2,
  33831. 3, 3,
  33832. 1, 3,
  33833. 2, 4 // 23: B + 12
  33834. ];
  33835. // Vertices[0, 1, ...9, A, B] : position on UV plane
  33836. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  33837. // First island of uv mapping
  33838. // v = 4h 3+ 2
  33839. // v = 3h 9+ 4
  33840. // v = 2h 9+ 5 B
  33841. // v = 1h 9 1 0
  33842. // v = 0h 3 8 7 A
  33843. // u = 0 1 2 3 4 5 6 *a
  33844. // Second island of uv mapping
  33845. // v = 4h 0+ B+ 4+
  33846. // v = 3h A+ 2+
  33847. // v = 2h 7+ 6 3+
  33848. // v = 1h 8+ 3+
  33849. // v = 0h
  33850. // u = 0 1 2 3 4 5 6 *a
  33851. // Face layout on texture UV mapping
  33852. // ============
  33853. // \ 4 /\ 16 / ======
  33854. // \ / \ / /\ 11 /
  33855. // \/ 7 \/ / \ /
  33856. // ======= / 10 \/
  33857. // /\ 17 /\ =======
  33858. // / \ / \ \ 15 /\
  33859. // / 8 \/ 12 \ \ / \
  33860. // ============ \/ 6 \
  33861. // \ 18 /\ ============
  33862. // \ / \ \ 5 /\ 0 /
  33863. // \/ 13 \ \ / \ /
  33864. // ======= \/ 1 \/
  33865. // =============
  33866. // /\ 19 /\ 2 /\
  33867. // / \ / \ / \
  33868. // / 14 \/ 9 \/ 3 \
  33869. // ===================
  33870. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  33871. var ustep = 138 / 1024;
  33872. var vstep = 239 / 1024;
  33873. var uoffset = 60 / 1024;
  33874. var voffset = 26 / 1024;
  33875. // Second island should have margin, not to touch the first island
  33876. // avoid any borderline artefact in pixel rounding
  33877. var island_u_offset = -40 / 1024;
  33878. var island_v_offset = +20 / 1024;
  33879. // face is either island 0 or 1 :
  33880. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  33881. var island = [
  33882. 0, 0, 0, 0, 1,
  33883. 0, 0, 1, 1, 0,
  33884. 0, 0, 1, 1, 0,
  33885. 0, 1, 1, 1, 0 // 15 - 19
  33886. ];
  33887. var indices = new Array();
  33888. var positions = new Array();
  33889. var normals = new Array();
  33890. var uvs = new Array();
  33891. var current_indice = 0;
  33892. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  33893. var face_vertex_pos = new Array(3);
  33894. var face_vertex_uv = new Array(3);
  33895. var v012;
  33896. for (v012 = 0; v012 < 3; v012++) {
  33897. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  33898. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  33899. }
  33900. // create all with normals
  33901. for (var face = 0; face < 20; face++) {
  33902. // 3 vertex per face
  33903. for (v012 = 0; v012 < 3; v012++) {
  33904. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  33905. var v_id = ico_indices[3 * face + v012];
  33906. // vertex have 3D position (x,y,z)
  33907. 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]);
  33908. // Normalize to get normal, then scale to radius
  33909. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  33910. // uv Coordinates from vertex ID
  33911. 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);
  33912. }
  33913. // Subdivide the face (interpolate pos, norm, uv)
  33914. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  33915. // - norm is linear interpolation of vertex corner normal
  33916. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  33917. // - uv is linear interpolation
  33918. //
  33919. // Topology is as below for sub-divide by 2
  33920. // vertex shown as v0,v1,v2
  33921. // interp index is i1 to progress in range [v0,v1[
  33922. // interp index is i2 to progress in range [v0,v2[
  33923. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  33924. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  33925. //
  33926. //
  33927. // i2 v2
  33928. // ^ ^
  33929. // / / \
  33930. // / / \
  33931. // / / \
  33932. // / / (0,1) \
  33933. // / #---------\
  33934. // / / \ (0,0)'/ \
  33935. // / / \ / \
  33936. // / / \ / \
  33937. // / / (0,0) \ / (1,0) \
  33938. // / #---------#---------\
  33939. // v0 v1
  33940. //
  33941. // --------------------> i1
  33942. //
  33943. // interp of (i1,i2):
  33944. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  33945. // along i1 : lerp(x0,x1, i1/(S-i2))
  33946. //
  33947. // centroid of triangle is needed to get help normal computation
  33948. // (c1,c2) are used for centroid location
  33949. var interp_vertex = function (i1, i2, c1, c2) {
  33950. // vertex is interpolated from
  33951. // - face_vertex_pos[0..2]
  33952. // - face_vertex_uv[0..2]
  33953. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  33954. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  33955. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  33956. pos_interp.normalize();
  33957. var vertex_normal;
  33958. if (flat) {
  33959. // in flat mode, recalculate normal as face centroid normal
  33960. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  33961. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  33962. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  33963. }
  33964. else {
  33965. // in smooth mode, recalculate normal from each single vertex position
  33966. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  33967. }
  33968. // Vertex normal need correction due to X,Y,Z radius scaling
  33969. vertex_normal.x /= radiusX;
  33970. vertex_normal.y /= radiusY;
  33971. vertex_normal.z /= radiusZ;
  33972. vertex_normal.normalize();
  33973. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  33974. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  33975. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  33976. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  33977. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  33978. uvs.push(uv_interp.x, uv_interp.y);
  33979. // push each vertex has member of a face
  33980. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  33981. indices.push(current_indice);
  33982. current_indice++;
  33983. };
  33984. for (var i2 = 0; i2 < subdivisions; i2++) {
  33985. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  33986. // face : (i1,i2) for /\ :
  33987. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  33988. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  33989. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  33990. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  33991. if (i1 + i2 + 1 < subdivisions) {
  33992. // face : (i1,i2)' for \/ :
  33993. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  33994. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  33995. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  33996. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  33997. }
  33998. }
  33999. }
  34000. }
  34001. // Sides
  34002. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34003. // Result
  34004. var vertexData = new VertexData();
  34005. vertexData.indices = indices;
  34006. vertexData.positions = positions;
  34007. vertexData.normals = normals;
  34008. vertexData.uvs = uvs;
  34009. return vertexData;
  34010. };
  34011. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  34012. /**
  34013. * Creates the VertexData of the Polyhedron.
  34014. */
  34015. VertexData.CreatePolyhedron = function (options) {
  34016. // provided polyhedron types :
  34017. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  34018. // 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)
  34019. var polyhedra = [];
  34020. 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]] };
  34021. 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]] };
  34022. polyhedra[2] = {
  34023. 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]],
  34024. 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]]
  34025. };
  34026. polyhedra[3] = {
  34027. 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]],
  34028. 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]]
  34029. };
  34030. polyhedra[4] = {
  34031. 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]],
  34032. 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]]
  34033. };
  34034. 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]] };
  34035. 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]] };
  34036. 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]] };
  34037. 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]] };
  34038. 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]] };
  34039. 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]] };
  34040. 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]] };
  34041. 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]] };
  34042. 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]] };
  34043. polyhedra[14] = {
  34044. 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]],
  34045. 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]]
  34046. };
  34047. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  34048. var size = options.size;
  34049. var sizeX = options.sizeX || size || 1;
  34050. var sizeY = options.sizeY || size || 1;
  34051. var sizeZ = options.sizeZ || size || 1;
  34052. var data = options.custom || polyhedra[type];
  34053. var nbfaces = data.face.length;
  34054. var faceUV = options.faceUV || new Array(nbfaces);
  34055. var faceColors = options.faceColors;
  34056. var flat = (options.flat === undefined) ? true : options.flat;
  34057. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34058. var positions = new Array();
  34059. var indices = new Array();
  34060. var normals = new Array();
  34061. var uvs = new Array();
  34062. var colors = new Array();
  34063. var index = 0;
  34064. var faceIdx = 0; // face cursor in the array "indexes"
  34065. var indexes = new Array();
  34066. var i = 0;
  34067. var f = 0;
  34068. var u, v, ang, x, y, tmp;
  34069. // default face colors and UV if undefined
  34070. if (flat) {
  34071. for (f = 0; f < nbfaces; f++) {
  34072. if (faceColors && faceColors[f] === undefined) {
  34073. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  34074. }
  34075. if (faceUV && faceUV[f] === undefined) {
  34076. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  34077. }
  34078. }
  34079. }
  34080. if (!flat) {
  34081. for (i = 0; i < data.vertex.length; i++) {
  34082. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  34083. uvs.push(0, 0);
  34084. }
  34085. for (f = 0; f < nbfaces; f++) {
  34086. for (i = 0; i < data.face[f].length - 2; i++) {
  34087. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  34088. }
  34089. }
  34090. }
  34091. else {
  34092. for (f = 0; f < nbfaces; f++) {
  34093. var fl = data.face[f].length; // number of vertices of the current face
  34094. ang = 2 * Math.PI / fl;
  34095. x = 0.5 * Math.tan(ang / 2);
  34096. y = 0.5;
  34097. // positions, uvs, colors
  34098. for (i = 0; i < fl; i++) {
  34099. // positions
  34100. 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);
  34101. indexes.push(index);
  34102. index++;
  34103. // uvs
  34104. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  34105. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  34106. uvs.push(u, v);
  34107. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  34108. y = x * Math.sin(ang) + y * Math.cos(ang);
  34109. x = tmp;
  34110. // colors
  34111. if (faceColors) {
  34112. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  34113. }
  34114. }
  34115. // indices from indexes
  34116. for (i = 0; i < fl - 2; i++) {
  34117. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  34118. }
  34119. faceIdx += fl;
  34120. }
  34121. }
  34122. VertexData.ComputeNormals(positions, indices, normals);
  34123. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34124. var vertexData = new VertexData();
  34125. vertexData.positions = positions;
  34126. vertexData.indices = indices;
  34127. vertexData.normals = normals;
  34128. vertexData.uvs = uvs;
  34129. if (faceColors && flat) {
  34130. vertexData.colors = colors;
  34131. }
  34132. return vertexData;
  34133. };
  34134. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  34135. /**
  34136. * Creates the VertexData of the Torus Knot.
  34137. */
  34138. VertexData.CreateTorusKnot = function (options) {
  34139. var indices = new Array();
  34140. var positions = new Array();
  34141. var normals = new Array();
  34142. var uvs = new Array();
  34143. var radius = options.radius || 2;
  34144. var tube = options.tube || 0.5;
  34145. var radialSegments = options.radialSegments || 32;
  34146. var tubularSegments = options.tubularSegments || 32;
  34147. var p = options.p || 2;
  34148. var q = options.q || 3;
  34149. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34150. // Helper
  34151. var getPos = function (angle) {
  34152. var cu = Math.cos(angle);
  34153. var su = Math.sin(angle);
  34154. var quOverP = q / p * angle;
  34155. var cs = Math.cos(quOverP);
  34156. var tx = radius * (2 + cs) * 0.5 * cu;
  34157. var ty = radius * (2 + cs) * su * 0.5;
  34158. var tz = radius * Math.sin(quOverP) * 0.5;
  34159. return new BABYLON.Vector3(tx, ty, tz);
  34160. };
  34161. // Vertices
  34162. var i;
  34163. var j;
  34164. for (i = 0; i <= radialSegments; i++) {
  34165. var modI = i % radialSegments;
  34166. var u = modI / radialSegments * 2 * p * Math.PI;
  34167. var p1 = getPos(u);
  34168. var p2 = getPos(u + 0.01);
  34169. var tang = p2.subtract(p1);
  34170. var n = p2.add(p1);
  34171. var bitan = BABYLON.Vector3.Cross(tang, n);
  34172. n = BABYLON.Vector3.Cross(bitan, tang);
  34173. bitan.normalize();
  34174. n.normalize();
  34175. for (j = 0; j < tubularSegments; j++) {
  34176. var modJ = j % tubularSegments;
  34177. var v = modJ / tubularSegments * 2 * Math.PI;
  34178. var cx = -tube * Math.cos(v);
  34179. var cy = tube * Math.sin(v);
  34180. positions.push(p1.x + cx * n.x + cy * bitan.x);
  34181. positions.push(p1.y + cx * n.y + cy * bitan.y);
  34182. positions.push(p1.z + cx * n.z + cy * bitan.z);
  34183. uvs.push(i / radialSegments);
  34184. uvs.push(j / tubularSegments);
  34185. }
  34186. }
  34187. for (i = 0; i < radialSegments; i++) {
  34188. for (j = 0; j < tubularSegments; j++) {
  34189. var jNext = (j + 1) % tubularSegments;
  34190. var a = i * tubularSegments + j;
  34191. var b = (i + 1) * tubularSegments + j;
  34192. var c = (i + 1) * tubularSegments + jNext;
  34193. var d = i * tubularSegments + jNext;
  34194. indices.push(d);
  34195. indices.push(b);
  34196. indices.push(a);
  34197. indices.push(d);
  34198. indices.push(c);
  34199. indices.push(b);
  34200. }
  34201. }
  34202. // Normals
  34203. VertexData.ComputeNormals(positions, indices, normals);
  34204. // Sides
  34205. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34206. // Result
  34207. var vertexData = new VertexData();
  34208. vertexData.indices = indices;
  34209. vertexData.positions = positions;
  34210. vertexData.normals = normals;
  34211. vertexData.uvs = uvs;
  34212. return vertexData;
  34213. };
  34214. // Tools
  34215. /**
  34216. * @param {any} - positions (number[] or Float32Array)
  34217. * @param {any} - indices (number[] or Uint16Array)
  34218. * @param {any} - normals (number[] or Float32Array)
  34219. * options (optional) :
  34220. * facetPositions : optional array of facet positions (vector3)
  34221. * facetNormals : optional array of facet normals (vector3)
  34222. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  34223. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  34224. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  34225. * bbSize : optional bounding box size data, required for facetPartitioning computation
  34226. * bInfo : optional bounding info, required for facetPartitioning computation
  34227. * useRightHandedSystem: optional boolean to for right handed system computation
  34228. * depthSort : optional boolean to enable the facet depth sort computation
  34229. * distanceTo : optional Vector3 to compute the facet depth from this location
  34230. * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  34231. */
  34232. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  34233. // temporary scalar variables
  34234. var index = 0; // facet index
  34235. var p1p2x = 0.0; // p1p2 vector x coordinate
  34236. var p1p2y = 0.0; // p1p2 vector y coordinate
  34237. var p1p2z = 0.0; // p1p2 vector z coordinate
  34238. var p3p2x = 0.0; // p3p2 vector x coordinate
  34239. var p3p2y = 0.0; // p3p2 vector y coordinate
  34240. var p3p2z = 0.0; // p3p2 vector z coordinate
  34241. var faceNormalx = 0.0; // facet normal x coordinate
  34242. var faceNormaly = 0.0; // facet normal y coordinate
  34243. var faceNormalz = 0.0; // facet normal z coordinate
  34244. var length = 0.0; // facet normal length before normalization
  34245. var v1x = 0; // vector1 x index in the positions array
  34246. var v1y = 0; // vector1 y index in the positions array
  34247. var v1z = 0; // vector1 z index in the positions array
  34248. var v2x = 0; // vector2 x index in the positions array
  34249. var v2y = 0; // vector2 y index in the positions array
  34250. var v2z = 0; // vector2 z index in the positions array
  34251. var v3x = 0; // vector3 x index in the positions array
  34252. var v3y = 0; // vector3 y index in the positions array
  34253. var v3z = 0; // vector3 z index in the positions array
  34254. var computeFacetNormals = false;
  34255. var computeFacetPositions = false;
  34256. var computeFacetPartitioning = false;
  34257. var computeDepthSort = false;
  34258. var faceNormalSign = 1;
  34259. var ratio = 0;
  34260. var distanceTo = null;
  34261. if (options) {
  34262. computeFacetNormals = (options.facetNormals) ? true : false;
  34263. computeFacetPositions = (options.facetPositions) ? true : false;
  34264. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  34265. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  34266. ratio = options.ratio || 0;
  34267. computeDepthSort = (options.depthSort) ? true : false;
  34268. distanceTo = (options.distanceTo);
  34269. if (computeDepthSort) {
  34270. if (distanceTo === undefined) {
  34271. distanceTo = BABYLON.Vector3.Zero();
  34272. }
  34273. var depthSortedFacets = options.depthSortedFacets;
  34274. }
  34275. }
  34276. // facetPartitioning reinit if needed
  34277. var xSubRatio = 0;
  34278. var ySubRatio = 0;
  34279. var zSubRatio = 0;
  34280. var subSq = 0;
  34281. if (computeFacetPartitioning && options && options.bbSize) {
  34282. var ox = 0; // X partitioning index for facet position
  34283. var oy = 0; // Y partinioning index for facet position
  34284. var oz = 0; // Z partinioning index for facet position
  34285. var b1x = 0; // X partitioning index for facet v1 vertex
  34286. var b1y = 0; // Y partitioning index for facet v1 vertex
  34287. var b1z = 0; // z partitioning index for facet v1 vertex
  34288. var b2x = 0; // X partitioning index for facet v2 vertex
  34289. var b2y = 0; // Y partitioning index for facet v2 vertex
  34290. var b2z = 0; // Z partitioning index for facet v2 vertex
  34291. var b3x = 0; // X partitioning index for facet v3 vertex
  34292. var b3y = 0; // Y partitioning index for facet v3 vertex
  34293. var b3z = 0; // Z partitioning index for facet v3 vertex
  34294. var block_idx_o = 0; // facet barycenter block index
  34295. var block_idx_v1 = 0; // v1 vertex block index
  34296. var block_idx_v2 = 0; // v2 vertex block index
  34297. var block_idx_v3 = 0; // v3 vertex block index
  34298. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  34299. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  34300. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  34301. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  34302. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  34303. subSq = options.subDiv.max * options.subDiv.max;
  34304. options.facetPartitioning.length = 0;
  34305. }
  34306. // reset the normals
  34307. for (index = 0; index < positions.length; index++) {
  34308. normals[index] = 0.0;
  34309. }
  34310. // Loop : 1 indice triplet = 1 facet
  34311. var nbFaces = (indices.length / 3) | 0;
  34312. for (index = 0; index < nbFaces; index++) {
  34313. // get the indexes of the coordinates of each vertex of the facet
  34314. v1x = indices[index * 3] * 3;
  34315. v1y = v1x + 1;
  34316. v1z = v1x + 2;
  34317. v2x = indices[index * 3 + 1] * 3;
  34318. v2y = v2x + 1;
  34319. v2z = v2x + 2;
  34320. v3x = indices[index * 3 + 2] * 3;
  34321. v3y = v3x + 1;
  34322. v3z = v3x + 2;
  34323. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  34324. p1p2y = positions[v1y] - positions[v2y];
  34325. p1p2z = positions[v1z] - positions[v2z];
  34326. p3p2x = positions[v3x] - positions[v2x];
  34327. p3p2y = positions[v3y] - positions[v2y];
  34328. p3p2z = positions[v3z] - positions[v2z];
  34329. // compute the face normal with the cross product
  34330. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  34331. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  34332. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  34333. // normalize this normal and store it in the array facetData
  34334. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  34335. length = (length === 0) ? 1.0 : length;
  34336. faceNormalx /= length;
  34337. faceNormaly /= length;
  34338. faceNormalz /= length;
  34339. if (computeFacetNormals && options) {
  34340. options.facetNormals[index].x = faceNormalx;
  34341. options.facetNormals[index].y = faceNormaly;
  34342. options.facetNormals[index].z = faceNormalz;
  34343. }
  34344. if (computeFacetPositions && options) {
  34345. // compute and the facet barycenter coordinates in the array facetPositions
  34346. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  34347. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  34348. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  34349. }
  34350. if (computeFacetPartitioning && options) {
  34351. // store the facet indexes in arrays in the main facetPartitioning array :
  34352. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  34353. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  34354. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  34355. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  34356. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  34357. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  34358. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  34359. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  34360. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  34361. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  34362. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  34363. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  34364. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  34365. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  34366. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  34367. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  34368. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  34369. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  34370. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  34371. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  34372. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  34373. // push each facet index in each block containing the vertex
  34374. options.facetPartitioning[block_idx_v1].push(index);
  34375. if (block_idx_v2 != block_idx_v1) {
  34376. options.facetPartitioning[block_idx_v2].push(index);
  34377. }
  34378. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  34379. options.facetPartitioning[block_idx_v3].push(index);
  34380. }
  34381. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  34382. options.facetPartitioning[block_idx_o].push(index);
  34383. }
  34384. }
  34385. if (computeDepthSort && options && options.facetPositions) {
  34386. var dsf = depthSortedFacets[index];
  34387. dsf.ind = index * 3;
  34388. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  34389. }
  34390. // compute the normals anyway
  34391. normals[v1x] += faceNormalx; // accumulate all the normals per face
  34392. normals[v1y] += faceNormaly;
  34393. normals[v1z] += faceNormalz;
  34394. normals[v2x] += faceNormalx;
  34395. normals[v2y] += faceNormaly;
  34396. normals[v2z] += faceNormalz;
  34397. normals[v3x] += faceNormalx;
  34398. normals[v3y] += faceNormaly;
  34399. normals[v3z] += faceNormalz;
  34400. }
  34401. // last normalization of each normal
  34402. for (index = 0; index < normals.length / 3; index++) {
  34403. faceNormalx = normals[index * 3];
  34404. faceNormaly = normals[index * 3 + 1];
  34405. faceNormalz = normals[index * 3 + 2];
  34406. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  34407. length = (length === 0) ? 1.0 : length;
  34408. faceNormalx /= length;
  34409. faceNormaly /= length;
  34410. faceNormalz /= length;
  34411. normals[index * 3] = faceNormalx;
  34412. normals[index * 3 + 1] = faceNormaly;
  34413. normals[index * 3 + 2] = faceNormalz;
  34414. }
  34415. };
  34416. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  34417. var li = indices.length;
  34418. var ln = normals.length;
  34419. var i;
  34420. var n;
  34421. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34422. switch (sideOrientation) {
  34423. case BABYLON.Mesh.FRONTSIDE:
  34424. // nothing changed
  34425. break;
  34426. case BABYLON.Mesh.BACKSIDE:
  34427. var tmp;
  34428. // indices
  34429. for (i = 0; i < li; i += 3) {
  34430. tmp = indices[i];
  34431. indices[i] = indices[i + 2];
  34432. indices[i + 2] = tmp;
  34433. }
  34434. // normals
  34435. for (n = 0; n < ln; n++) {
  34436. normals[n] = -normals[n];
  34437. }
  34438. break;
  34439. case BABYLON.Mesh.DOUBLESIDE:
  34440. // positions
  34441. var lp = positions.length;
  34442. var l = lp / 3;
  34443. for (var p = 0; p < lp; p++) {
  34444. positions[lp + p] = positions[p];
  34445. }
  34446. // indices
  34447. for (i = 0; i < li; i += 3) {
  34448. indices[i + li] = indices[i + 2] + l;
  34449. indices[i + 1 + li] = indices[i + 1] + l;
  34450. indices[i + 2 + li] = indices[i] + l;
  34451. }
  34452. // normals
  34453. for (n = 0; n < ln; n++) {
  34454. normals[ln + n] = -normals[n];
  34455. }
  34456. // uvs
  34457. var lu = uvs.length;
  34458. var u = 0;
  34459. for (u = 0; u < lu; u++) {
  34460. uvs[u + lu] = uvs[u];
  34461. }
  34462. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  34463. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  34464. u = 0;
  34465. for (i = 0; i < lu / 2; i++) {
  34466. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  34467. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  34468. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  34469. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  34470. u += 2;
  34471. }
  34472. break;
  34473. }
  34474. };
  34475. /**
  34476. * Creates a new VertexData from the imported parameters.
  34477. */
  34478. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  34479. var vertexData = new VertexData();
  34480. // positions
  34481. var positions = parsedVertexData.positions;
  34482. if (positions) {
  34483. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  34484. }
  34485. // normals
  34486. var normals = parsedVertexData.normals;
  34487. if (normals) {
  34488. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  34489. }
  34490. // tangents
  34491. var tangents = parsedVertexData.tangents;
  34492. if (tangents) {
  34493. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  34494. }
  34495. // uvs
  34496. var uvs = parsedVertexData.uvs;
  34497. if (uvs) {
  34498. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  34499. }
  34500. // uv2s
  34501. var uv2s = parsedVertexData.uv2s;
  34502. if (uv2s) {
  34503. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  34504. }
  34505. // uv3s
  34506. var uv3s = parsedVertexData.uv3s;
  34507. if (uv3s) {
  34508. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  34509. }
  34510. // uv4s
  34511. var uv4s = parsedVertexData.uv4s;
  34512. if (uv4s) {
  34513. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  34514. }
  34515. // uv5s
  34516. var uv5s = parsedVertexData.uv5s;
  34517. if (uv5s) {
  34518. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  34519. }
  34520. // uv6s
  34521. var uv6s = parsedVertexData.uv6s;
  34522. if (uv6s) {
  34523. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  34524. }
  34525. // colors
  34526. var colors = parsedVertexData.colors;
  34527. if (colors) {
  34528. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  34529. }
  34530. // matricesIndices
  34531. var matricesIndices = parsedVertexData.matricesIndices;
  34532. if (matricesIndices) {
  34533. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  34534. }
  34535. // matricesWeights
  34536. var matricesWeights = parsedVertexData.matricesWeights;
  34537. if (matricesWeights) {
  34538. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  34539. }
  34540. // indices
  34541. var indices = parsedVertexData.indices;
  34542. if (indices) {
  34543. vertexData.indices = indices;
  34544. }
  34545. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  34546. };
  34547. return VertexData;
  34548. }());
  34549. BABYLON.VertexData = VertexData;
  34550. })(BABYLON || (BABYLON = {}));
  34551. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  34552. var BABYLON;
  34553. (function (BABYLON) {
  34554. /**
  34555. * Class used to store geometry data (vertex buffers + index buffer)
  34556. */
  34557. var Geometry = /** @class */ (function () {
  34558. /**
  34559. * Creates a new geometry
  34560. * @param id defines the unique ID
  34561. * @param scene defines the hosting scene
  34562. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  34563. * @param updatable defines if geometry must be updatable (false by default)
  34564. * @param mesh defines the mesh that will be associated with the geometry
  34565. */
  34566. function Geometry(id, scene, vertexData, updatable, mesh) {
  34567. if (updatable === void 0) { updatable = false; }
  34568. if (mesh === void 0) { mesh = null; }
  34569. /**
  34570. * Gets the delay loading state of the geometry (none by default which means not delayed)
  34571. */
  34572. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  34573. this._totalVertices = 0;
  34574. this._isDisposed = false;
  34575. this._indexBufferIsUpdatable = false;
  34576. this.id = id;
  34577. this._engine = scene.getEngine();
  34578. this._meshes = [];
  34579. this._scene = scene;
  34580. //Init vertex buffer cache
  34581. this._vertexBuffers = {};
  34582. this._indices = [];
  34583. this._updatable = updatable;
  34584. // vertexData
  34585. if (vertexData) {
  34586. this.setAllVerticesData(vertexData, updatable);
  34587. }
  34588. else {
  34589. this._totalVertices = 0;
  34590. this._indices = [];
  34591. }
  34592. if (this._engine.getCaps().vertexArrayObject) {
  34593. this._vertexArrayObjects = {};
  34594. }
  34595. // applyToMesh
  34596. if (mesh) {
  34597. if (mesh.getClassName() === "LinesMesh") {
  34598. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  34599. this.updateExtend();
  34600. }
  34601. this.applyToMesh(mesh);
  34602. mesh.computeWorldMatrix(true);
  34603. }
  34604. }
  34605. Object.defineProperty(Geometry.prototype, "boundingBias", {
  34606. /**
  34607. * Gets or sets the Bias Vector to apply on the bounding elements (box/sphere), the max extend is computed as v += v * bias.x + bias.y, the min is computed as v -= v * bias.x + bias.y
  34608. */
  34609. get: function () {
  34610. return this._boundingBias;
  34611. },
  34612. /**
  34613. * Gets or sets the Bias Vector to apply on the bounding elements (box/sphere), the max extend is computed as v += v * bias.x + bias.y, the min is computed as v -= v * bias.x + bias.y
  34614. */
  34615. set: function (value) {
  34616. if (this._boundingBias && this._boundingBias.equals(value)) {
  34617. return;
  34618. }
  34619. this._boundingBias = value.clone();
  34620. this.updateBoundingInfo(true, null);
  34621. },
  34622. enumerable: true,
  34623. configurable: true
  34624. });
  34625. /**
  34626. * Static function used to attach a new empty geometry to a mesh
  34627. * @param mesh defines the mesh to attach the geometry to
  34628. * @returns the new {BABYLON.Geometry}
  34629. */
  34630. Geometry.CreateGeometryForMesh = function (mesh) {
  34631. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  34632. geometry.applyToMesh(mesh);
  34633. return geometry;
  34634. };
  34635. Object.defineProperty(Geometry.prototype, "extend", {
  34636. /**
  34637. * Gets the current extend of the geometry
  34638. */
  34639. get: function () {
  34640. return this._extend;
  34641. },
  34642. enumerable: true,
  34643. configurable: true
  34644. });
  34645. /**
  34646. * Gets the hosting scene
  34647. * @returns the hosting {BABYLON.Scene}
  34648. */
  34649. Geometry.prototype.getScene = function () {
  34650. return this._scene;
  34651. };
  34652. /**
  34653. * Gets the hosting engine
  34654. * @returns the hosting {BABYLON.Engine}
  34655. */
  34656. Geometry.prototype.getEngine = function () {
  34657. return this._engine;
  34658. };
  34659. /**
  34660. * Defines if the geometry is ready to use
  34661. * @returns true if the geometry is ready to be used
  34662. */
  34663. Geometry.prototype.isReady = function () {
  34664. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  34665. };
  34666. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  34667. /**
  34668. * Gets a value indicating that the geometry should not be serialized
  34669. */
  34670. get: function () {
  34671. for (var index = 0; index < this._meshes.length; index++) {
  34672. if (!this._meshes[index].doNotSerialize) {
  34673. return false;
  34674. }
  34675. }
  34676. return true;
  34677. },
  34678. enumerable: true,
  34679. configurable: true
  34680. });
  34681. /** @ignore */
  34682. Geometry.prototype._rebuild = function () {
  34683. if (this._vertexArrayObjects) {
  34684. this._vertexArrayObjects = {};
  34685. }
  34686. // Index buffer
  34687. if (this._meshes.length !== 0 && this._indices) {
  34688. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  34689. }
  34690. // Vertex buffers
  34691. for (var key in this._vertexBuffers) {
  34692. var vertexBuffer = this._vertexBuffers[key];
  34693. vertexBuffer._rebuild();
  34694. }
  34695. };
  34696. /**
  34697. * Affects all gemetry data in one call
  34698. * @param vertexData defines the geometry data
  34699. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  34700. */
  34701. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  34702. vertexData.applyToGeometry(this, updatable);
  34703. this.notifyUpdate();
  34704. };
  34705. /**
  34706. * Set specific vertex data
  34707. * @param kind defines the data kind (Position, normal, etc...)
  34708. * @param data defines the vertex data to use
  34709. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  34710. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  34711. */
  34712. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  34713. if (updatable === void 0) { updatable = false; }
  34714. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  34715. this.setVerticesBuffer(buffer);
  34716. };
  34717. /**
  34718. * Removes a specific vertex data
  34719. * @param kind defines the data kind (Position, normal, etc...)
  34720. */
  34721. Geometry.prototype.removeVerticesData = function (kind) {
  34722. if (this._vertexBuffers[kind]) {
  34723. this._vertexBuffers[kind].dispose();
  34724. delete this._vertexBuffers[kind];
  34725. }
  34726. };
  34727. /**
  34728. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  34729. * @param buffer defines the vertex buffer to use
  34730. */
  34731. Geometry.prototype.setVerticesBuffer = function (buffer) {
  34732. var kind = buffer.getKind();
  34733. if (this._vertexBuffers[kind]) {
  34734. this._vertexBuffers[kind].dispose();
  34735. }
  34736. this._vertexBuffers[kind] = buffer;
  34737. if (kind === BABYLON.VertexBuffer.PositionKind) {
  34738. var data = buffer.getData();
  34739. var stride = buffer.getStrideSize();
  34740. this._totalVertices = data.length / stride;
  34741. this.updateExtend(data, stride);
  34742. this._resetPointsArrayCache();
  34743. var meshes = this._meshes;
  34744. var numOfMeshes = meshes.length;
  34745. for (var index = 0; index < numOfMeshes; index++) {
  34746. var mesh = meshes[index];
  34747. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  34748. mesh._createGlobalSubMesh(false);
  34749. mesh.computeWorldMatrix(true);
  34750. }
  34751. }
  34752. this.notifyUpdate(kind);
  34753. if (this._vertexArrayObjects) {
  34754. this._disposeVertexArrayObjects();
  34755. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  34756. }
  34757. };
  34758. /**
  34759. * Update a specific vertex buffer
  34760. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  34761. * It will do nothing if the buffer is not updatable
  34762. * @param kind defines the data kind (Position, normal, etc...)
  34763. * @param data defines the data to use
  34764. * @param offset defines the offset in the target buffer where to store the data
  34765. */
  34766. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  34767. var vertexBuffer = this.getVertexBuffer(kind);
  34768. if (!vertexBuffer) {
  34769. return;
  34770. }
  34771. vertexBuffer.updateDirectly(data, offset);
  34772. this.notifyUpdate(kind);
  34773. };
  34774. /**
  34775. * Update a specific vertex buffer
  34776. * This function will create a new buffer if the current one is not updatable
  34777. * @param kind defines the data kind (Position, normal, etc...)
  34778. * @param data defines the data to use
  34779. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  34780. */
  34781. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  34782. if (updateExtends === void 0) { updateExtends = false; }
  34783. var vertexBuffer = this.getVertexBuffer(kind);
  34784. if (!vertexBuffer) {
  34785. return;
  34786. }
  34787. vertexBuffer.update(data);
  34788. if (kind === BABYLON.VertexBuffer.PositionKind) {
  34789. var stride = vertexBuffer.getStrideSize();
  34790. this._totalVertices = data.length / stride;
  34791. this.updateBoundingInfo(updateExtends, data);
  34792. }
  34793. this.notifyUpdate(kind);
  34794. };
  34795. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  34796. if (updateExtends) {
  34797. this.updateExtend(data);
  34798. }
  34799. var meshes = this._meshes;
  34800. var numOfMeshes = meshes.length;
  34801. this._resetPointsArrayCache();
  34802. for (var index = 0; index < numOfMeshes; index++) {
  34803. var mesh = meshes[index];
  34804. if (updateExtends) {
  34805. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  34806. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  34807. var subMesh = mesh.subMeshes[subIndex];
  34808. subMesh.refreshBoundingInfo();
  34809. }
  34810. }
  34811. }
  34812. };
  34813. /** @ignore */
  34814. Geometry.prototype._bind = function (effect, indexToBind) {
  34815. if (!effect) {
  34816. return;
  34817. }
  34818. if (indexToBind === undefined) {
  34819. indexToBind = this._indexBuffer;
  34820. }
  34821. var vbs = this.getVertexBuffers();
  34822. if (!vbs) {
  34823. return;
  34824. }
  34825. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  34826. this._engine.bindBuffers(vbs, indexToBind, effect);
  34827. return;
  34828. }
  34829. // Using VAO
  34830. if (!this._vertexArrayObjects[effect.key]) {
  34831. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  34832. }
  34833. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  34834. };
  34835. /**
  34836. * Gets total number of vertices
  34837. * @returns the total number of vertices
  34838. */
  34839. Geometry.prototype.getTotalVertices = function () {
  34840. if (!this.isReady()) {
  34841. return 0;
  34842. }
  34843. return this._totalVertices;
  34844. };
  34845. /**
  34846. * Gets a specific vertex data attached to this geometry
  34847. * @param kind defines the data kind (Position, normal, etc...)
  34848. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  34849. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  34850. * @returns a float array containing vertex data
  34851. */
  34852. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  34853. var vertexBuffer = this.getVertexBuffer(kind);
  34854. if (!vertexBuffer) {
  34855. return null;
  34856. }
  34857. var orig = vertexBuffer.getData();
  34858. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  34859. return orig;
  34860. }
  34861. else {
  34862. var len = orig.length;
  34863. var copy = [];
  34864. for (var i = 0; i < len; i++) {
  34865. copy.push(orig[i]);
  34866. }
  34867. return copy;
  34868. }
  34869. };
  34870. /**
  34871. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  34872. * @param kind defines the data kind (Position, normal, etc...)
  34873. * @returns true if the vertex buffer with the specified kind is updatable
  34874. */
  34875. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  34876. var vb = this._vertexBuffers[kind];
  34877. if (!vb) {
  34878. return false;
  34879. }
  34880. return vb.isUpdatable();
  34881. };
  34882. /**
  34883. * Gets a specific vertex buffer
  34884. * @param kind defines the data kind (Position, normal, etc...)
  34885. * @returns a {BABYLON.VertexBuffer}
  34886. */
  34887. Geometry.prototype.getVertexBuffer = function (kind) {
  34888. if (!this.isReady()) {
  34889. return null;
  34890. }
  34891. return this._vertexBuffers[kind];
  34892. };
  34893. /**
  34894. * Returns all vertex buffers
  34895. * @return an object holding all vertex buffers indexed by kind
  34896. */
  34897. Geometry.prototype.getVertexBuffers = function () {
  34898. if (!this.isReady()) {
  34899. return null;
  34900. }
  34901. return this._vertexBuffers;
  34902. };
  34903. /**
  34904. * Gets a boolean indicating if specific vertex buffer is present
  34905. * @param kind defines the data kind (Position, normal, etc...)
  34906. * @returns true if data is present
  34907. */
  34908. Geometry.prototype.isVerticesDataPresent = function (kind) {
  34909. if (!this._vertexBuffers) {
  34910. if (this._delayInfo) {
  34911. return this._delayInfo.indexOf(kind) !== -1;
  34912. }
  34913. return false;
  34914. }
  34915. return this._vertexBuffers[kind] !== undefined;
  34916. };
  34917. /**
  34918. * Gets a list of all attached data kinds (Position, normal, etc...)
  34919. * @returns a list of string containing all kinds
  34920. */
  34921. Geometry.prototype.getVerticesDataKinds = function () {
  34922. var result = [];
  34923. var kind;
  34924. if (!this._vertexBuffers && this._delayInfo) {
  34925. for (kind in this._delayInfo) {
  34926. result.push(kind);
  34927. }
  34928. }
  34929. else {
  34930. for (kind in this._vertexBuffers) {
  34931. result.push(kind);
  34932. }
  34933. }
  34934. return result;
  34935. };
  34936. /**
  34937. * Update index buffer
  34938. * @param indices defines the indices to store in the index buffer
  34939. * @param offset defines the offset in the target buffer where to store the data
  34940. */
  34941. Geometry.prototype.updateIndices = function (indices, offset) {
  34942. if (!this._indexBuffer) {
  34943. return;
  34944. }
  34945. if (!this._indexBufferIsUpdatable) {
  34946. this.setIndices(indices, null, true);
  34947. }
  34948. else {
  34949. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  34950. }
  34951. };
  34952. /**
  34953. * Creates a new index buffer
  34954. * @param indices defines the indices to store in the index buffer
  34955. * @param totalVertices defines the total number of vertices (could be null)
  34956. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  34957. */
  34958. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  34959. if (totalVertices === void 0) { totalVertices = null; }
  34960. if (updatable === void 0) { updatable = false; }
  34961. if (this._indexBuffer) {
  34962. this._engine._releaseBuffer(this._indexBuffer);
  34963. }
  34964. this._disposeVertexArrayObjects();
  34965. this._indices = indices;
  34966. this._indexBufferIsUpdatable = updatable;
  34967. if (this._meshes.length !== 0 && this._indices) {
  34968. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  34969. }
  34970. if (totalVertices != undefined) {
  34971. this._totalVertices = totalVertices;
  34972. }
  34973. var meshes = this._meshes;
  34974. var numOfMeshes = meshes.length;
  34975. for (var index = 0; index < numOfMeshes; index++) {
  34976. meshes[index]._createGlobalSubMesh(true);
  34977. }
  34978. this.notifyUpdate();
  34979. };
  34980. /**
  34981. * Return the total number of indices
  34982. * @returns the total number of indices
  34983. */
  34984. Geometry.prototype.getTotalIndices = function () {
  34985. if (!this.isReady()) {
  34986. return 0;
  34987. }
  34988. return this._indices.length;
  34989. };
  34990. /**
  34991. * Gets the index buffer array
  34992. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  34993. * @returns the index buffer array
  34994. */
  34995. Geometry.prototype.getIndices = function (copyWhenShared) {
  34996. if (!this.isReady()) {
  34997. return null;
  34998. }
  34999. var orig = this._indices;
  35000. if (!copyWhenShared || this._meshes.length === 1) {
  35001. return orig;
  35002. }
  35003. else {
  35004. var len = orig.length;
  35005. var copy = [];
  35006. for (var i = 0; i < len; i++) {
  35007. copy.push(orig[i]);
  35008. }
  35009. return copy;
  35010. }
  35011. };
  35012. /**
  35013. * Gets the index buffer
  35014. * @return the index buffer
  35015. */
  35016. Geometry.prototype.getIndexBuffer = function () {
  35017. if (!this.isReady()) {
  35018. return null;
  35019. }
  35020. return this._indexBuffer;
  35021. };
  35022. /** @ignore */
  35023. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  35024. if (effect === void 0) { effect = null; }
  35025. if (!effect || !this._vertexArrayObjects) {
  35026. return;
  35027. }
  35028. if (this._vertexArrayObjects[effect.key]) {
  35029. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  35030. delete this._vertexArrayObjects[effect.key];
  35031. }
  35032. };
  35033. /**
  35034. * Release the associated resources for a specific mesh
  35035. * @param mesh defines the source mesh
  35036. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  35037. */
  35038. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  35039. var meshes = this._meshes;
  35040. var index = meshes.indexOf(mesh);
  35041. if (index === -1) {
  35042. return;
  35043. }
  35044. meshes.splice(index, 1);
  35045. mesh._geometry = null;
  35046. if (meshes.length === 0 && shouldDispose) {
  35047. this.dispose();
  35048. }
  35049. };
  35050. /**
  35051. * Apply current geometry to a given mesh
  35052. * @param mesh defines the mesh to apply geometry to
  35053. */
  35054. Geometry.prototype.applyToMesh = function (mesh) {
  35055. if (mesh._geometry === this) {
  35056. return;
  35057. }
  35058. var previousGeometry = mesh._geometry;
  35059. if (previousGeometry) {
  35060. previousGeometry.releaseForMesh(mesh);
  35061. }
  35062. var meshes = this._meshes;
  35063. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  35064. mesh._geometry = this;
  35065. this._scene.pushGeometry(this);
  35066. meshes.push(mesh);
  35067. if (this.isReady()) {
  35068. this._applyToMesh(mesh);
  35069. }
  35070. else {
  35071. mesh._boundingInfo = this._boundingInfo;
  35072. }
  35073. };
  35074. Geometry.prototype.updateExtend = function (data, stride) {
  35075. if (data === void 0) { data = null; }
  35076. if (!data) {
  35077. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  35078. }
  35079. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  35080. };
  35081. Geometry.prototype._applyToMesh = function (mesh) {
  35082. var numOfMeshes = this._meshes.length;
  35083. // vertexBuffers
  35084. for (var kind in this._vertexBuffers) {
  35085. if (numOfMeshes === 1) {
  35086. this._vertexBuffers[kind].create();
  35087. }
  35088. var buffer = this._vertexBuffers[kind].getBuffer();
  35089. if (buffer)
  35090. buffer.references = numOfMeshes;
  35091. if (kind === BABYLON.VertexBuffer.PositionKind) {
  35092. if (!this._extend) {
  35093. this.updateExtend(this._vertexBuffers[kind].getData());
  35094. }
  35095. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  35096. mesh._createGlobalSubMesh(false);
  35097. //bounding info was just created again, world matrix should be applied again.
  35098. mesh._updateBoundingInfo();
  35099. }
  35100. }
  35101. // indexBuffer
  35102. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  35103. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  35104. }
  35105. if (this._indexBuffer) {
  35106. this._indexBuffer.references = numOfMeshes;
  35107. }
  35108. };
  35109. Geometry.prototype.notifyUpdate = function (kind) {
  35110. if (this.onGeometryUpdated) {
  35111. this.onGeometryUpdated(this, kind);
  35112. }
  35113. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  35114. var mesh = _a[_i];
  35115. mesh._markSubMeshesAsAttributesDirty();
  35116. }
  35117. };
  35118. /**
  35119. * Load the geometry if it was flagged as delay loaded
  35120. * @param scene defines the hosting scene
  35121. * @param onLoaded defines a callback called when the geometry is loaded
  35122. */
  35123. Geometry.prototype.load = function (scene, onLoaded) {
  35124. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  35125. return;
  35126. }
  35127. if (this.isReady()) {
  35128. if (onLoaded) {
  35129. onLoaded();
  35130. }
  35131. return;
  35132. }
  35133. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  35134. this._queueLoad(scene, onLoaded);
  35135. };
  35136. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  35137. var _this = this;
  35138. if (!this.delayLoadingFile) {
  35139. return;
  35140. }
  35141. scene._addPendingData(this);
  35142. scene._loadFile(this.delayLoadingFile, function (data) {
  35143. if (!_this._delayLoadingFunction) {
  35144. return;
  35145. }
  35146. _this._delayLoadingFunction(JSON.parse(data), _this);
  35147. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  35148. _this._delayInfo = [];
  35149. scene._removePendingData(_this);
  35150. var meshes = _this._meshes;
  35151. var numOfMeshes = meshes.length;
  35152. for (var index = 0; index < numOfMeshes; index++) {
  35153. _this._applyToMesh(meshes[index]);
  35154. }
  35155. if (onLoaded) {
  35156. onLoaded();
  35157. }
  35158. }, undefined, true);
  35159. };
  35160. /**
  35161. * Invert the geometry to move from a right handed system to a left handed one.
  35162. */
  35163. Geometry.prototype.toLeftHanded = function () {
  35164. // Flip faces
  35165. var tIndices = this.getIndices(false);
  35166. if (tIndices != null && tIndices.length > 0) {
  35167. for (var i = 0; i < tIndices.length; i += 3) {
  35168. var tTemp = tIndices[i + 0];
  35169. tIndices[i + 0] = tIndices[i + 2];
  35170. tIndices[i + 2] = tTemp;
  35171. }
  35172. this.setIndices(tIndices);
  35173. }
  35174. // Negate position.z
  35175. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  35176. if (tPositions != null && tPositions.length > 0) {
  35177. for (var i = 0; i < tPositions.length; i += 3) {
  35178. tPositions[i + 2] = -tPositions[i + 2];
  35179. }
  35180. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  35181. }
  35182. // Negate normal.z
  35183. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  35184. if (tNormals != null && tNormals.length > 0) {
  35185. for (var i = 0; i < tNormals.length; i += 3) {
  35186. tNormals[i + 2] = -tNormals[i + 2];
  35187. }
  35188. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  35189. }
  35190. };
  35191. // Cache
  35192. /** @ignore */
  35193. Geometry.prototype._resetPointsArrayCache = function () {
  35194. this._positions = null;
  35195. };
  35196. /** @ignore */
  35197. Geometry.prototype._generatePointsArray = function () {
  35198. if (this._positions)
  35199. return true;
  35200. this._positions = [];
  35201. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  35202. if (!data) {
  35203. return false;
  35204. }
  35205. for (var index = 0; index < data.length; index += 3) {
  35206. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  35207. }
  35208. return true;
  35209. };
  35210. /**
  35211. * Gets a value indicating if the geometry is disposed
  35212. * @returns true if the geometry was disposed
  35213. */
  35214. Geometry.prototype.isDisposed = function () {
  35215. return this._isDisposed;
  35216. };
  35217. Geometry.prototype._disposeVertexArrayObjects = function () {
  35218. if (this._vertexArrayObjects) {
  35219. for (var kind in this._vertexArrayObjects) {
  35220. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  35221. }
  35222. this._vertexArrayObjects = {};
  35223. }
  35224. };
  35225. /**
  35226. * Free all associated resources
  35227. */
  35228. Geometry.prototype.dispose = function () {
  35229. var meshes = this._meshes;
  35230. var numOfMeshes = meshes.length;
  35231. var index;
  35232. for (index = 0; index < numOfMeshes; index++) {
  35233. this.releaseForMesh(meshes[index]);
  35234. }
  35235. this._meshes = [];
  35236. this._disposeVertexArrayObjects();
  35237. for (var kind in this._vertexBuffers) {
  35238. this._vertexBuffers[kind].dispose();
  35239. }
  35240. this._vertexBuffers = {};
  35241. this._totalVertices = 0;
  35242. if (this._indexBuffer) {
  35243. this._engine._releaseBuffer(this._indexBuffer);
  35244. }
  35245. this._indexBuffer = null;
  35246. this._indices = [];
  35247. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  35248. this.delayLoadingFile = null;
  35249. this._delayLoadingFunction = null;
  35250. this._delayInfo = [];
  35251. this._boundingInfo = null;
  35252. this._scene.removeGeometry(this);
  35253. this._isDisposed = true;
  35254. };
  35255. /**
  35256. * Clone the current geometry into a new geometry
  35257. * @param id defines the unique ID of the new geometry
  35258. * @returns a new geometry object
  35259. */
  35260. Geometry.prototype.copy = function (id) {
  35261. var vertexData = new BABYLON.VertexData();
  35262. vertexData.indices = [];
  35263. var indices = this.getIndices();
  35264. if (indices) {
  35265. for (var index = 0; index < indices.length; index++) {
  35266. vertexData.indices.push(indices[index]);
  35267. }
  35268. }
  35269. var updatable = false;
  35270. var stopChecking = false;
  35271. var kind;
  35272. for (kind in this._vertexBuffers) {
  35273. // using slice() to make a copy of the array and not just reference it
  35274. var data = this.getVerticesData(kind);
  35275. if (data instanceof Float32Array) {
  35276. vertexData.set(new Float32Array(data), kind);
  35277. }
  35278. else {
  35279. vertexData.set(data.slice(0), kind);
  35280. }
  35281. if (!stopChecking) {
  35282. var vb = this.getVertexBuffer(kind);
  35283. if (vb) {
  35284. updatable = vb.isUpdatable();
  35285. stopChecking = !updatable;
  35286. }
  35287. }
  35288. }
  35289. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  35290. geometry.delayLoadState = this.delayLoadState;
  35291. geometry.delayLoadingFile = this.delayLoadingFile;
  35292. geometry._delayLoadingFunction = this._delayLoadingFunction;
  35293. for (kind in this._delayInfo) {
  35294. geometry._delayInfo = geometry._delayInfo || [];
  35295. geometry._delayInfo.push(kind);
  35296. }
  35297. // Bounding info
  35298. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  35299. return geometry;
  35300. };
  35301. /**
  35302. * Serialize the current geometry info (and not the vertices data) into a JSON object
  35303. * @return a JSON representation of the current geometry data (without the vertices data)
  35304. */
  35305. Geometry.prototype.serialize = function () {
  35306. var serializationObject = {};
  35307. serializationObject.id = this.id;
  35308. serializationObject.updatable = this._updatable;
  35309. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  35310. serializationObject.tags = BABYLON.Tags.GetTags(this);
  35311. }
  35312. return serializationObject;
  35313. };
  35314. Geometry.prototype.toNumberArray = function (origin) {
  35315. if (Array.isArray(origin)) {
  35316. return origin;
  35317. }
  35318. else {
  35319. return Array.prototype.slice.call(origin);
  35320. }
  35321. };
  35322. /**
  35323. * Serialize all vertices data into a JSON oject
  35324. * @returns a JSON representation of the current geometry data
  35325. */
  35326. Geometry.prototype.serializeVerticeData = function () {
  35327. var serializationObject = this.serialize();
  35328. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  35329. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  35330. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  35331. serializationObject.positions._updatable = true;
  35332. }
  35333. }
  35334. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  35335. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  35336. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  35337. serializationObject.normals._updatable = true;
  35338. }
  35339. }
  35340. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  35341. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  35342. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  35343. serializationObject.tangets._updatable = true;
  35344. }
  35345. }
  35346. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  35347. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  35348. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  35349. serializationObject.uvs._updatable = true;
  35350. }
  35351. }
  35352. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  35353. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  35354. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  35355. serializationObject.uv2s._updatable = true;
  35356. }
  35357. }
  35358. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  35359. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  35360. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  35361. serializationObject.uv3s._updatable = true;
  35362. }
  35363. }
  35364. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  35365. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  35366. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  35367. serializationObject.uv4s._updatable = true;
  35368. }
  35369. }
  35370. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  35371. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  35372. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  35373. serializationObject.uv5s._updatable = true;
  35374. }
  35375. }
  35376. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  35377. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  35378. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  35379. serializationObject.uv6s._updatable = true;
  35380. }
  35381. }
  35382. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  35383. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  35384. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  35385. serializationObject.colors._updatable = true;
  35386. }
  35387. }
  35388. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  35389. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  35390. serializationObject.matricesIndices._isExpanded = true;
  35391. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  35392. serializationObject.matricesIndices._updatable = true;
  35393. }
  35394. }
  35395. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  35396. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  35397. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  35398. serializationObject.matricesWeights._updatable = true;
  35399. }
  35400. }
  35401. serializationObject.indices = this.toNumberArray(this.getIndices());
  35402. return serializationObject;
  35403. };
  35404. // Statics
  35405. /**
  35406. * Extracts a clone of a mesh geometry
  35407. * @param mesh defines the source mesh
  35408. * @param id defines the unique ID of the new geometry object
  35409. * @returns the new geometry object
  35410. */
  35411. Geometry.ExtractFromMesh = function (mesh, id) {
  35412. var geometry = mesh._geometry;
  35413. if (!geometry) {
  35414. return null;
  35415. }
  35416. return geometry.copy(id);
  35417. };
  35418. /**
  35419. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  35420. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  35421. * Be aware Math.random() could cause collisions, but:
  35422. * "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"
  35423. * @returns a string containing a new GUID
  35424. */
  35425. Geometry.RandomId = function () {
  35426. return BABYLON.Tools.RandomId();
  35427. };
  35428. /** @ignore */
  35429. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  35430. var scene = mesh.getScene();
  35431. // Geometry
  35432. var geometryId = parsedGeometry.geometryId;
  35433. if (geometryId) {
  35434. var geometry = scene.getGeometryByID(geometryId);
  35435. if (geometry) {
  35436. geometry.applyToMesh(mesh);
  35437. }
  35438. }
  35439. else if (parsedGeometry instanceof ArrayBuffer) {
  35440. var binaryInfo = mesh._binaryInfo;
  35441. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  35442. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  35443. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  35444. }
  35445. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  35446. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  35447. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  35448. }
  35449. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  35450. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  35451. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  35452. }
  35453. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  35454. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  35455. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  35456. }
  35457. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  35458. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  35459. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  35460. }
  35461. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  35462. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  35463. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  35464. }
  35465. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  35466. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  35467. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  35468. }
  35469. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  35470. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  35471. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  35472. }
  35473. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  35474. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  35475. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  35476. }
  35477. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  35478. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  35479. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  35480. }
  35481. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  35482. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  35483. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  35484. }
  35485. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  35486. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  35487. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  35488. }
  35489. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  35490. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  35491. mesh.setIndices(indicesData, null);
  35492. }
  35493. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  35494. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  35495. mesh.subMeshes = [];
  35496. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  35497. var materialIndex = subMeshesData[(i * 5) + 0];
  35498. var verticesStart = subMeshesData[(i * 5) + 1];
  35499. var verticesCount = subMeshesData[(i * 5) + 2];
  35500. var indexStart = subMeshesData[(i * 5) + 3];
  35501. var indexCount = subMeshesData[(i * 5) + 4];
  35502. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  35503. }
  35504. }
  35505. }
  35506. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  35507. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  35508. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  35509. if (parsedGeometry.tangents) {
  35510. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  35511. }
  35512. if (parsedGeometry.uvs) {
  35513. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  35514. }
  35515. if (parsedGeometry.uvs2) {
  35516. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  35517. }
  35518. if (parsedGeometry.uvs3) {
  35519. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  35520. }
  35521. if (parsedGeometry.uvs4) {
  35522. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  35523. }
  35524. if (parsedGeometry.uvs5) {
  35525. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  35526. }
  35527. if (parsedGeometry.uvs6) {
  35528. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  35529. }
  35530. if (parsedGeometry.colors) {
  35531. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  35532. }
  35533. if (parsedGeometry.matricesIndices) {
  35534. if (!parsedGeometry.matricesIndices._isExpanded) {
  35535. var floatIndices = [];
  35536. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  35537. var matricesIndex = parsedGeometry.matricesIndices[i];
  35538. floatIndices.push(matricesIndex & 0x000000FF);
  35539. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  35540. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  35541. floatIndices.push(matricesIndex >> 24);
  35542. }
  35543. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  35544. }
  35545. else {
  35546. delete parsedGeometry.matricesIndices._isExpanded;
  35547. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  35548. }
  35549. }
  35550. if (parsedGeometry.matricesIndicesExtra) {
  35551. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  35552. var floatIndices = [];
  35553. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  35554. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  35555. floatIndices.push(matricesIndex & 0x000000FF);
  35556. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  35557. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  35558. floatIndices.push(matricesIndex >> 24);
  35559. }
  35560. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  35561. }
  35562. else {
  35563. delete parsedGeometry.matricesIndices._isExpanded;
  35564. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  35565. }
  35566. }
  35567. if (parsedGeometry.matricesWeights) {
  35568. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  35569. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  35570. }
  35571. if (parsedGeometry.matricesWeightsExtra) {
  35572. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  35573. }
  35574. mesh.setIndices(parsedGeometry.indices, null);
  35575. }
  35576. // SubMeshes
  35577. if (parsedGeometry.subMeshes) {
  35578. mesh.subMeshes = [];
  35579. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  35580. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  35581. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  35582. }
  35583. }
  35584. // Flat shading
  35585. if (mesh._shouldGenerateFlatShading) {
  35586. mesh.convertToFlatShadedMesh();
  35587. delete mesh._shouldGenerateFlatShading;
  35588. }
  35589. // Update
  35590. mesh.computeWorldMatrix(true);
  35591. // Octree
  35592. var sceneOctree = scene.selectionOctree;
  35593. if (sceneOctree !== undefined && sceneOctree !== null) {
  35594. sceneOctree.addMesh(mesh);
  35595. }
  35596. };
  35597. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  35598. var epsilon = 1e-3;
  35599. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  35600. return;
  35601. }
  35602. var noInfluenceBoneIndex = 0.0;
  35603. if (parsedGeometry.skeletonId > -1) {
  35604. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  35605. if (!skeleton) {
  35606. return;
  35607. }
  35608. noInfluenceBoneIndex = skeleton.bones.length;
  35609. }
  35610. else {
  35611. return;
  35612. }
  35613. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  35614. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  35615. var matricesWeights = parsedGeometry.matricesWeights;
  35616. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  35617. var influencers = parsedGeometry.numBoneInfluencer;
  35618. var size = matricesWeights.length;
  35619. for (var i = 0; i < size; i += 4) {
  35620. var weight = 0.0;
  35621. var firstZeroWeight = -1;
  35622. for (var j = 0; j < 4; j++) {
  35623. var w = matricesWeights[i + j];
  35624. weight += w;
  35625. if (w < epsilon && firstZeroWeight < 0) {
  35626. firstZeroWeight = j;
  35627. }
  35628. }
  35629. if (matricesWeightsExtra) {
  35630. for (var j = 0; j < 4; j++) {
  35631. var w = matricesWeightsExtra[i + j];
  35632. weight += w;
  35633. if (w < epsilon && firstZeroWeight < 0) {
  35634. firstZeroWeight = j + 4;
  35635. }
  35636. }
  35637. }
  35638. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  35639. firstZeroWeight = influencers - 1;
  35640. }
  35641. if (weight > epsilon) {
  35642. var mweight = 1.0 / weight;
  35643. for (var j = 0; j < 4; j++) {
  35644. matricesWeights[i + j] *= mweight;
  35645. }
  35646. if (matricesWeightsExtra) {
  35647. for (var j = 0; j < 4; j++) {
  35648. matricesWeightsExtra[i + j] *= mweight;
  35649. }
  35650. }
  35651. }
  35652. else {
  35653. if (firstZeroWeight >= 4) {
  35654. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  35655. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  35656. }
  35657. else {
  35658. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  35659. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  35660. }
  35661. }
  35662. }
  35663. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  35664. if (parsedGeometry.matricesWeightsExtra) {
  35665. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  35666. }
  35667. };
  35668. /**
  35669. * Create a new geometry from persisted data (Using .babylon file format)
  35670. * @param parsedVertexData defines the persisted data
  35671. * @param scene defines the hosting scene
  35672. * @param rootUrl defines the root url to use to load assets (like delayed data)
  35673. * @returns the new geometry object
  35674. */
  35675. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  35676. if (scene.getGeometryByID(parsedVertexData.id)) {
  35677. return null; // null since geometry could be something else than a box...
  35678. }
  35679. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  35680. if (BABYLON.Tags) {
  35681. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  35682. }
  35683. if (parsedVertexData.delayLoadingFile) {
  35684. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  35685. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  35686. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  35687. geometry._delayInfo = [];
  35688. if (parsedVertexData.hasUVs) {
  35689. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  35690. }
  35691. if (parsedVertexData.hasUVs2) {
  35692. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  35693. }
  35694. if (parsedVertexData.hasUVs3) {
  35695. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  35696. }
  35697. if (parsedVertexData.hasUVs4) {
  35698. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  35699. }
  35700. if (parsedVertexData.hasUVs5) {
  35701. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  35702. }
  35703. if (parsedVertexData.hasUVs6) {
  35704. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  35705. }
  35706. if (parsedVertexData.hasColors) {
  35707. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  35708. }
  35709. if (parsedVertexData.hasMatricesIndices) {
  35710. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  35711. }
  35712. if (parsedVertexData.hasMatricesWeights) {
  35713. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  35714. }
  35715. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  35716. }
  35717. else {
  35718. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  35719. }
  35720. scene.pushGeometry(geometry, true);
  35721. return geometry;
  35722. };
  35723. return Geometry;
  35724. }());
  35725. BABYLON.Geometry = Geometry;
  35726. // Primitives
  35727. /// Abstract class
  35728. /**
  35729. * Abstract class used to provide common services for all typed geometries
  35730. */
  35731. var _PrimitiveGeometry = /** @class */ (function (_super) {
  35732. __extends(_PrimitiveGeometry, _super);
  35733. /**
  35734. * Creates a new typed geometry
  35735. * @param id defines the unique ID of the geometry
  35736. * @param scene defines the hosting scene
  35737. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35738. * @param mesh defines the hosting mesh (can be null)
  35739. */
  35740. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  35741. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  35742. if (mesh === void 0) { mesh = null; }
  35743. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  35744. _this._canBeRegenerated = _canBeRegenerated;
  35745. _this._beingRegenerated = true;
  35746. _this.regenerate();
  35747. _this._beingRegenerated = false;
  35748. return _this;
  35749. }
  35750. /**
  35751. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  35752. * @returns true if the geometry can be regenerated
  35753. */
  35754. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  35755. return this._canBeRegenerated;
  35756. };
  35757. /**
  35758. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  35759. */
  35760. _PrimitiveGeometry.prototype.regenerate = function () {
  35761. if (!this._canBeRegenerated) {
  35762. return;
  35763. }
  35764. this._beingRegenerated = true;
  35765. this.setAllVerticesData(this._regenerateVertexData(), false);
  35766. this._beingRegenerated = false;
  35767. };
  35768. /**
  35769. * Clone the geometry
  35770. * @param id defines the unique ID of the new geometry
  35771. * @returns the new geometry
  35772. */
  35773. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  35774. return _super.prototype.copy.call(this, id);
  35775. };
  35776. // overrides
  35777. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  35778. if (!this._beingRegenerated) {
  35779. return;
  35780. }
  35781. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  35782. };
  35783. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  35784. if (!this._beingRegenerated) {
  35785. return;
  35786. }
  35787. _super.prototype.setVerticesData.call(this, kind, data, false);
  35788. };
  35789. // to override
  35790. /** @ignore */
  35791. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  35792. throw new Error("Abstract method");
  35793. };
  35794. _PrimitiveGeometry.prototype.copy = function (id) {
  35795. throw new Error("Must be overriden in sub-classes.");
  35796. };
  35797. _PrimitiveGeometry.prototype.serialize = function () {
  35798. var serializationObject = _super.prototype.serialize.call(this);
  35799. serializationObject.canBeRegenerated = this.canBeRegenerated();
  35800. return serializationObject;
  35801. };
  35802. return _PrimitiveGeometry;
  35803. }(Geometry));
  35804. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  35805. /**
  35806. * Creates a ribbon geometry
  35807. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  35808. */
  35809. var RibbonGeometry = /** @class */ (function (_super) {
  35810. __extends(RibbonGeometry, _super);
  35811. /**
  35812. * Creates a ribbon geometry
  35813. * @param id defines the unique ID of the geometry
  35814. * @param scene defines the hosting scene
  35815. * @param pathArray defines the array of paths to use
  35816. * @param closeArray defines if the last path and the first path must be joined
  35817. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  35818. * @param offset defines the offset between points
  35819. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35820. * @param mesh defines the hosting mesh (can be null)
  35821. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35822. */
  35823. function RibbonGeometry(id, scene,
  35824. /**
  35825. * Defines the array of paths to use
  35826. */
  35827. pathArray,
  35828. /**
  35829. * Defines if the last and first points of each path in your pathArray must be joined
  35830. */
  35831. closeArray,
  35832. /**
  35833. * Defines if the last and first points of each path in your pathArray must be joined
  35834. */
  35835. closePath,
  35836. /**
  35837. * Defines the offset between points
  35838. */
  35839. offset, canBeRegenerated, mesh,
  35840. /**
  35841. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35842. */
  35843. side) {
  35844. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35845. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35846. _this.pathArray = pathArray;
  35847. _this.closeArray = closeArray;
  35848. _this.closePath = closePath;
  35849. _this.offset = offset;
  35850. _this.side = side;
  35851. return _this;
  35852. }
  35853. /** @ignore */
  35854. RibbonGeometry.prototype._regenerateVertexData = function () {
  35855. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  35856. };
  35857. RibbonGeometry.prototype.copy = function (id) {
  35858. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  35859. };
  35860. return RibbonGeometry;
  35861. }(_PrimitiveGeometry));
  35862. BABYLON.RibbonGeometry = RibbonGeometry;
  35863. /**
  35864. * Creates a box geometry
  35865. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  35866. */
  35867. var BoxGeometry = /** @class */ (function (_super) {
  35868. __extends(BoxGeometry, _super);
  35869. /**
  35870. * Creates a box geometry
  35871. * @param id defines the unique ID of the geometry
  35872. * @param scene defines the hosting scene
  35873. * @param size defines the zise of the box (width, height and depth are the same)
  35874. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35875. * @param mesh defines the hosting mesh (can be null)
  35876. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35877. */
  35878. function BoxGeometry(id, scene,
  35879. /**
  35880. * Defines the zise of the box (width, height and depth are the same)
  35881. */
  35882. size, canBeRegenerated, mesh,
  35883. /**
  35884. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35885. */
  35886. side) {
  35887. if (mesh === void 0) { mesh = null; }
  35888. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35889. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35890. _this.size = size;
  35891. _this.side = side;
  35892. return _this;
  35893. }
  35894. BoxGeometry.prototype._regenerateVertexData = function () {
  35895. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  35896. };
  35897. BoxGeometry.prototype.copy = function (id) {
  35898. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  35899. };
  35900. BoxGeometry.prototype.serialize = function () {
  35901. var serializationObject = _super.prototype.serialize.call(this);
  35902. serializationObject.size = this.size;
  35903. return serializationObject;
  35904. };
  35905. BoxGeometry.Parse = function (parsedBox, scene) {
  35906. if (scene.getGeometryByID(parsedBox.id)) {
  35907. return null; // null since geometry could be something else than a box...
  35908. }
  35909. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  35910. if (BABYLON.Tags) {
  35911. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  35912. }
  35913. scene.pushGeometry(box, true);
  35914. return box;
  35915. };
  35916. return BoxGeometry;
  35917. }(_PrimitiveGeometry));
  35918. BABYLON.BoxGeometry = BoxGeometry;
  35919. /**
  35920. * Creates a sphere geometry
  35921. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  35922. */
  35923. var SphereGeometry = /** @class */ (function (_super) {
  35924. __extends(SphereGeometry, _super);
  35925. /**
  35926. * Create a new sphere geometry
  35927. * @param id defines the unique ID of the geometry
  35928. * @param scene defines the hosting scene
  35929. * @param segments defines the number of segments to use to create the sphere
  35930. * @param diameter defines the diameter of the sphere
  35931. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35932. * @param mesh defines the hosting mesh (can be null)
  35933. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35934. */
  35935. function SphereGeometry(id, scene,
  35936. /**
  35937. * Defines the number of segments to use to create the sphere
  35938. */
  35939. segments,
  35940. /**
  35941. * Defines the diameter of the sphere
  35942. */
  35943. diameter, canBeRegenerated, mesh,
  35944. /**
  35945. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35946. */
  35947. side) {
  35948. if (mesh === void 0) { mesh = null; }
  35949. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35950. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35951. _this.segments = segments;
  35952. _this.diameter = diameter;
  35953. _this.side = side;
  35954. return _this;
  35955. }
  35956. SphereGeometry.prototype._regenerateVertexData = function () {
  35957. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  35958. };
  35959. SphereGeometry.prototype.copy = function (id) {
  35960. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  35961. };
  35962. SphereGeometry.prototype.serialize = function () {
  35963. var serializationObject = _super.prototype.serialize.call(this);
  35964. serializationObject.segments = this.segments;
  35965. serializationObject.diameter = this.diameter;
  35966. return serializationObject;
  35967. };
  35968. SphereGeometry.Parse = function (parsedSphere, scene) {
  35969. if (scene.getGeometryByID(parsedSphere.id)) {
  35970. return null; // null since geometry could be something else than a sphere...
  35971. }
  35972. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  35973. if (BABYLON.Tags) {
  35974. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  35975. }
  35976. scene.pushGeometry(sphere, true);
  35977. return sphere;
  35978. };
  35979. return SphereGeometry;
  35980. }(_PrimitiveGeometry));
  35981. BABYLON.SphereGeometry = SphereGeometry;
  35982. /**
  35983. * Creates a disc geometry
  35984. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  35985. */
  35986. var DiscGeometry = /** @class */ (function (_super) {
  35987. __extends(DiscGeometry, _super);
  35988. /**
  35989. * Creates a new disc geometry
  35990. * @param id defines the unique ID of the geometry
  35991. * @param scene defines the hosting scene
  35992. * @param radius defines the radius of the disc
  35993. * @param tessellation defines the tesselation factor to apply to the disc
  35994. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35995. * @param mesh defines the hosting mesh (can be null)
  35996. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35997. */
  35998. function DiscGeometry(id, scene,
  35999. /**
  36000. * Defines the radius of the disc
  36001. */
  36002. radius,
  36003. /**
  36004. * Defines the tesselation factor to apply to the disc
  36005. */
  36006. tessellation, canBeRegenerated, mesh,
  36007. /**
  36008. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36009. */
  36010. side) {
  36011. if (mesh === void 0) { mesh = null; }
  36012. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36013. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36014. _this.radius = radius;
  36015. _this.tessellation = tessellation;
  36016. _this.side = side;
  36017. return _this;
  36018. }
  36019. DiscGeometry.prototype._regenerateVertexData = function () {
  36020. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  36021. };
  36022. DiscGeometry.prototype.copy = function (id) {
  36023. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  36024. };
  36025. return DiscGeometry;
  36026. }(_PrimitiveGeometry));
  36027. BABYLON.DiscGeometry = DiscGeometry;
  36028. /**
  36029. * Creates a new cylinder geometry
  36030. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  36031. */
  36032. var CylinderGeometry = /** @class */ (function (_super) {
  36033. __extends(CylinderGeometry, _super);
  36034. /**
  36035. * Creates a new cylinder geometry
  36036. * @param id defines the unique ID of the geometry
  36037. * @param scene defines the hosting scene
  36038. * @param height defines the height of the cylinder
  36039. * @param diameterTop defines the diameter of the cylinder's top cap
  36040. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  36041. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  36042. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  36043. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36044. * @param mesh defines the hosting mesh (can be null)
  36045. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36046. */
  36047. function CylinderGeometry(id, scene,
  36048. /**
  36049. * Defines the height of the cylinder
  36050. */
  36051. height,
  36052. /**
  36053. * Defines the diameter of the cylinder's top cap
  36054. */
  36055. diameterTop,
  36056. /**
  36057. * Defines the diameter of the cylinder's bottom cap
  36058. */
  36059. diameterBottom,
  36060. /**
  36061. * Defines the tessellation factor to apply to the cylinder
  36062. */
  36063. tessellation,
  36064. /**
  36065. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  36066. */
  36067. subdivisions, canBeRegenerated, mesh,
  36068. /**
  36069. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36070. */
  36071. side) {
  36072. if (subdivisions === void 0) { subdivisions = 1; }
  36073. if (mesh === void 0) { mesh = null; }
  36074. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36075. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36076. _this.height = height;
  36077. _this.diameterTop = diameterTop;
  36078. _this.diameterBottom = diameterBottom;
  36079. _this.tessellation = tessellation;
  36080. _this.subdivisions = subdivisions;
  36081. _this.side = side;
  36082. return _this;
  36083. }
  36084. CylinderGeometry.prototype._regenerateVertexData = function () {
  36085. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  36086. };
  36087. CylinderGeometry.prototype.copy = function (id) {
  36088. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  36089. };
  36090. CylinderGeometry.prototype.serialize = function () {
  36091. var serializationObject = _super.prototype.serialize.call(this);
  36092. serializationObject.height = this.height;
  36093. serializationObject.diameterTop = this.diameterTop;
  36094. serializationObject.diameterBottom = this.diameterBottom;
  36095. serializationObject.tessellation = this.tessellation;
  36096. return serializationObject;
  36097. };
  36098. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  36099. if (scene.getGeometryByID(parsedCylinder.id)) {
  36100. return null; // null since geometry could be something else than a cylinder...
  36101. }
  36102. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  36103. if (BABYLON.Tags) {
  36104. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  36105. }
  36106. scene.pushGeometry(cylinder, true);
  36107. return cylinder;
  36108. };
  36109. return CylinderGeometry;
  36110. }(_PrimitiveGeometry));
  36111. BABYLON.CylinderGeometry = CylinderGeometry;
  36112. /**
  36113. * Creates a new torus geometry
  36114. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  36115. */
  36116. var TorusGeometry = /** @class */ (function (_super) {
  36117. __extends(TorusGeometry, _super);
  36118. /**
  36119. * Creates a new torus geometry
  36120. * @param id defines the unique ID of the geometry
  36121. * @param scene defines the hosting scene
  36122. * @param diameter defines the diameter of the torus
  36123. * @param thickness defines the thickness of the torus (ie. internal diameter)
  36124. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  36125. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36126. * @param mesh defines the hosting mesh (can be null)
  36127. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36128. */
  36129. function TorusGeometry(id, scene,
  36130. /**
  36131. * Defines the diameter of the torus
  36132. */
  36133. diameter,
  36134. /**
  36135. * Defines the thickness of the torus (ie. internal diameter)
  36136. */
  36137. thickness,
  36138. /**
  36139. * Defines the tesselation factor to apply to the torus
  36140. */
  36141. tessellation, canBeRegenerated, mesh,
  36142. /**
  36143. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36144. */
  36145. side) {
  36146. if (mesh === void 0) { mesh = null; }
  36147. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36148. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36149. _this.diameter = diameter;
  36150. _this.thickness = thickness;
  36151. _this.tessellation = tessellation;
  36152. _this.side = side;
  36153. return _this;
  36154. }
  36155. TorusGeometry.prototype._regenerateVertexData = function () {
  36156. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  36157. };
  36158. TorusGeometry.prototype.copy = function (id) {
  36159. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  36160. };
  36161. TorusGeometry.prototype.serialize = function () {
  36162. var serializationObject = _super.prototype.serialize.call(this);
  36163. serializationObject.diameter = this.diameter;
  36164. serializationObject.thickness = this.thickness;
  36165. serializationObject.tessellation = this.tessellation;
  36166. return serializationObject;
  36167. };
  36168. TorusGeometry.Parse = function (parsedTorus, scene) {
  36169. if (scene.getGeometryByID(parsedTorus.id)) {
  36170. return null; // null since geometry could be something else than a torus...
  36171. }
  36172. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  36173. if (BABYLON.Tags) {
  36174. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  36175. }
  36176. scene.pushGeometry(torus, true);
  36177. return torus;
  36178. };
  36179. return TorusGeometry;
  36180. }(_PrimitiveGeometry));
  36181. BABYLON.TorusGeometry = TorusGeometry;
  36182. /**
  36183. * Creates a new ground geometry
  36184. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  36185. */
  36186. var GroundGeometry = /** @class */ (function (_super) {
  36187. __extends(GroundGeometry, _super);
  36188. /**
  36189. * Creates a new ground geometry
  36190. * @param id defines the unique ID of the geometry
  36191. * @param scene defines the hosting scene
  36192. * @param width defines the width of the ground
  36193. * @param height defines the height of the ground
  36194. * @param subdivisions defines the subdivisions to apply to the ground
  36195. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36196. * @param mesh defines the hosting mesh (can be null)
  36197. */
  36198. function GroundGeometry(id, scene,
  36199. /**
  36200. * Defines the width of the ground
  36201. */
  36202. width,
  36203. /**
  36204. * Defines the height of the ground
  36205. */
  36206. height,
  36207. /**
  36208. * Defines the subdivisions to apply to the ground
  36209. */
  36210. subdivisions, canBeRegenerated, mesh) {
  36211. if (mesh === void 0) { mesh = null; }
  36212. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36213. _this.width = width;
  36214. _this.height = height;
  36215. _this.subdivisions = subdivisions;
  36216. return _this;
  36217. }
  36218. GroundGeometry.prototype._regenerateVertexData = function () {
  36219. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  36220. };
  36221. GroundGeometry.prototype.copy = function (id) {
  36222. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  36223. };
  36224. GroundGeometry.prototype.serialize = function () {
  36225. var serializationObject = _super.prototype.serialize.call(this);
  36226. serializationObject.width = this.width;
  36227. serializationObject.height = this.height;
  36228. serializationObject.subdivisions = this.subdivisions;
  36229. return serializationObject;
  36230. };
  36231. GroundGeometry.Parse = function (parsedGround, scene) {
  36232. if (scene.getGeometryByID(parsedGround.id)) {
  36233. return null; // null since geometry could be something else than a ground...
  36234. }
  36235. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  36236. if (BABYLON.Tags) {
  36237. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  36238. }
  36239. scene.pushGeometry(ground, true);
  36240. return ground;
  36241. };
  36242. return GroundGeometry;
  36243. }(_PrimitiveGeometry));
  36244. BABYLON.GroundGeometry = GroundGeometry;
  36245. /**
  36246. * Creates a tiled ground geometry
  36247. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  36248. */
  36249. var TiledGroundGeometry = /** @class */ (function (_super) {
  36250. __extends(TiledGroundGeometry, _super);
  36251. /**
  36252. * Creates a tiled ground geometry
  36253. * @param id defines the unique ID of the geometry
  36254. * @param scene defines the hosting scene
  36255. * @param xmin defines the minimum value on X axis
  36256. * @param zmin defines the minimum value on Z axis
  36257. * @param xmax defines the maximum value on X axis
  36258. * @param zmax defines the maximum value on Z axis
  36259. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  36260. * @param precision defines the precision to use when computing the tiles
  36261. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36262. * @param mesh defines the hosting mesh (can be null)
  36263. */
  36264. function TiledGroundGeometry(id, scene,
  36265. /**
  36266. * Defines the minimum value on X axis
  36267. */
  36268. xmin,
  36269. /**
  36270. * Defines the minimum value on Z axis
  36271. */
  36272. zmin,
  36273. /**
  36274. * Defines the maximum value on X axis
  36275. */
  36276. xmax,
  36277. /**
  36278. * Defines the maximum value on Z axis
  36279. */
  36280. zmax,
  36281. /**
  36282. * Defines the subdivisions to apply to the ground
  36283. */
  36284. subdivisions,
  36285. /**
  36286. * Defines the precision to use when computing the tiles
  36287. */
  36288. precision, canBeRegenerated, mesh) {
  36289. if (mesh === void 0) { mesh = null; }
  36290. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36291. _this.xmin = xmin;
  36292. _this.zmin = zmin;
  36293. _this.xmax = xmax;
  36294. _this.zmax = zmax;
  36295. _this.subdivisions = subdivisions;
  36296. _this.precision = precision;
  36297. return _this;
  36298. }
  36299. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  36300. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  36301. };
  36302. TiledGroundGeometry.prototype.copy = function (id) {
  36303. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  36304. };
  36305. return TiledGroundGeometry;
  36306. }(_PrimitiveGeometry));
  36307. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  36308. /**
  36309. * Creates a plane geometry
  36310. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  36311. */
  36312. var PlaneGeometry = /** @class */ (function (_super) {
  36313. __extends(PlaneGeometry, _super);
  36314. /**
  36315. * Creates a plane geometry
  36316. * @param id defines the unique ID of the geometry
  36317. * @param scene defines the hosting scene
  36318. * @param size defines the size of the plane (width === height)
  36319. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36320. * @param mesh defines the hosting mesh (can be null)
  36321. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36322. */
  36323. function PlaneGeometry(id, scene,
  36324. /**
  36325. * Defines the size of the plane (width === height)
  36326. */
  36327. size, canBeRegenerated, mesh,
  36328. /**
  36329. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36330. */
  36331. side) {
  36332. if (mesh === void 0) { mesh = null; }
  36333. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36334. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36335. _this.size = size;
  36336. _this.side = side;
  36337. return _this;
  36338. }
  36339. PlaneGeometry.prototype._regenerateVertexData = function () {
  36340. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  36341. };
  36342. PlaneGeometry.prototype.copy = function (id) {
  36343. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  36344. };
  36345. PlaneGeometry.prototype.serialize = function () {
  36346. var serializationObject = _super.prototype.serialize.call(this);
  36347. serializationObject.size = this.size;
  36348. return serializationObject;
  36349. };
  36350. PlaneGeometry.Parse = function (parsedPlane, scene) {
  36351. if (scene.getGeometryByID(parsedPlane.id)) {
  36352. return null; // null since geometry could be something else than a ground...
  36353. }
  36354. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  36355. if (BABYLON.Tags) {
  36356. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  36357. }
  36358. scene.pushGeometry(plane, true);
  36359. return plane;
  36360. };
  36361. return PlaneGeometry;
  36362. }(_PrimitiveGeometry));
  36363. BABYLON.PlaneGeometry = PlaneGeometry;
  36364. /**
  36365. * Creates a torus knot geometry
  36366. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  36367. */
  36368. var TorusKnotGeometry = /** @class */ (function (_super) {
  36369. __extends(TorusKnotGeometry, _super);
  36370. /**
  36371. * Creates a torus knot geometry
  36372. * @param id defines the unique ID of the geometry
  36373. * @param scene defines the hosting scene
  36374. * @param radius defines the radius of the torus knot
  36375. * @param tube defines the thickness of the torus knot tube
  36376. * @param radialSegments defines the number of radial segments
  36377. * @param tubularSegments defines the number of tubular segments
  36378. * @param p defines the first number of windings
  36379. * @param q defines the second number of windings
  36380. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36381. * @param mesh defines the hosting mesh (can be null)
  36382. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36383. */
  36384. function TorusKnotGeometry(id, scene,
  36385. /**
  36386. * Defines the radius of the torus knot
  36387. */
  36388. radius,
  36389. /**
  36390. * Defines the thickness of the torus knot tube
  36391. */
  36392. tube,
  36393. /**
  36394. * Defines the number of radial segments
  36395. */
  36396. radialSegments,
  36397. /**
  36398. * Defines the number of tubular segments
  36399. */
  36400. tubularSegments,
  36401. /**
  36402. * Defines the first number of windings
  36403. */
  36404. p,
  36405. /**
  36406. * Defines the second number of windings
  36407. */
  36408. q, canBeRegenerated, mesh,
  36409. /**
  36410. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36411. */
  36412. side) {
  36413. if (mesh === void 0) { mesh = null; }
  36414. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36415. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36416. _this.radius = radius;
  36417. _this.tube = tube;
  36418. _this.radialSegments = radialSegments;
  36419. _this.tubularSegments = tubularSegments;
  36420. _this.p = p;
  36421. _this.q = q;
  36422. _this.side = side;
  36423. return _this;
  36424. }
  36425. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  36426. 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 });
  36427. };
  36428. TorusKnotGeometry.prototype.copy = function (id) {
  36429. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  36430. };
  36431. TorusKnotGeometry.prototype.serialize = function () {
  36432. var serializationObject = _super.prototype.serialize.call(this);
  36433. serializationObject.radius = this.radius;
  36434. serializationObject.tube = this.tube;
  36435. serializationObject.radialSegments = this.radialSegments;
  36436. serializationObject.tubularSegments = this.tubularSegments;
  36437. serializationObject.p = this.p;
  36438. serializationObject.q = this.q;
  36439. return serializationObject;
  36440. };
  36441. ;
  36442. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  36443. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  36444. return null; // null since geometry could be something else than a ground...
  36445. }
  36446. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  36447. if (BABYLON.Tags) {
  36448. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  36449. }
  36450. scene.pushGeometry(torusKnot, true);
  36451. return torusKnot;
  36452. };
  36453. return TorusKnotGeometry;
  36454. }(_PrimitiveGeometry));
  36455. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  36456. //}
  36457. })(BABYLON || (BABYLON = {}));
  36458. //# sourceMappingURL=babylon.geometry.js.map
  36459. var BABYLON;
  36460. (function (BABYLON) {
  36461. /**
  36462. * PostProcessManager is used to manage one or more post processes or post process pipelines
  36463. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  36464. */
  36465. var PostProcessManager = /** @class */ (function () {
  36466. /**
  36467. * Creates a new instance of @see PostProcess
  36468. * @param scene The scene that the post process is associated with.
  36469. */
  36470. function PostProcessManager(scene) {
  36471. this._vertexBuffers = {};
  36472. this._scene = scene;
  36473. }
  36474. PostProcessManager.prototype._prepareBuffers = function () {
  36475. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  36476. return;
  36477. }
  36478. // VBO
  36479. var vertices = [];
  36480. vertices.push(1, 1);
  36481. vertices.push(-1, 1);
  36482. vertices.push(-1, -1);
  36483. vertices.push(1, -1);
  36484. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  36485. this._buildIndexBuffer();
  36486. };
  36487. PostProcessManager.prototype._buildIndexBuffer = function () {
  36488. // Indices
  36489. var indices = [];
  36490. indices.push(0);
  36491. indices.push(1);
  36492. indices.push(2);
  36493. indices.push(0);
  36494. indices.push(2);
  36495. indices.push(3);
  36496. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  36497. };
  36498. /**
  36499. * Rebuilds the vertex buffers of the manager.
  36500. */
  36501. PostProcessManager.prototype._rebuild = function () {
  36502. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  36503. if (!vb) {
  36504. return;
  36505. }
  36506. vb._rebuild();
  36507. this._buildIndexBuffer();
  36508. };
  36509. // Methods
  36510. /**
  36511. * Prepares a frame to be run through a post process.
  36512. * @param sourceTexture The input texture to the post procesess. (default: null)
  36513. * @param postProcesses An array of post processes to be run. (default: null)
  36514. * @returns True if the post processes were able to be run.
  36515. */
  36516. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  36517. if (sourceTexture === void 0) { sourceTexture = null; }
  36518. if (postProcesses === void 0) { postProcesses = null; }
  36519. var camera = this._scene.activeCamera;
  36520. if (!camera) {
  36521. return false;
  36522. }
  36523. var postProcesses = postProcesses || camera._postProcesses;
  36524. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  36525. return false;
  36526. }
  36527. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  36528. return true;
  36529. };
  36530. /**
  36531. * Manually render a set of post processes to a texture.
  36532. * @param postProcesses An array of post processes to be run.
  36533. * @param targetTexture The target texture to render to.
  36534. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  36535. */
  36536. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  36537. if (targetTexture === void 0) { targetTexture = null; }
  36538. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  36539. var engine = this._scene.getEngine();
  36540. for (var index = 0; index < postProcesses.length; index++) {
  36541. if (index < postProcesses.length - 1) {
  36542. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  36543. }
  36544. else {
  36545. if (targetTexture) {
  36546. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  36547. }
  36548. else {
  36549. engine.restoreDefaultFramebuffer();
  36550. }
  36551. }
  36552. var pp = postProcesses[index];
  36553. var effect = pp.apply();
  36554. if (effect) {
  36555. pp.onBeforeRenderObservable.notifyObservers(effect);
  36556. // VBOs
  36557. this._prepareBuffers();
  36558. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  36559. // Draw order
  36560. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  36561. pp.onAfterRenderObservable.notifyObservers(effect);
  36562. }
  36563. }
  36564. // Restore depth buffer
  36565. engine.setDepthBuffer(true);
  36566. engine.setDepthWrite(true);
  36567. };
  36568. /**
  36569. * Finalize the result of the output of the postprocesses.
  36570. * @param doNotPresent If true the result will not be displayed to the screen.
  36571. * @param targetTexture The target texture to render to.
  36572. * @param faceIndex The index of the face to bind the target texture to.
  36573. * @param postProcesses The array of post processes to render.
  36574. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  36575. */
  36576. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  36577. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  36578. var camera = this._scene.activeCamera;
  36579. if (!camera) {
  36580. return;
  36581. }
  36582. postProcesses = postProcesses || camera._postProcesses;
  36583. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  36584. return;
  36585. }
  36586. var engine = this._scene.getEngine();
  36587. for (var index = 0, len = postProcesses.length; index < len; index++) {
  36588. if (index < len - 1) {
  36589. postProcesses[index + 1].activate(camera, targetTexture);
  36590. }
  36591. else {
  36592. if (targetTexture) {
  36593. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  36594. }
  36595. else {
  36596. engine.restoreDefaultFramebuffer();
  36597. }
  36598. }
  36599. if (doNotPresent) {
  36600. break;
  36601. }
  36602. var pp = postProcesses[index];
  36603. var effect = pp.apply();
  36604. if (effect) {
  36605. pp.onBeforeRenderObservable.notifyObservers(effect);
  36606. // VBOs
  36607. this._prepareBuffers();
  36608. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  36609. // Draw order
  36610. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  36611. pp.onAfterRenderObservable.notifyObservers(effect);
  36612. }
  36613. }
  36614. // Restore states
  36615. engine.setDepthBuffer(true);
  36616. engine.setDepthWrite(true);
  36617. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  36618. };
  36619. /**
  36620. * Disposes of the post process manager.
  36621. */
  36622. PostProcessManager.prototype.dispose = function () {
  36623. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  36624. if (buffer) {
  36625. buffer.dispose();
  36626. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  36627. }
  36628. if (this._indexBuffer) {
  36629. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  36630. this._indexBuffer = null;
  36631. }
  36632. };
  36633. return PostProcessManager;
  36634. }());
  36635. BABYLON.PostProcessManager = PostProcessManager;
  36636. })(BABYLON || (BABYLON = {}));
  36637. //# sourceMappingURL=babylon.postProcessManager.js.map
  36638. var BABYLON;
  36639. (function (BABYLON) {
  36640. /**
  36641. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  36642. */
  36643. var PerformanceMonitor = /** @class */ (function () {
  36644. /**
  36645. * constructor
  36646. * @param frameSampleSize The number of samples required to saturate the sliding window
  36647. */
  36648. function PerformanceMonitor(frameSampleSize) {
  36649. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  36650. this._enabled = true;
  36651. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  36652. }
  36653. /**
  36654. * Samples current frame
  36655. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  36656. */
  36657. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  36658. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  36659. if (!this._enabled)
  36660. return;
  36661. if (this._lastFrameTimeMs != null) {
  36662. var dt = timeMs - this._lastFrameTimeMs;
  36663. this._rollingFrameTime.add(dt);
  36664. }
  36665. this._lastFrameTimeMs = timeMs;
  36666. };
  36667. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  36668. /**
  36669. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  36670. * @return Average frame time in milliseconds
  36671. */
  36672. get: function () {
  36673. return this._rollingFrameTime.average;
  36674. },
  36675. enumerable: true,
  36676. configurable: true
  36677. });
  36678. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  36679. /**
  36680. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  36681. * @return Frame time variance in milliseconds squared
  36682. */
  36683. get: function () {
  36684. return this._rollingFrameTime.variance;
  36685. },
  36686. enumerable: true,
  36687. configurable: true
  36688. });
  36689. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  36690. /**
  36691. * Returns the frame time of the most recent frame
  36692. * @return Frame time in milliseconds
  36693. */
  36694. get: function () {
  36695. return this._rollingFrameTime.history(0);
  36696. },
  36697. enumerable: true,
  36698. configurable: true
  36699. });
  36700. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  36701. /**
  36702. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  36703. * @return Framerate in frames per second
  36704. */
  36705. get: function () {
  36706. return 1000.0 / this._rollingFrameTime.average;
  36707. },
  36708. enumerable: true,
  36709. configurable: true
  36710. });
  36711. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  36712. /**
  36713. * Returns the average framerate in frames per second using the most recent frame time
  36714. * @return Framerate in frames per second
  36715. */
  36716. get: function () {
  36717. var history = this._rollingFrameTime.history(0);
  36718. if (history === 0) {
  36719. return 0;
  36720. }
  36721. return 1000.0 / history;
  36722. },
  36723. enumerable: true,
  36724. configurable: true
  36725. });
  36726. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  36727. /**
  36728. * Returns true if enough samples have been taken to completely fill the sliding window
  36729. * @return true if saturated
  36730. */
  36731. get: function () {
  36732. return this._rollingFrameTime.isSaturated();
  36733. },
  36734. enumerable: true,
  36735. configurable: true
  36736. });
  36737. /**
  36738. * Enables contributions to the sliding window sample set
  36739. */
  36740. PerformanceMonitor.prototype.enable = function () {
  36741. this._enabled = true;
  36742. };
  36743. /**
  36744. * Disables contributions to the sliding window sample set
  36745. * Samples will not be interpolated over the disabled period
  36746. */
  36747. PerformanceMonitor.prototype.disable = function () {
  36748. this._enabled = false;
  36749. //clear last sample to avoid interpolating over the disabled period when next enabled
  36750. this._lastFrameTimeMs = null;
  36751. };
  36752. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  36753. /**
  36754. * Returns true if sampling is enabled
  36755. * @return true if enabled
  36756. */
  36757. get: function () {
  36758. return this._enabled;
  36759. },
  36760. enumerable: true,
  36761. configurable: true
  36762. });
  36763. /**
  36764. * Resets performance monitor
  36765. */
  36766. PerformanceMonitor.prototype.reset = function () {
  36767. //clear last sample to avoid interpolating over the disabled period when next enabled
  36768. this._lastFrameTimeMs = null;
  36769. //wipe record
  36770. this._rollingFrameTime.reset();
  36771. };
  36772. return PerformanceMonitor;
  36773. }());
  36774. BABYLON.PerformanceMonitor = PerformanceMonitor;
  36775. /**
  36776. * RollingAverage
  36777. *
  36778. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  36779. */
  36780. var RollingAverage = /** @class */ (function () {
  36781. /**
  36782. * constructor
  36783. * @param length The number of samples required to saturate the sliding window
  36784. */
  36785. function RollingAverage(length) {
  36786. this._samples = new Array(length);
  36787. this.reset();
  36788. }
  36789. /**
  36790. * Adds a sample to the sample set
  36791. * @param v The sample value
  36792. */
  36793. RollingAverage.prototype.add = function (v) {
  36794. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  36795. var delta;
  36796. //we need to check if we've already wrapped round
  36797. if (this.isSaturated()) {
  36798. //remove bottom of stack from mean
  36799. var bottomValue = this._samples[this._pos];
  36800. delta = bottomValue - this.average;
  36801. this.average -= delta / (this._sampleCount - 1);
  36802. this._m2 -= delta * (bottomValue - this.average);
  36803. }
  36804. else {
  36805. this._sampleCount++;
  36806. }
  36807. //add new value to mean
  36808. delta = v - this.average;
  36809. this.average += delta / (this._sampleCount);
  36810. this._m2 += delta * (v - this.average);
  36811. //set the new variance
  36812. this.variance = this._m2 / (this._sampleCount - 1);
  36813. this._samples[this._pos] = v;
  36814. this._pos++;
  36815. this._pos %= this._samples.length; //positive wrap around
  36816. };
  36817. /**
  36818. * Returns previously added values or null if outside of history or outside the sliding window domain
  36819. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  36820. * @return Value previously recorded with add() or null if outside of range
  36821. */
  36822. RollingAverage.prototype.history = function (i) {
  36823. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  36824. return 0;
  36825. }
  36826. var i0 = this._wrapPosition(this._pos - 1.0);
  36827. return this._samples[this._wrapPosition(i0 - i)];
  36828. };
  36829. /**
  36830. * Returns true if enough samples have been taken to completely fill the sliding window
  36831. * @return true if sample-set saturated
  36832. */
  36833. RollingAverage.prototype.isSaturated = function () {
  36834. return this._sampleCount >= this._samples.length;
  36835. };
  36836. /**
  36837. * Resets the rolling average (equivalent to 0 samples taken so far)
  36838. */
  36839. RollingAverage.prototype.reset = function () {
  36840. this.average = 0;
  36841. this.variance = 0;
  36842. this._sampleCount = 0;
  36843. this._pos = 0;
  36844. this._m2 = 0;
  36845. };
  36846. /**
  36847. * Wraps a value around the sample range boundaries
  36848. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  36849. * @return Wrapped position in sample range
  36850. */
  36851. RollingAverage.prototype._wrapPosition = function (i) {
  36852. var max = this._samples.length;
  36853. return ((i % max) + max) % max;
  36854. };
  36855. return RollingAverage;
  36856. }());
  36857. BABYLON.RollingAverage = RollingAverage;
  36858. })(BABYLON || (BABYLON = {}));
  36859. //# sourceMappingURL=babylon.performanceMonitor.js.map
  36860. var BABYLON;
  36861. (function (BABYLON) {
  36862. /**
  36863. * This groups together the common properties used for image processing either in direct forward pass
  36864. * or through post processing effect depending on the use of the image processing pipeline in your scene
  36865. * or not.
  36866. */
  36867. var ImageProcessingConfiguration = /** @class */ (function () {
  36868. function ImageProcessingConfiguration() {
  36869. /**
  36870. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  36871. */
  36872. this.colorCurves = new BABYLON.ColorCurves();
  36873. this._colorCurvesEnabled = false;
  36874. this._colorGradingEnabled = false;
  36875. this._colorGradingWithGreenDepth = true;
  36876. this._colorGradingBGR = true;
  36877. this._exposure = 1.0;
  36878. this._toneMappingEnabled = false;
  36879. this._contrast = 1.0;
  36880. /**
  36881. * Vignette stretch size.
  36882. */
  36883. this.vignetteStretch = 0;
  36884. /**
  36885. * Vignette centre X Offset.
  36886. */
  36887. this.vignetteCentreX = 0;
  36888. /**
  36889. * Vignette centre Y Offset.
  36890. */
  36891. this.vignetteCentreY = 0;
  36892. /**
  36893. * Vignette weight or intensity of the vignette effect.
  36894. */
  36895. this.vignetteWeight = 1.5;
  36896. /**
  36897. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  36898. * if vignetteEnabled is set to true.
  36899. */
  36900. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  36901. /**
  36902. * Camera field of view used by the Vignette effect.
  36903. */
  36904. this.vignetteCameraFov = 0.5;
  36905. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  36906. this._vignetteEnabled = false;
  36907. this._applyByPostProcess = false;
  36908. this._isEnabled = true;
  36909. /**
  36910. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  36911. * @type {BABYLON.Observable}
  36912. */
  36913. this.onUpdateParameters = new BABYLON.Observable();
  36914. }
  36915. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  36916. /**
  36917. * Gets wether the color curves effect is enabled.
  36918. */
  36919. get: function () {
  36920. return this._colorCurvesEnabled;
  36921. },
  36922. /**
  36923. * Sets wether the color curves effect is enabled.
  36924. */
  36925. set: function (value) {
  36926. if (this._colorCurvesEnabled === value) {
  36927. return;
  36928. }
  36929. this._colorCurvesEnabled = value;
  36930. this._updateParameters();
  36931. },
  36932. enumerable: true,
  36933. configurable: true
  36934. });
  36935. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  36936. /**
  36937. * Gets wether the color grading effect is enabled.
  36938. */
  36939. get: function () {
  36940. return this._colorGradingEnabled;
  36941. },
  36942. /**
  36943. * Sets wether the color grading effect is enabled.
  36944. */
  36945. set: function (value) {
  36946. if (this._colorGradingEnabled === value) {
  36947. return;
  36948. }
  36949. this._colorGradingEnabled = value;
  36950. this._updateParameters();
  36951. },
  36952. enumerable: true,
  36953. configurable: true
  36954. });
  36955. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  36956. /**
  36957. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  36958. */
  36959. get: function () {
  36960. return this._colorGradingWithGreenDepth;
  36961. },
  36962. /**
  36963. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  36964. */
  36965. set: function (value) {
  36966. if (this._colorGradingWithGreenDepth === value) {
  36967. return;
  36968. }
  36969. this._colorGradingWithGreenDepth = value;
  36970. this._updateParameters();
  36971. },
  36972. enumerable: true,
  36973. configurable: true
  36974. });
  36975. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  36976. /**
  36977. * Gets wether the color grading texture contains BGR values.
  36978. */
  36979. get: function () {
  36980. return this._colorGradingBGR;
  36981. },
  36982. /**
  36983. * Sets wether the color grading texture contains BGR values.
  36984. */
  36985. set: function (value) {
  36986. if (this._colorGradingBGR === value) {
  36987. return;
  36988. }
  36989. this._colorGradingBGR = value;
  36990. this._updateParameters();
  36991. },
  36992. enumerable: true,
  36993. configurable: true
  36994. });
  36995. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  36996. /**
  36997. * Gets the Exposure used in the effect.
  36998. */
  36999. get: function () {
  37000. return this._exposure;
  37001. },
  37002. /**
  37003. * Sets the Exposure used in the effect.
  37004. */
  37005. set: function (value) {
  37006. if (this._exposure === value) {
  37007. return;
  37008. }
  37009. this._exposure = value;
  37010. this._updateParameters();
  37011. },
  37012. enumerable: true,
  37013. configurable: true
  37014. });
  37015. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  37016. /**
  37017. * Gets wether the tone mapping effect is enabled.
  37018. */
  37019. get: function () {
  37020. return this._toneMappingEnabled;
  37021. },
  37022. /**
  37023. * Sets wether the tone mapping effect is enabled.
  37024. */
  37025. set: function (value) {
  37026. if (this._toneMappingEnabled === value) {
  37027. return;
  37028. }
  37029. this._toneMappingEnabled = value;
  37030. this._updateParameters();
  37031. },
  37032. enumerable: true,
  37033. configurable: true
  37034. });
  37035. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  37036. /**
  37037. * Gets the contrast used in the effect.
  37038. */
  37039. get: function () {
  37040. return this._contrast;
  37041. },
  37042. /**
  37043. * Sets the contrast used in the effect.
  37044. */
  37045. set: function (value) {
  37046. if (this._contrast === value) {
  37047. return;
  37048. }
  37049. this._contrast = value;
  37050. this._updateParameters();
  37051. },
  37052. enumerable: true,
  37053. configurable: true
  37054. });
  37055. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  37056. /**
  37057. * Gets the vignette blend mode allowing different kind of effect.
  37058. */
  37059. get: function () {
  37060. return this._vignetteBlendMode;
  37061. },
  37062. /**
  37063. * Sets the vignette blend mode allowing different kind of effect.
  37064. */
  37065. set: function (value) {
  37066. if (this._vignetteBlendMode === value) {
  37067. return;
  37068. }
  37069. this._vignetteBlendMode = value;
  37070. this._updateParameters();
  37071. },
  37072. enumerable: true,
  37073. configurable: true
  37074. });
  37075. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  37076. /**
  37077. * Gets wether the vignette effect is enabled.
  37078. */
  37079. get: function () {
  37080. return this._vignetteEnabled;
  37081. },
  37082. /**
  37083. * Sets wether the vignette effect is enabled.
  37084. */
  37085. set: function (value) {
  37086. if (this._vignetteEnabled === value) {
  37087. return;
  37088. }
  37089. this._vignetteEnabled = value;
  37090. this._updateParameters();
  37091. },
  37092. enumerable: true,
  37093. configurable: true
  37094. });
  37095. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  37096. /**
  37097. * Gets wether the image processing is applied through a post process or not.
  37098. */
  37099. get: function () {
  37100. return this._applyByPostProcess;
  37101. },
  37102. /**
  37103. * Sets wether the image processing is applied through a post process or not.
  37104. */
  37105. set: function (value) {
  37106. if (this._applyByPostProcess === value) {
  37107. return;
  37108. }
  37109. this._applyByPostProcess = value;
  37110. this._updateParameters();
  37111. },
  37112. enumerable: true,
  37113. configurable: true
  37114. });
  37115. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  37116. /**
  37117. * Gets wether the image processing is enabled or not.
  37118. */
  37119. get: function () {
  37120. return this._isEnabled;
  37121. },
  37122. /**
  37123. * Sets wether the image processing is enabled or not.
  37124. */
  37125. set: function (value) {
  37126. if (this._isEnabled === value) {
  37127. return;
  37128. }
  37129. this._isEnabled = value;
  37130. this._updateParameters();
  37131. },
  37132. enumerable: true,
  37133. configurable: true
  37134. });
  37135. /**
  37136. * Method called each time the image processing information changes requires to recompile the effect.
  37137. */
  37138. ImageProcessingConfiguration.prototype._updateParameters = function () {
  37139. this.onUpdateParameters.notifyObservers(this);
  37140. };
  37141. ImageProcessingConfiguration.prototype.getClassName = function () {
  37142. return "ImageProcessingConfiguration";
  37143. };
  37144. /**
  37145. * Prepare the list of uniforms associated with the Image Processing effects.
  37146. * @param uniformsList The list of uniforms used in the effect
  37147. * @param defines the list of defines currently in use
  37148. */
  37149. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  37150. if (defines.EXPOSURE) {
  37151. uniforms.push("exposureLinear");
  37152. }
  37153. if (defines.CONTRAST) {
  37154. uniforms.push("contrast");
  37155. }
  37156. if (defines.COLORGRADING) {
  37157. uniforms.push("colorTransformSettings");
  37158. }
  37159. if (defines.VIGNETTE) {
  37160. uniforms.push("vInverseScreenSize");
  37161. uniforms.push("vignetteSettings1");
  37162. uniforms.push("vignetteSettings2");
  37163. }
  37164. if (defines.COLORCURVES) {
  37165. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  37166. }
  37167. };
  37168. /**
  37169. * Prepare the list of samplers associated with the Image Processing effects.
  37170. * @param uniformsList The list of uniforms used in the effect
  37171. * @param defines the list of defines currently in use
  37172. */
  37173. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  37174. if (defines.COLORGRADING) {
  37175. samplersList.push("txColorTransform");
  37176. }
  37177. };
  37178. /**
  37179. * Prepare the list of defines associated to the shader.
  37180. * @param defines the list of defines to complete
  37181. */
  37182. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  37183. if (forPostProcess === void 0) { forPostProcess = false; }
  37184. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  37185. defines.VIGNETTE = false;
  37186. defines.TONEMAPPING = false;
  37187. defines.CONTRAST = false;
  37188. defines.EXPOSURE = false;
  37189. defines.COLORCURVES = false;
  37190. defines.COLORGRADING = false;
  37191. defines.COLORGRADING3D = false;
  37192. defines.IMAGEPROCESSING = false;
  37193. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  37194. return;
  37195. }
  37196. defines.VIGNETTE = this.vignetteEnabled;
  37197. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  37198. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  37199. defines.TONEMAPPING = this.toneMappingEnabled;
  37200. defines.CONTRAST = (this.contrast !== 1.0);
  37201. defines.EXPOSURE = (this.exposure !== 1.0);
  37202. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  37203. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  37204. if (defines.COLORGRADING) {
  37205. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  37206. }
  37207. else {
  37208. defines.COLORGRADING3D = false;
  37209. }
  37210. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  37211. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  37212. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  37213. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  37214. };
  37215. /**
  37216. * Returns true if all the image processing information are ready.
  37217. */
  37218. ImageProcessingConfiguration.prototype.isReady = function () {
  37219. // Color Grading texure can not be none blocking.
  37220. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  37221. };
  37222. /**
  37223. * Binds the image processing to the shader.
  37224. * @param effect The effect to bind to
  37225. */
  37226. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  37227. if (aspectRatio === void 0) { aspectRatio = 1; }
  37228. // Color Curves
  37229. if (this._colorCurvesEnabled && this.colorCurves) {
  37230. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  37231. }
  37232. // Vignette
  37233. if (this._vignetteEnabled) {
  37234. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  37235. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  37236. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  37237. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  37238. var vignetteScaleX = vignetteScaleY * aspectRatio;
  37239. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  37240. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  37241. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  37242. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  37243. var vignettePower = -2.0 * this.vignetteWeight;
  37244. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  37245. }
  37246. // Exposure
  37247. effect.setFloat("exposureLinear", this.exposure);
  37248. // Contrast
  37249. effect.setFloat("contrast", this.contrast);
  37250. // Color transform settings
  37251. if (this.colorGradingTexture) {
  37252. effect.setTexture("txColorTransform", this.colorGradingTexture);
  37253. var textureSize = this.colorGradingTexture.getSize().height;
  37254. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  37255. 0.5 / textureSize, // textureOffset
  37256. textureSize, // textureSize
  37257. this.colorGradingTexture.level // weight
  37258. );
  37259. }
  37260. };
  37261. /**
  37262. * Clones the current image processing instance.
  37263. * @return The cloned image processing
  37264. */
  37265. ImageProcessingConfiguration.prototype.clone = function () {
  37266. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  37267. };
  37268. /**
  37269. * Serializes the current image processing instance to a json representation.
  37270. * @return a JSON representation
  37271. */
  37272. ImageProcessingConfiguration.prototype.serialize = function () {
  37273. return BABYLON.SerializationHelper.Serialize(this);
  37274. };
  37275. /**
  37276. * Parses the image processing from a json representation.
  37277. * @param source the JSON source to parse
  37278. * @return The parsed image processing
  37279. */
  37280. ImageProcessingConfiguration.Parse = function (source) {
  37281. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  37282. };
  37283. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  37284. /**
  37285. * Used to apply the vignette as a mix with the pixel color.
  37286. */
  37287. get: function () {
  37288. return this._VIGNETTEMODE_MULTIPLY;
  37289. },
  37290. enumerable: true,
  37291. configurable: true
  37292. });
  37293. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  37294. /**
  37295. * Used to apply the vignette as a replacement of the pixel color.
  37296. */
  37297. get: function () {
  37298. return this._VIGNETTEMODE_OPAQUE;
  37299. },
  37300. enumerable: true,
  37301. configurable: true
  37302. });
  37303. // Static constants associated to the image processing.
  37304. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  37305. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  37306. __decorate([
  37307. BABYLON.serializeAsColorCurves()
  37308. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  37309. __decorate([
  37310. BABYLON.serialize()
  37311. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  37312. __decorate([
  37313. BABYLON.serializeAsTexture()
  37314. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  37315. __decorate([
  37316. BABYLON.serialize()
  37317. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  37318. __decorate([
  37319. BABYLON.serialize()
  37320. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  37321. __decorate([
  37322. BABYLON.serialize()
  37323. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  37324. __decorate([
  37325. BABYLON.serialize()
  37326. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  37327. __decorate([
  37328. BABYLON.serialize()
  37329. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  37330. __decorate([
  37331. BABYLON.serialize()
  37332. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  37333. __decorate([
  37334. BABYLON.serialize()
  37335. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  37336. __decorate([
  37337. BABYLON.serialize()
  37338. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  37339. __decorate([
  37340. BABYLON.serialize()
  37341. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  37342. __decorate([
  37343. BABYLON.serialize()
  37344. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  37345. __decorate([
  37346. BABYLON.serializeAsColor4()
  37347. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  37348. __decorate([
  37349. BABYLON.serialize()
  37350. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  37351. __decorate([
  37352. BABYLON.serialize()
  37353. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  37354. __decorate([
  37355. BABYLON.serialize()
  37356. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  37357. __decorate([
  37358. BABYLON.serialize()
  37359. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  37360. __decorate([
  37361. BABYLON.serialize()
  37362. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  37363. return ImageProcessingConfiguration;
  37364. }());
  37365. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  37366. })(BABYLON || (BABYLON = {}));
  37367. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  37368. var BABYLON;
  37369. (function (BABYLON) {
  37370. /**
  37371. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  37372. * It can help converting any input color in a desired output one. This can then be used to create effects
  37373. * from sepia, black and white to sixties or futuristic rendering...
  37374. *
  37375. * The only supported format is currently 3dl.
  37376. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  37377. */
  37378. var ColorGradingTexture = /** @class */ (function (_super) {
  37379. __extends(ColorGradingTexture, _super);
  37380. /**
  37381. * Instantiates a ColorGradingTexture from the following parameters.
  37382. *
  37383. * @param url The location of the color gradind data (currently only supporting 3dl)
  37384. * @param scene The scene the texture will be used in
  37385. */
  37386. function ColorGradingTexture(url, scene) {
  37387. var _this = _super.call(this, scene) || this;
  37388. if (!url) {
  37389. return _this;
  37390. }
  37391. _this._engine = scene.getEngine();
  37392. _this._textureMatrix = BABYLON.Matrix.Identity();
  37393. _this.name = url;
  37394. _this.url = url;
  37395. _this.hasAlpha = false;
  37396. _this.isCube = false;
  37397. _this.is3D = _this._engine.webGLVersion > 1;
  37398. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37399. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37400. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37401. _this.anisotropicFilteringLevel = 1;
  37402. _this._texture = _this._getFromCache(url, true);
  37403. if (!_this._texture) {
  37404. if (!scene.useDelayedTextureLoading) {
  37405. _this.loadTexture();
  37406. }
  37407. else {
  37408. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  37409. }
  37410. }
  37411. return _this;
  37412. }
  37413. /**
  37414. * Returns the texture matrix used in most of the material.
  37415. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  37416. */
  37417. ColorGradingTexture.prototype.getTextureMatrix = function () {
  37418. return this._textureMatrix;
  37419. };
  37420. /**
  37421. * Occurs when the file being loaded is a .3dl LUT file.
  37422. */
  37423. ColorGradingTexture.prototype.load3dlTexture = function () {
  37424. var engine = this._engine;
  37425. var texture;
  37426. if (engine.webGLVersion === 1) {
  37427. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  37428. }
  37429. else {
  37430. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  37431. }
  37432. this._texture = texture;
  37433. var callback = function (text) {
  37434. if (typeof text !== "string") {
  37435. return;
  37436. }
  37437. var data = null;
  37438. var tempData = null;
  37439. var line;
  37440. var lines = text.split('\n');
  37441. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  37442. var maxColor = 0;
  37443. for (var i = 0; i < lines.length; i++) {
  37444. line = lines[i];
  37445. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  37446. continue;
  37447. if (line.indexOf('#') === 0)
  37448. continue;
  37449. var words = line.split(" ");
  37450. if (size === 0) {
  37451. // Number of space + one
  37452. size = words.length;
  37453. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  37454. tempData = new Float32Array(size * size * size * 4);
  37455. continue;
  37456. }
  37457. if (size != 0) {
  37458. var r = Math.max(parseInt(words[0]), 0);
  37459. var g = Math.max(parseInt(words[1]), 0);
  37460. var b = Math.max(parseInt(words[2]), 0);
  37461. maxColor = Math.max(r, maxColor);
  37462. maxColor = Math.max(g, maxColor);
  37463. maxColor = Math.max(b, maxColor);
  37464. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  37465. if (tempData) {
  37466. tempData[pixelStorageIndex + 0] = r;
  37467. tempData[pixelStorageIndex + 1] = g;
  37468. tempData[pixelStorageIndex + 2] = b;
  37469. }
  37470. pixelIndexSlice++;
  37471. if (pixelIndexSlice % size == 0) {
  37472. pixelIndexH++;
  37473. pixelIndexSlice = 0;
  37474. if (pixelIndexH % size == 0) {
  37475. pixelIndexW++;
  37476. pixelIndexH = 0;
  37477. }
  37478. }
  37479. }
  37480. }
  37481. if (tempData && data) {
  37482. for (var i = 0; i < tempData.length; i++) {
  37483. if (i > 0 && (i + 1) % 4 === 0) {
  37484. data[i] = 255;
  37485. }
  37486. else {
  37487. var value = tempData[i];
  37488. data[i] = (value / maxColor * 255);
  37489. }
  37490. }
  37491. }
  37492. if (texture.is3D) {
  37493. texture.updateSize(size, size, size);
  37494. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  37495. }
  37496. else {
  37497. texture.updateSize(size * size, size);
  37498. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  37499. }
  37500. };
  37501. var scene = this.getScene();
  37502. if (scene) {
  37503. scene._loadFile(this.url, callback);
  37504. }
  37505. else {
  37506. this._engine._loadFile(this.url, callback);
  37507. }
  37508. return this._texture;
  37509. };
  37510. /**
  37511. * Starts the loading process of the texture.
  37512. */
  37513. ColorGradingTexture.prototype.loadTexture = function () {
  37514. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  37515. this.load3dlTexture();
  37516. }
  37517. };
  37518. /**
  37519. * Clones the color gradind texture.
  37520. */
  37521. ColorGradingTexture.prototype.clone = function () {
  37522. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  37523. // Base texture
  37524. newTexture.level = this.level;
  37525. return newTexture;
  37526. };
  37527. /**
  37528. * Called during delayed load for textures.
  37529. */
  37530. ColorGradingTexture.prototype.delayLoad = function () {
  37531. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  37532. return;
  37533. }
  37534. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  37535. this._texture = this._getFromCache(this.url, true);
  37536. if (!this._texture) {
  37537. this.loadTexture();
  37538. }
  37539. };
  37540. /**
  37541. * Parses a color grading texture serialized by Babylon.
  37542. * @param parsedTexture The texture information being parsedTexture
  37543. * @param scene The scene to load the texture in
  37544. * @param rootUrl The root url of the data assets to load
  37545. * @return A color gradind texture
  37546. */
  37547. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  37548. var texture = null;
  37549. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  37550. texture = new ColorGradingTexture(parsedTexture.name, scene);
  37551. texture.name = parsedTexture.name;
  37552. texture.level = parsedTexture.level;
  37553. }
  37554. return texture;
  37555. };
  37556. /**
  37557. * Serializes the LUT texture to json format.
  37558. */
  37559. ColorGradingTexture.prototype.serialize = function () {
  37560. if (!this.name) {
  37561. return null;
  37562. }
  37563. var serializationObject = {};
  37564. serializationObject.name = this.name;
  37565. serializationObject.level = this.level;
  37566. serializationObject.customType = "BABYLON.ColorGradingTexture";
  37567. return serializationObject;
  37568. };
  37569. /**
  37570. * Empty line regex stored for GC.
  37571. */
  37572. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  37573. return ColorGradingTexture;
  37574. }(BABYLON.BaseTexture));
  37575. BABYLON.ColorGradingTexture = ColorGradingTexture;
  37576. })(BABYLON || (BABYLON = {}));
  37577. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  37578. var BABYLON;
  37579. (function (BABYLON) {
  37580. /**
  37581. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  37582. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  37583. * 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;
  37584. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  37585. */
  37586. var ColorCurves = /** @class */ (function () {
  37587. function ColorCurves() {
  37588. this._dirty = true;
  37589. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  37590. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  37591. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  37592. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  37593. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  37594. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  37595. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  37596. this._globalHue = 30;
  37597. this._globalDensity = 0;
  37598. this._globalSaturation = 0;
  37599. this._globalExposure = 0;
  37600. this._highlightsHue = 30;
  37601. this._highlightsDensity = 0;
  37602. this._highlightsSaturation = 0;
  37603. this._highlightsExposure = 0;
  37604. this._midtonesHue = 30;
  37605. this._midtonesDensity = 0;
  37606. this._midtonesSaturation = 0;
  37607. this._midtonesExposure = 0;
  37608. this._shadowsHue = 30;
  37609. this._shadowsDensity = 0;
  37610. this._shadowsSaturation = 0;
  37611. this._shadowsExposure = 0;
  37612. }
  37613. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  37614. /**
  37615. * Gets the global Hue value.
  37616. * 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).
  37617. */
  37618. get: function () {
  37619. return this._globalHue;
  37620. },
  37621. /**
  37622. * Sets the global Hue value.
  37623. * 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).
  37624. */
  37625. set: function (value) {
  37626. this._globalHue = value;
  37627. this._dirty = true;
  37628. },
  37629. enumerable: true,
  37630. configurable: true
  37631. });
  37632. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  37633. /**
  37634. * Gets the global Density value.
  37635. * 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.
  37636. * Values less than zero provide a filter of opposite hue.
  37637. */
  37638. get: function () {
  37639. return this._globalDensity;
  37640. },
  37641. /**
  37642. * Sets the global Density value.
  37643. * 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.
  37644. * Values less than zero provide a filter of opposite hue.
  37645. */
  37646. set: function (value) {
  37647. this._globalDensity = value;
  37648. this._dirty = true;
  37649. },
  37650. enumerable: true,
  37651. configurable: true
  37652. });
  37653. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  37654. /**
  37655. * Gets the global Saturation value.
  37656. * 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.
  37657. */
  37658. get: function () {
  37659. return this._globalSaturation;
  37660. },
  37661. /**
  37662. * Sets the global Saturation value.
  37663. * 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.
  37664. */
  37665. set: function (value) {
  37666. this._globalSaturation = value;
  37667. this._dirty = true;
  37668. },
  37669. enumerable: true,
  37670. configurable: true
  37671. });
  37672. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  37673. /**
  37674. * Gets the highlights Hue value.
  37675. * 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).
  37676. */
  37677. get: function () {
  37678. return this._highlightsHue;
  37679. },
  37680. /**
  37681. * Sets the highlights Hue value.
  37682. * 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).
  37683. */
  37684. set: function (value) {
  37685. this._highlightsHue = value;
  37686. this._dirty = true;
  37687. },
  37688. enumerable: true,
  37689. configurable: true
  37690. });
  37691. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  37692. /**
  37693. * Gets the highlights Density value.
  37694. * 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.
  37695. * Values less than zero provide a filter of opposite hue.
  37696. */
  37697. get: function () {
  37698. return this._highlightsDensity;
  37699. },
  37700. /**
  37701. * Sets the highlights Density value.
  37702. * 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.
  37703. * Values less than zero provide a filter of opposite hue.
  37704. */
  37705. set: function (value) {
  37706. this._highlightsDensity = value;
  37707. this._dirty = true;
  37708. },
  37709. enumerable: true,
  37710. configurable: true
  37711. });
  37712. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  37713. /**
  37714. * Gets the highlights Saturation value.
  37715. * 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.
  37716. */
  37717. get: function () {
  37718. return this._highlightsSaturation;
  37719. },
  37720. /**
  37721. * Sets the highlights Saturation value.
  37722. * 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.
  37723. */
  37724. set: function (value) {
  37725. this._highlightsSaturation = value;
  37726. this._dirty = true;
  37727. },
  37728. enumerable: true,
  37729. configurable: true
  37730. });
  37731. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  37732. /**
  37733. * Gets the highlights Exposure value.
  37734. * 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.
  37735. */
  37736. get: function () {
  37737. return this._highlightsExposure;
  37738. },
  37739. /**
  37740. * Sets the highlights Exposure value.
  37741. * 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.
  37742. */
  37743. set: function (value) {
  37744. this._highlightsExposure = value;
  37745. this._dirty = true;
  37746. },
  37747. enumerable: true,
  37748. configurable: true
  37749. });
  37750. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  37751. /**
  37752. * Gets the midtones Hue value.
  37753. * 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).
  37754. */
  37755. get: function () {
  37756. return this._midtonesHue;
  37757. },
  37758. /**
  37759. * Sets the midtones Hue value.
  37760. * 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).
  37761. */
  37762. set: function (value) {
  37763. this._midtonesHue = value;
  37764. this._dirty = true;
  37765. },
  37766. enumerable: true,
  37767. configurable: true
  37768. });
  37769. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  37770. /**
  37771. * Gets the midtones Density value.
  37772. * 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.
  37773. * Values less than zero provide a filter of opposite hue.
  37774. */
  37775. get: function () {
  37776. return this._midtonesDensity;
  37777. },
  37778. /**
  37779. * Sets the midtones Density value.
  37780. * 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.
  37781. * Values less than zero provide a filter of opposite hue.
  37782. */
  37783. set: function (value) {
  37784. this._midtonesDensity = value;
  37785. this._dirty = true;
  37786. },
  37787. enumerable: true,
  37788. configurable: true
  37789. });
  37790. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  37791. /**
  37792. * Gets the midtones Saturation value.
  37793. * 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.
  37794. */
  37795. get: function () {
  37796. return this._midtonesSaturation;
  37797. },
  37798. /**
  37799. * Sets the midtones Saturation value.
  37800. * 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.
  37801. */
  37802. set: function (value) {
  37803. this._midtonesSaturation = value;
  37804. this._dirty = true;
  37805. },
  37806. enumerable: true,
  37807. configurable: true
  37808. });
  37809. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  37810. /**
  37811. * Gets the midtones Exposure value.
  37812. * 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.
  37813. */
  37814. get: function () {
  37815. return this._midtonesExposure;
  37816. },
  37817. /**
  37818. * Sets the midtones Exposure value.
  37819. * 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.
  37820. */
  37821. set: function (value) {
  37822. this._midtonesExposure = value;
  37823. this._dirty = true;
  37824. },
  37825. enumerable: true,
  37826. configurable: true
  37827. });
  37828. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  37829. /**
  37830. * Gets the shadows Hue value.
  37831. * 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).
  37832. */
  37833. get: function () {
  37834. return this._shadowsHue;
  37835. },
  37836. /**
  37837. * Sets the shadows Hue value.
  37838. * 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).
  37839. */
  37840. set: function (value) {
  37841. this._shadowsHue = value;
  37842. this._dirty = true;
  37843. },
  37844. enumerable: true,
  37845. configurable: true
  37846. });
  37847. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  37848. /**
  37849. * Gets the shadows Density value.
  37850. * 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.
  37851. * Values less than zero provide a filter of opposite hue.
  37852. */
  37853. get: function () {
  37854. return this._shadowsDensity;
  37855. },
  37856. /**
  37857. * Sets the shadows Density value.
  37858. * 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.
  37859. * Values less than zero provide a filter of opposite hue.
  37860. */
  37861. set: function (value) {
  37862. this._shadowsDensity = value;
  37863. this._dirty = true;
  37864. },
  37865. enumerable: true,
  37866. configurable: true
  37867. });
  37868. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  37869. /**
  37870. * Gets the shadows Saturation value.
  37871. * 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.
  37872. */
  37873. get: function () {
  37874. return this._shadowsSaturation;
  37875. },
  37876. /**
  37877. * Sets the shadows Saturation value.
  37878. * 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.
  37879. */
  37880. set: function (value) {
  37881. this._shadowsSaturation = value;
  37882. this._dirty = true;
  37883. },
  37884. enumerable: true,
  37885. configurable: true
  37886. });
  37887. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  37888. /**
  37889. * Gets the shadows Exposure value.
  37890. * 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.
  37891. */
  37892. get: function () {
  37893. return this._shadowsExposure;
  37894. },
  37895. /**
  37896. * Sets the shadows Exposure value.
  37897. * 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.
  37898. */
  37899. set: function (value) {
  37900. this._shadowsExposure = value;
  37901. this._dirty = true;
  37902. },
  37903. enumerable: true,
  37904. configurable: true
  37905. });
  37906. ColorCurves.prototype.getClassName = function () {
  37907. return "ColorCurves";
  37908. };
  37909. /**
  37910. * Binds the color curves to the shader.
  37911. * @param colorCurves The color curve to bind
  37912. * @param effect The effect to bind to
  37913. */
  37914. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  37915. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  37916. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  37917. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  37918. if (colorCurves._dirty) {
  37919. colorCurves._dirty = false;
  37920. // Fill in global info.
  37921. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  37922. // Compute highlights info.
  37923. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  37924. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  37925. // Compute midtones info.
  37926. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  37927. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  37928. // Compute shadows info.
  37929. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  37930. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  37931. // Compute deltas (neutral is midtones).
  37932. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  37933. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  37934. }
  37935. if (effect) {
  37936. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  37937. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  37938. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  37939. }
  37940. };
  37941. /**
  37942. * Prepare the list of uniforms associated with the ColorCurves effects.
  37943. * @param uniformsList The list of uniforms used in the effect
  37944. */
  37945. ColorCurves.PrepareUniforms = function (uniformsList) {
  37946. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  37947. };
  37948. /**
  37949. * Returns color grading data based on a hue, density, saturation and exposure value.
  37950. * @param filterHue The hue of the color filter.
  37951. * @param filterDensity The density of the color filter.
  37952. * @param saturation The saturation.
  37953. * @param exposure The exposure.
  37954. * @param result The result data container.
  37955. */
  37956. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  37957. if (hue == null) {
  37958. return;
  37959. }
  37960. hue = ColorCurves.clamp(hue, 0, 360);
  37961. density = ColorCurves.clamp(density, -100, 100);
  37962. saturation = ColorCurves.clamp(saturation, -100, 100);
  37963. exposure = ColorCurves.clamp(exposure, -100, 100);
  37964. // Remap the slider/config filter density with non-linear mapping and also scale by half
  37965. // so that the maximum filter density is only 50% control. This provides fine control
  37966. // for small values and reasonable range.
  37967. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  37968. density *= 0.5;
  37969. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  37970. if (density < 0) {
  37971. density *= -1;
  37972. hue = (hue + 180) % 360;
  37973. }
  37974. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  37975. result.scaleToRef(2, result);
  37976. result.a = 1 + 0.01 * saturation;
  37977. };
  37978. /**
  37979. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  37980. * @param value The input slider value in range [-100,100].
  37981. * @returns Adjusted value.
  37982. */
  37983. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  37984. value /= 100;
  37985. var x = Math.abs(value);
  37986. x = Math.pow(x, 2);
  37987. if (value < 0) {
  37988. x *= -1;
  37989. }
  37990. x *= 100;
  37991. return x;
  37992. };
  37993. /**
  37994. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  37995. * @param hue The hue (H) input.
  37996. * @param saturation The saturation (S) input.
  37997. * @param brightness The brightness (B) input.
  37998. * @result An RGBA color represented as Vector4.
  37999. */
  38000. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  38001. var h = ColorCurves.clamp(hue, 0, 360);
  38002. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  38003. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  38004. if (s === 0) {
  38005. result.r = v;
  38006. result.g = v;
  38007. result.b = v;
  38008. }
  38009. else {
  38010. // sector 0 to 5
  38011. h /= 60;
  38012. var i = Math.floor(h);
  38013. // fractional part of h
  38014. var f = h - i;
  38015. var p = v * (1 - s);
  38016. var q = v * (1 - s * f);
  38017. var t = v * (1 - s * (1 - f));
  38018. switch (i) {
  38019. case 0:
  38020. result.r = v;
  38021. result.g = t;
  38022. result.b = p;
  38023. break;
  38024. case 1:
  38025. result.r = q;
  38026. result.g = v;
  38027. result.b = p;
  38028. break;
  38029. case 2:
  38030. result.r = p;
  38031. result.g = v;
  38032. result.b = t;
  38033. break;
  38034. case 3:
  38035. result.r = p;
  38036. result.g = q;
  38037. result.b = v;
  38038. break;
  38039. case 4:
  38040. result.r = t;
  38041. result.g = p;
  38042. result.b = v;
  38043. break;
  38044. default:// case 5:
  38045. result.r = v;
  38046. result.g = p;
  38047. result.b = q;
  38048. break;
  38049. }
  38050. }
  38051. result.a = 1;
  38052. };
  38053. /**
  38054. * Returns a value clamped between min and max
  38055. * @param value The value to clamp
  38056. * @param min The minimum of value
  38057. * @param max The maximum of value
  38058. * @returns The clamped value.
  38059. */
  38060. ColorCurves.clamp = function (value, min, max) {
  38061. return Math.min(Math.max(value, min), max);
  38062. };
  38063. /**
  38064. * Clones the current color curve instance.
  38065. * @return The cloned curves
  38066. */
  38067. ColorCurves.prototype.clone = function () {
  38068. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  38069. };
  38070. /**
  38071. * Serializes the current color curve instance to a json representation.
  38072. * @return a JSON representation
  38073. */
  38074. ColorCurves.prototype.serialize = function () {
  38075. return BABYLON.SerializationHelper.Serialize(this);
  38076. };
  38077. /**
  38078. * Parses the color curve from a json representation.
  38079. * @param source the JSON source to parse
  38080. * @return The parsed curves
  38081. */
  38082. ColorCurves.Parse = function (source) {
  38083. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  38084. };
  38085. __decorate([
  38086. BABYLON.serialize()
  38087. ], ColorCurves.prototype, "_globalHue", void 0);
  38088. __decorate([
  38089. BABYLON.serialize()
  38090. ], ColorCurves.prototype, "_globalDensity", void 0);
  38091. __decorate([
  38092. BABYLON.serialize()
  38093. ], ColorCurves.prototype, "_globalSaturation", void 0);
  38094. __decorate([
  38095. BABYLON.serialize()
  38096. ], ColorCurves.prototype, "_globalExposure", void 0);
  38097. __decorate([
  38098. BABYLON.serialize()
  38099. ], ColorCurves.prototype, "_highlightsHue", void 0);
  38100. __decorate([
  38101. BABYLON.serialize()
  38102. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  38103. __decorate([
  38104. BABYLON.serialize()
  38105. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  38106. __decorate([
  38107. BABYLON.serialize()
  38108. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  38109. __decorate([
  38110. BABYLON.serialize()
  38111. ], ColorCurves.prototype, "_midtonesHue", void 0);
  38112. __decorate([
  38113. BABYLON.serialize()
  38114. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  38115. __decorate([
  38116. BABYLON.serialize()
  38117. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  38118. __decorate([
  38119. BABYLON.serialize()
  38120. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  38121. return ColorCurves;
  38122. }());
  38123. BABYLON.ColorCurves = ColorCurves;
  38124. })(BABYLON || (BABYLON = {}));
  38125. //# sourceMappingURL=babylon.colorCurves.js.map
  38126. //# sourceMappingURL=babylon.behavior.js.map
  38127. var BABYLON;
  38128. (function (BABYLON) {
  38129. /**
  38130. * "Static Class" containing the most commonly used helper while dealing with material for
  38131. * rendering purpose.
  38132. *
  38133. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  38134. *
  38135. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  38136. */
  38137. var MaterialHelper = /** @class */ (function () {
  38138. function MaterialHelper() {
  38139. }
  38140. /**
  38141. * Bind the current view position to an effect.
  38142. * @param effect The effect to be bound
  38143. * @param scene The scene the eyes position is used from
  38144. */
  38145. MaterialHelper.BindEyePosition = function (effect, scene) {
  38146. if (scene._forcedViewPosition) {
  38147. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  38148. return;
  38149. }
  38150. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  38151. };
  38152. /**
  38153. * Helps preparing the defines values about the UVs in used in the effect.
  38154. * UVs are shared as much as we can accross chanels in the shaders.
  38155. * @param texture The texture we are preparing the UVs for
  38156. * @param defines The defines to update
  38157. * @param key The chanel key "diffuse", "specular"... used in the shader
  38158. */
  38159. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  38160. defines._needUVs = true;
  38161. defines[key] = true;
  38162. if (texture.getTextureMatrix().isIdentity(true)) {
  38163. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  38164. if (texture.coordinatesIndex === 0) {
  38165. defines["MAINUV1"] = true;
  38166. }
  38167. else {
  38168. defines["MAINUV2"] = true;
  38169. }
  38170. }
  38171. else {
  38172. defines[key + "DIRECTUV"] = 0;
  38173. }
  38174. };
  38175. /**
  38176. * Binds a texture matrix value to its corrsponding uniform
  38177. * @param texture The texture to bind the matrix for
  38178. * @param uniformBuffer The uniform buffer receivin the data
  38179. * @param key The chanel key "diffuse", "specular"... used in the shader
  38180. */
  38181. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  38182. var matrix = texture.getTextureMatrix();
  38183. if (!matrix.isIdentity(true)) {
  38184. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  38185. }
  38186. };
  38187. /**
  38188. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  38189. * @param mesh defines the current mesh
  38190. * @param scene defines the current scene
  38191. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  38192. * @param pointsCloud defines if point cloud rendering has to be turned on
  38193. * @param fogEnabled defines if fog has to be turned on
  38194. * @param alphaTest defines if alpha testing has to be turned on
  38195. * @param defines defines the current list of defines
  38196. */
  38197. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  38198. if (defines._areMiscDirty) {
  38199. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  38200. defines["POINTSIZE"] = (pointsCloud || scene.forcePointsCloud);
  38201. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  38202. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  38203. defines["ALPHATEST"] = alphaTest;
  38204. }
  38205. };
  38206. /**
  38207. * Helper used to prepare the list of defines associated with frame values for shader compilation
  38208. * @param scene defines the current scene
  38209. * @param engine defines the current engine
  38210. * @param defines specifies the list of active defines
  38211. * @param useInstances defines if instances have to be turned on
  38212. * @param useClipPlane defines if clip plane have to be turned on
  38213. */
  38214. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  38215. if (useClipPlane === void 0) { useClipPlane = null; }
  38216. var changed = false;
  38217. if (useClipPlane == null) {
  38218. useClipPlane = (scene.clipPlane !== undefined && scene.clipPlane !== null);
  38219. }
  38220. if (defines["CLIPPLANE"] !== useClipPlane) {
  38221. defines["CLIPPLANE"] = useClipPlane;
  38222. changed = true;
  38223. }
  38224. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  38225. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  38226. changed = true;
  38227. }
  38228. if (defines["INSTANCES"] !== useInstances) {
  38229. defines["INSTANCES"] = useInstances;
  38230. changed = true;
  38231. }
  38232. if (changed) {
  38233. defines.markAsUnprocessed();
  38234. }
  38235. };
  38236. /**
  38237. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  38238. * @param mesh The mesh containing the geometry data we will draw
  38239. * @param defines The defines to update
  38240. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  38241. * @param useBones Precise whether bones should be used or not (override mesh info)
  38242. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  38243. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  38244. * @returns false if defines are considered not dirty and have not been checked
  38245. */
  38246. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  38247. if (useMorphTargets === void 0) { useMorphTargets = false; }
  38248. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  38249. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  38250. return false;
  38251. }
  38252. defines._normals = defines._needNormals;
  38253. defines._uvs = defines._needUVs;
  38254. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  38255. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  38256. defines["TANGENT"] = true;
  38257. }
  38258. if (defines._needUVs) {
  38259. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  38260. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  38261. }
  38262. else {
  38263. defines["UV1"] = false;
  38264. defines["UV2"] = false;
  38265. }
  38266. if (useVertexColor) {
  38267. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  38268. defines["VERTEXCOLOR"] = hasVertexColors;
  38269. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  38270. }
  38271. if (useBones) {
  38272. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  38273. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  38274. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  38275. }
  38276. else {
  38277. defines["NUM_BONE_INFLUENCERS"] = 0;
  38278. defines["BonesPerMesh"] = 0;
  38279. }
  38280. }
  38281. if (useMorphTargets) {
  38282. var manager = mesh.morphTargetManager;
  38283. if (manager) {
  38284. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  38285. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  38286. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  38287. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  38288. }
  38289. else {
  38290. defines["MORPHTARGETS_TANGENT"] = false;
  38291. defines["MORPHTARGETS_NORMAL"] = false;
  38292. defines["MORPHTARGETS"] = false;
  38293. defines["NUM_MORPH_INFLUENCERS"] = 0;
  38294. }
  38295. }
  38296. return true;
  38297. };
  38298. /**
  38299. * Prepares the defines related to the light information passed in parameter
  38300. * @param scene The scene we are intending to draw
  38301. * @param mesh The mesh the effect is compiling for
  38302. * @param defines The defines to update
  38303. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  38304. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  38305. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  38306. * @returns true if normals will be required for the rest of the effect
  38307. */
  38308. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  38309. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  38310. if (disableLighting === void 0) { disableLighting = false; }
  38311. if (!defines._areLightsDirty) {
  38312. return defines._needNormals;
  38313. }
  38314. var lightIndex = 0;
  38315. var needNormals = false;
  38316. var needRebuild = false;
  38317. var lightmapMode = false;
  38318. var shadowEnabled = false;
  38319. var specularEnabled = false;
  38320. if (scene.lightsEnabled && !disableLighting) {
  38321. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  38322. var light = _a[_i];
  38323. needNormals = true;
  38324. if (defines["LIGHT" + lightIndex] === undefined) {
  38325. needRebuild = true;
  38326. }
  38327. defines["LIGHT" + lightIndex] = true;
  38328. defines["SPOTLIGHT" + lightIndex] = false;
  38329. defines["HEMILIGHT" + lightIndex] = false;
  38330. defines["POINTLIGHT" + lightIndex] = false;
  38331. defines["DIRLIGHT" + lightIndex] = false;
  38332. var type;
  38333. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  38334. type = "SPOTLIGHT" + lightIndex;
  38335. var spotLight = light;
  38336. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = spotLight.projectionTexture ? spotLight.projectionTexture.isReady() : false;
  38337. }
  38338. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  38339. type = "HEMILIGHT" + lightIndex;
  38340. }
  38341. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  38342. type = "POINTLIGHT" + lightIndex;
  38343. }
  38344. else {
  38345. type = "DIRLIGHT" + lightIndex;
  38346. }
  38347. defines[type] = true;
  38348. // Specular
  38349. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  38350. specularEnabled = true;
  38351. }
  38352. // Shadows
  38353. defines["SHADOW" + lightIndex] = false;
  38354. defines["SHADOWPCF" + lightIndex] = false;
  38355. defines["SHADOWESM" + lightIndex] = false;
  38356. defines["SHADOWCUBE" + lightIndex] = false;
  38357. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  38358. var shadowGenerator = light.getShadowGenerator();
  38359. if (shadowGenerator) {
  38360. shadowEnabled = true;
  38361. shadowGenerator.prepareDefines(defines, lightIndex);
  38362. }
  38363. }
  38364. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  38365. lightmapMode = true;
  38366. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  38367. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  38368. }
  38369. else {
  38370. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  38371. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  38372. }
  38373. lightIndex++;
  38374. if (lightIndex === maxSimultaneousLights)
  38375. break;
  38376. }
  38377. }
  38378. defines["SPECULARTERM"] = specularEnabled;
  38379. defines["SHADOWS"] = shadowEnabled;
  38380. // Resetting all other lights if any
  38381. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  38382. if (defines["LIGHT" + index] !== undefined) {
  38383. defines["LIGHT" + index] = false;
  38384. defines["HEMILIGHT" + lightIndex] = false;
  38385. defines["POINTLIGHT" + lightIndex] = false;
  38386. defines["DIRLIGHT" + lightIndex] = false;
  38387. defines["SPOTLIGHT" + lightIndex] = false;
  38388. defines["SHADOW" + lightIndex] = false;
  38389. }
  38390. }
  38391. var caps = scene.getEngine().getCaps();
  38392. if (defines["SHADOWFLOAT"] === undefined) {
  38393. needRebuild = true;
  38394. }
  38395. defines["SHADOWFLOAT"] = shadowEnabled &&
  38396. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  38397. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  38398. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  38399. if (needRebuild) {
  38400. defines.rebuild();
  38401. }
  38402. return needNormals;
  38403. };
  38404. /**
  38405. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  38406. * that won t be acctive due to defines being turned off.
  38407. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  38408. * @param samplersList The samplers list
  38409. * @param defines The defines helping in the list generation
  38410. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  38411. */
  38412. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  38413. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  38414. var uniformsList;
  38415. var uniformBuffersList = null;
  38416. if (uniformsListOrOptions.uniformsNames) {
  38417. var options = uniformsListOrOptions;
  38418. uniformsList = options.uniformsNames;
  38419. uniformBuffersList = options.uniformBuffersNames;
  38420. samplersList = options.samplers;
  38421. defines = options.defines;
  38422. maxSimultaneousLights = options.maxSimultaneousLights;
  38423. }
  38424. else {
  38425. uniformsList = uniformsListOrOptions;
  38426. if (!samplersList) {
  38427. samplersList = [];
  38428. }
  38429. }
  38430. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  38431. if (!defines["LIGHT" + lightIndex]) {
  38432. break;
  38433. }
  38434. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  38435. if (uniformBuffersList) {
  38436. uniformBuffersList.push("Light" + lightIndex);
  38437. }
  38438. samplersList.push("shadowSampler" + lightIndex);
  38439. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  38440. samplersList.push("projectionLightSampler" + lightIndex);
  38441. uniformsList.push("textureProjectionMatrix" + lightIndex);
  38442. }
  38443. }
  38444. if (defines["NUM_MORPH_INFLUENCERS"]) {
  38445. uniformsList.push("morphTargetInfluences");
  38446. }
  38447. };
  38448. /**
  38449. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  38450. * @param defines The defines to update while falling back
  38451. * @param fallbacks The authorized effect fallbacks
  38452. * @param maxSimultaneousLights The maximum number of lights allowed
  38453. * @param rank the current rank of the Effect
  38454. * @returns The newly affected rank
  38455. */
  38456. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  38457. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  38458. if (rank === void 0) { rank = 0; }
  38459. var lightFallbackRank = 0;
  38460. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  38461. if (!defines["LIGHT" + lightIndex]) {
  38462. break;
  38463. }
  38464. if (lightIndex > 0) {
  38465. lightFallbackRank = rank + lightIndex;
  38466. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  38467. }
  38468. if (!defines["SHADOWS"]) {
  38469. if (defines["SHADOW" + lightIndex]) {
  38470. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  38471. }
  38472. if (defines["SHADOWPCF" + lightIndex]) {
  38473. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  38474. }
  38475. if (defines["SHADOWESM" + lightIndex]) {
  38476. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  38477. }
  38478. }
  38479. }
  38480. return lightFallbackRank++;
  38481. };
  38482. /**
  38483. * Prepares the list of attributes required for morph targets according to the effect defines.
  38484. * @param attribs The current list of supported attribs
  38485. * @param mesh The mesh to prepare the morph targets attributes for
  38486. * @param defines The current Defines of the effect
  38487. */
  38488. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  38489. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  38490. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  38491. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  38492. var manager = mesh.morphTargetManager;
  38493. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  38494. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  38495. for (var index = 0; index < influencers; index++) {
  38496. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  38497. if (normal) {
  38498. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  38499. }
  38500. if (tangent) {
  38501. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  38502. }
  38503. if (attribs.length > maxAttributesCount) {
  38504. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  38505. }
  38506. }
  38507. }
  38508. };
  38509. /**
  38510. * Prepares the list of attributes required for bones according to the effect defines.
  38511. * @param attribs The current list of supported attribs
  38512. * @param mesh The mesh to prepare the bones attributes for
  38513. * @param defines The current Defines of the effect
  38514. * @param fallbacks The current efffect fallback strategy
  38515. */
  38516. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  38517. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  38518. fallbacks.addCPUSkinningFallback(0, mesh);
  38519. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  38520. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  38521. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  38522. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  38523. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  38524. }
  38525. }
  38526. };
  38527. /**
  38528. * Prepares the list of attributes required for instances according to the effect defines.
  38529. * @param attribs The current list of supported attribs
  38530. * @param defines The current Defines of the effect
  38531. */
  38532. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  38533. if (defines["INSTANCES"]) {
  38534. attribs.push("world0");
  38535. attribs.push("world1");
  38536. attribs.push("world2");
  38537. attribs.push("world3");
  38538. }
  38539. };
  38540. /**
  38541. * Binds the light shadow information to the effect for the given mesh.
  38542. * @param light The light containing the generator
  38543. * @param scene The scene the lights belongs to
  38544. * @param mesh The mesh we are binding the information to render
  38545. * @param lightIndex The light index in the effect used to render the mesh
  38546. * @param effect The effect we are binding the data to
  38547. */
  38548. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  38549. if (light.shadowEnabled && mesh.receiveShadows) {
  38550. var shadowGenerator = light.getShadowGenerator();
  38551. if (shadowGenerator) {
  38552. shadowGenerator.bindShadowLight(lightIndex, effect);
  38553. }
  38554. }
  38555. };
  38556. /**
  38557. * Binds the light information to the effect.
  38558. * @param light The light containing the generator
  38559. * @param effect The effect we are binding the data to
  38560. * @param lightIndex The light index in the effect used to render
  38561. */
  38562. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  38563. light.transferToEffect(effect, lightIndex + "");
  38564. };
  38565. /**
  38566. * Binds the lights information from the scene to the effect for the given mesh.
  38567. * @param scene The scene the lights belongs to
  38568. * @param mesh The mesh we are binding the information to render
  38569. * @param effect The effect we are binding the data to
  38570. * @param defines The generated defines for the effect
  38571. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  38572. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  38573. */
  38574. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  38575. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  38576. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  38577. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  38578. for (var i = 0; i < len; i++) {
  38579. var light = mesh._lightSources[i];
  38580. var iAsString = i.toString();
  38581. var scaledIntensity = light.getScaledIntensity();
  38582. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  38583. MaterialHelper.BindLightProperties(light, effect, i);
  38584. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  38585. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  38586. if (defines["SPECULARTERM"]) {
  38587. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  38588. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  38589. }
  38590. // Shadows
  38591. if (scene.shadowsEnabled) {
  38592. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  38593. }
  38594. light._uniformBuffer.update();
  38595. }
  38596. };
  38597. /**
  38598. * Binds the fog information from the scene to the effect for the given mesh.
  38599. * @param scene The scene the lights belongs to
  38600. * @param mesh The mesh we are binding the information to render
  38601. * @param effect The effect we are binding the data to
  38602. */
  38603. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  38604. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  38605. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  38606. effect.setColor3("vFogColor", scene.fogColor);
  38607. }
  38608. };
  38609. /**
  38610. * Binds the bones information from the mesh to the effect.
  38611. * @param mesh The mesh we are binding the information to render
  38612. * @param effect The effect we are binding the data to
  38613. */
  38614. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  38615. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  38616. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  38617. if (matrices && effect) {
  38618. effect.setMatrices("mBones", matrices);
  38619. }
  38620. }
  38621. };
  38622. /**
  38623. * Binds the morph targets information from the mesh to the effect.
  38624. * @param abstractMesh The mesh we are binding the information to render
  38625. * @param effect The effect we are binding the data to
  38626. */
  38627. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  38628. var manager = abstractMesh.morphTargetManager;
  38629. if (!abstractMesh || !manager) {
  38630. return;
  38631. }
  38632. effect.setFloatArray("morphTargetInfluences", manager.influences);
  38633. };
  38634. /**
  38635. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  38636. * @param defines The generated defines used in the effect
  38637. * @param effect The effect we are binding the data to
  38638. * @param scene The scene we are willing to render with logarithmic scale for
  38639. */
  38640. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  38641. if (defines["LOGARITHMICDEPTH"]) {
  38642. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  38643. }
  38644. };
  38645. /**
  38646. * Binds the clip plane information from the scene to the effect.
  38647. * @param scene The scene the clip plane information are extracted from
  38648. * @param effect The effect we are binding the data to
  38649. */
  38650. MaterialHelper.BindClipPlane = function (effect, scene) {
  38651. if (scene.clipPlane) {
  38652. var clipPlane = scene.clipPlane;
  38653. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  38654. }
  38655. };
  38656. return MaterialHelper;
  38657. }());
  38658. BABYLON.MaterialHelper = MaterialHelper;
  38659. })(BABYLON || (BABYLON = {}));
  38660. //# sourceMappingURL=babylon.materialHelper.js.map
  38661. var BABYLON;
  38662. (function (BABYLON) {
  38663. var PushMaterial = /** @class */ (function (_super) {
  38664. __extends(PushMaterial, _super);
  38665. function PushMaterial(name, scene) {
  38666. var _this = _super.call(this, name, scene) || this;
  38667. _this._normalMatrix = new BABYLON.Matrix();
  38668. _this.storeEffectOnSubMeshes = true;
  38669. return _this;
  38670. }
  38671. PushMaterial.prototype.getEffect = function () {
  38672. return this._activeEffect;
  38673. };
  38674. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  38675. if (!mesh) {
  38676. return false;
  38677. }
  38678. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  38679. return true;
  38680. }
  38681. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  38682. };
  38683. /**
  38684. * Binds the given world matrix to the active effect
  38685. *
  38686. * @param world the matrix to bind
  38687. */
  38688. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  38689. this._activeEffect.setMatrix("world", world);
  38690. };
  38691. /**
  38692. * Binds the given normal matrix to the active effect
  38693. *
  38694. * @param normalMatrix the matrix to bind
  38695. */
  38696. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  38697. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  38698. };
  38699. PushMaterial.prototype.bind = function (world, mesh) {
  38700. if (!mesh) {
  38701. return;
  38702. }
  38703. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  38704. };
  38705. PushMaterial.prototype._afterBind = function (mesh, effect) {
  38706. if (effect === void 0) { effect = null; }
  38707. _super.prototype._afterBind.call(this, mesh);
  38708. this.getScene()._cachedEffect = effect;
  38709. };
  38710. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  38711. if (visibility === void 0) { visibility = 1; }
  38712. return scene.isCachedMaterialInvalid(this, effect, visibility);
  38713. };
  38714. return PushMaterial;
  38715. }(BABYLON.Material));
  38716. BABYLON.PushMaterial = PushMaterial;
  38717. })(BABYLON || (BABYLON = {}));
  38718. //# sourceMappingURL=babylon.pushMaterial.js.map
  38719. var BABYLON;
  38720. (function (BABYLON) {
  38721. /** @ignore */
  38722. var StandardMaterialDefines = /** @class */ (function (_super) {
  38723. __extends(StandardMaterialDefines, _super);
  38724. function StandardMaterialDefines() {
  38725. var _this = _super.call(this) || this;
  38726. _this.MAINUV1 = false;
  38727. _this.MAINUV2 = false;
  38728. _this.DIFFUSE = false;
  38729. _this.DIFFUSEDIRECTUV = 0;
  38730. _this.AMBIENT = false;
  38731. _this.AMBIENTDIRECTUV = 0;
  38732. _this.OPACITY = false;
  38733. _this.OPACITYDIRECTUV = 0;
  38734. _this.OPACITYRGB = false;
  38735. _this.REFLECTION = false;
  38736. _this.EMISSIVE = false;
  38737. _this.EMISSIVEDIRECTUV = 0;
  38738. _this.SPECULAR = false;
  38739. _this.SPECULARDIRECTUV = 0;
  38740. _this.BUMP = false;
  38741. _this.BUMPDIRECTUV = 0;
  38742. _this.PARALLAX = false;
  38743. _this.PARALLAXOCCLUSION = false;
  38744. _this.SPECULAROVERALPHA = false;
  38745. _this.CLIPPLANE = false;
  38746. _this.ALPHATEST = false;
  38747. _this.DEPTHPREPASS = false;
  38748. _this.ALPHAFROMDIFFUSE = false;
  38749. _this.POINTSIZE = false;
  38750. _this.FOG = false;
  38751. _this.SPECULARTERM = false;
  38752. _this.DIFFUSEFRESNEL = false;
  38753. _this.OPACITYFRESNEL = false;
  38754. _this.REFLECTIONFRESNEL = false;
  38755. _this.REFRACTIONFRESNEL = false;
  38756. _this.EMISSIVEFRESNEL = false;
  38757. _this.FRESNEL = false;
  38758. _this.NORMAL = false;
  38759. _this.UV1 = false;
  38760. _this.UV2 = false;
  38761. _this.VERTEXCOLOR = false;
  38762. _this.VERTEXALPHA = false;
  38763. _this.NUM_BONE_INFLUENCERS = 0;
  38764. _this.BonesPerMesh = 0;
  38765. _this.INSTANCES = false;
  38766. _this.GLOSSINESS = false;
  38767. _this.ROUGHNESS = false;
  38768. _this.EMISSIVEASILLUMINATION = false;
  38769. _this.LINKEMISSIVEWITHDIFFUSE = false;
  38770. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  38771. _this.LIGHTMAP = false;
  38772. _this.LIGHTMAPDIRECTUV = 0;
  38773. _this.OBJECTSPACE_NORMALMAP = false;
  38774. _this.USELIGHTMAPASSHADOWMAP = false;
  38775. _this.REFLECTIONMAP_3D = false;
  38776. _this.REFLECTIONMAP_SPHERICAL = false;
  38777. _this.REFLECTIONMAP_PLANAR = false;
  38778. _this.REFLECTIONMAP_CUBIC = false;
  38779. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  38780. _this.REFLECTIONMAP_PROJECTION = false;
  38781. _this.REFLECTIONMAP_SKYBOX = false;
  38782. _this.REFLECTIONMAP_EXPLICIT = false;
  38783. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  38784. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  38785. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  38786. _this.INVERTCUBICMAP = false;
  38787. _this.LOGARITHMICDEPTH = false;
  38788. _this.REFRACTION = false;
  38789. _this.REFRACTIONMAP_3D = false;
  38790. _this.REFLECTIONOVERALPHA = false;
  38791. _this.TWOSIDEDLIGHTING = false;
  38792. _this.SHADOWFLOAT = false;
  38793. _this.MORPHTARGETS = false;
  38794. _this.MORPHTARGETS_NORMAL = false;
  38795. _this.MORPHTARGETS_TANGENT = false;
  38796. _this.NUM_MORPH_INFLUENCERS = 0;
  38797. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  38798. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  38799. _this.IMAGEPROCESSING = false;
  38800. _this.VIGNETTE = false;
  38801. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  38802. _this.VIGNETTEBLENDMODEOPAQUE = false;
  38803. _this.TONEMAPPING = false;
  38804. _this.CONTRAST = false;
  38805. _this.COLORCURVES = false;
  38806. _this.COLORGRADING = false;
  38807. _this.COLORGRADING3D = false;
  38808. _this.SAMPLER3DGREENDEPTH = false;
  38809. _this.SAMPLER3DBGRMAP = false;
  38810. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  38811. _this.EXPOSURE = false;
  38812. _this.rebuild();
  38813. return _this;
  38814. }
  38815. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  38816. var modes = [
  38817. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  38818. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  38819. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  38820. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  38821. ];
  38822. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  38823. var mode = modes_1[_i];
  38824. this[mode] = (mode === modeToEnable);
  38825. }
  38826. };
  38827. return StandardMaterialDefines;
  38828. }(BABYLON.MaterialDefines));
  38829. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  38830. var StandardMaterial = /** @class */ (function (_super) {
  38831. __extends(StandardMaterial, _super);
  38832. function StandardMaterial(name, scene) {
  38833. var _this = _super.call(this, name, scene) || this;
  38834. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  38835. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  38836. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  38837. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  38838. _this.specularPower = 64;
  38839. _this._useAlphaFromDiffuseTexture = false;
  38840. _this._useEmissiveAsIllumination = false;
  38841. _this._linkEmissiveWithDiffuse = false;
  38842. _this._useSpecularOverAlpha = false;
  38843. _this._useReflectionOverAlpha = false;
  38844. _this._disableLighting = false;
  38845. _this._useObjectSpaceNormalMap = false;
  38846. _this._useParallax = false;
  38847. _this._useParallaxOcclusion = false;
  38848. _this.parallaxScaleBias = 0.05;
  38849. _this._roughness = 0;
  38850. _this.indexOfRefraction = 0.98;
  38851. _this.invertRefractionY = true;
  38852. _this._useLightmapAsShadowmap = false;
  38853. _this._useReflectionFresnelFromSpecular = false;
  38854. _this._useGlossinessFromSpecularMapAlpha = false;
  38855. _this._maxSimultaneousLights = 4;
  38856. /**
  38857. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  38858. */
  38859. _this._invertNormalMapX = false;
  38860. /**
  38861. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  38862. */
  38863. _this._invertNormalMapY = false;
  38864. /**
  38865. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  38866. */
  38867. _this._twoSidedLighting = false;
  38868. _this._renderTargets = new BABYLON.SmartArray(16);
  38869. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  38870. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  38871. // Setup the default processing configuration to the scene.
  38872. _this._attachImageProcessingConfiguration(null);
  38873. _this.getRenderTargetTextures = function () {
  38874. _this._renderTargets.reset();
  38875. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  38876. _this._renderTargets.push(_this._reflectionTexture);
  38877. }
  38878. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  38879. _this._renderTargets.push(_this._refractionTexture);
  38880. }
  38881. return _this._renderTargets;
  38882. };
  38883. return _this;
  38884. }
  38885. ;
  38886. ;
  38887. ;
  38888. ;
  38889. ;
  38890. ;
  38891. ;
  38892. ;
  38893. ;
  38894. ;
  38895. ;
  38896. ;
  38897. ;
  38898. ;
  38899. ;
  38900. ;
  38901. ;
  38902. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  38903. /**
  38904. * Gets the image processing configuration used either in this material.
  38905. */
  38906. get: function () {
  38907. return this._imageProcessingConfiguration;
  38908. },
  38909. /**
  38910. * Sets the Default image processing configuration used either in the this material.
  38911. *
  38912. * If sets to null, the scene one is in use.
  38913. */
  38914. set: function (value) {
  38915. this._attachImageProcessingConfiguration(value);
  38916. // Ensure the effect will be rebuilt.
  38917. this._markAllSubMeshesAsTexturesDirty();
  38918. },
  38919. enumerable: true,
  38920. configurable: true
  38921. });
  38922. /**
  38923. * Attaches a new image processing configuration to the Standard Material.
  38924. * @param configuration
  38925. */
  38926. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  38927. var _this = this;
  38928. if (configuration === this._imageProcessingConfiguration) {
  38929. return;
  38930. }
  38931. // Detaches observer.
  38932. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  38933. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  38934. }
  38935. // Pick the scene configuration if needed.
  38936. if (!configuration) {
  38937. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  38938. }
  38939. else {
  38940. this._imageProcessingConfiguration = configuration;
  38941. }
  38942. // Attaches observer.
  38943. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  38944. _this._markAllSubMeshesAsImageProcessingDirty();
  38945. });
  38946. };
  38947. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  38948. /**
  38949. * Gets wether the color curves effect is enabled.
  38950. */
  38951. get: function () {
  38952. return this.imageProcessingConfiguration.colorCurvesEnabled;
  38953. },
  38954. /**
  38955. * Sets wether the color curves effect is enabled.
  38956. */
  38957. set: function (value) {
  38958. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  38959. },
  38960. enumerable: true,
  38961. configurable: true
  38962. });
  38963. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  38964. /**
  38965. * Gets wether the color grading effect is enabled.
  38966. */
  38967. get: function () {
  38968. return this.imageProcessingConfiguration.colorGradingEnabled;
  38969. },
  38970. /**
  38971. * Gets wether the color grading effect is enabled.
  38972. */
  38973. set: function (value) {
  38974. this.imageProcessingConfiguration.colorGradingEnabled = value;
  38975. },
  38976. enumerable: true,
  38977. configurable: true
  38978. });
  38979. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  38980. /**
  38981. * Gets wether tonemapping is enabled or not.
  38982. */
  38983. get: function () {
  38984. return this._imageProcessingConfiguration.toneMappingEnabled;
  38985. },
  38986. /**
  38987. * Sets wether tonemapping is enabled or not
  38988. */
  38989. set: function (value) {
  38990. this._imageProcessingConfiguration.toneMappingEnabled = value;
  38991. },
  38992. enumerable: true,
  38993. configurable: true
  38994. });
  38995. ;
  38996. ;
  38997. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  38998. /**
  38999. * The camera exposure used on this material.
  39000. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  39001. * This corresponds to a photographic exposure.
  39002. */
  39003. get: function () {
  39004. return this._imageProcessingConfiguration.exposure;
  39005. },
  39006. /**
  39007. * The camera exposure used on this material.
  39008. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  39009. * This corresponds to a photographic exposure.
  39010. */
  39011. set: function (value) {
  39012. this._imageProcessingConfiguration.exposure = value;
  39013. },
  39014. enumerable: true,
  39015. configurable: true
  39016. });
  39017. ;
  39018. ;
  39019. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  39020. /**
  39021. * Gets The camera contrast used on this material.
  39022. */
  39023. get: function () {
  39024. return this._imageProcessingConfiguration.contrast;
  39025. },
  39026. /**
  39027. * Sets The camera contrast used on this material.
  39028. */
  39029. set: function (value) {
  39030. this._imageProcessingConfiguration.contrast = value;
  39031. },
  39032. enumerable: true,
  39033. configurable: true
  39034. });
  39035. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  39036. /**
  39037. * Gets the Color Grading 2D Lookup Texture.
  39038. */
  39039. get: function () {
  39040. return this._imageProcessingConfiguration.colorGradingTexture;
  39041. },
  39042. /**
  39043. * Sets the Color Grading 2D Lookup Texture.
  39044. */
  39045. set: function (value) {
  39046. this._imageProcessingConfiguration.colorGradingTexture = value;
  39047. },
  39048. enumerable: true,
  39049. configurable: true
  39050. });
  39051. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  39052. /**
  39053. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  39054. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  39055. * 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;
  39056. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  39057. */
  39058. get: function () {
  39059. return this._imageProcessingConfiguration.colorCurves;
  39060. },
  39061. /**
  39062. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  39063. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  39064. * 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;
  39065. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  39066. */
  39067. set: function (value) {
  39068. this._imageProcessingConfiguration.colorCurves = value;
  39069. },
  39070. enumerable: true,
  39071. configurable: true
  39072. });
  39073. StandardMaterial.prototype.getClassName = function () {
  39074. return "StandardMaterial";
  39075. };
  39076. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  39077. get: function () {
  39078. return this._useLogarithmicDepth;
  39079. },
  39080. set: function (value) {
  39081. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  39082. this._markAllSubMeshesAsMiscDirty();
  39083. },
  39084. enumerable: true,
  39085. configurable: true
  39086. });
  39087. StandardMaterial.prototype.needAlphaBlending = function () {
  39088. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  39089. };
  39090. StandardMaterial.prototype.needAlphaTesting = function () {
  39091. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  39092. };
  39093. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  39094. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  39095. };
  39096. StandardMaterial.prototype.getAlphaTestTexture = function () {
  39097. return this._diffuseTexture;
  39098. };
  39099. /**
  39100. * Child classes can use it to update shaders
  39101. */
  39102. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  39103. if (useInstances === void 0) { useInstances = false; }
  39104. if (subMesh.effect && this.isFrozen) {
  39105. if (this._wasPreviouslyReady && subMesh.effect) {
  39106. return true;
  39107. }
  39108. }
  39109. if (!subMesh._materialDefines) {
  39110. subMesh._materialDefines = new StandardMaterialDefines();
  39111. }
  39112. var scene = this.getScene();
  39113. var defines = subMesh._materialDefines;
  39114. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  39115. if (defines._renderId === scene.getRenderId()) {
  39116. return true;
  39117. }
  39118. }
  39119. var engine = scene.getEngine();
  39120. // Lights
  39121. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  39122. // Textures
  39123. if (defines._areTexturesDirty) {
  39124. defines._needUVs = false;
  39125. defines.MAINUV1 = false;
  39126. defines.MAINUV2 = false;
  39127. if (scene.texturesEnabled) {
  39128. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  39129. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  39130. return false;
  39131. }
  39132. else {
  39133. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  39134. }
  39135. }
  39136. else {
  39137. defines.DIFFUSE = false;
  39138. }
  39139. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  39140. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  39141. return false;
  39142. }
  39143. else {
  39144. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  39145. }
  39146. }
  39147. else {
  39148. defines.AMBIENT = false;
  39149. }
  39150. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  39151. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  39152. return false;
  39153. }
  39154. else {
  39155. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  39156. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  39157. }
  39158. }
  39159. else {
  39160. defines.OPACITY = false;
  39161. }
  39162. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  39163. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  39164. return false;
  39165. }
  39166. else {
  39167. defines._needNormals = true;
  39168. defines.REFLECTION = true;
  39169. defines.ROUGHNESS = (this._roughness > 0);
  39170. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  39171. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  39172. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  39173. switch (this._reflectionTexture.coordinatesMode) {
  39174. case BABYLON.Texture.CUBIC_MODE:
  39175. case BABYLON.Texture.INVCUBIC_MODE:
  39176. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  39177. break;
  39178. case BABYLON.Texture.EXPLICIT_MODE:
  39179. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  39180. break;
  39181. case BABYLON.Texture.PLANAR_MODE:
  39182. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  39183. break;
  39184. case BABYLON.Texture.PROJECTION_MODE:
  39185. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  39186. break;
  39187. case BABYLON.Texture.SKYBOX_MODE:
  39188. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  39189. break;
  39190. case BABYLON.Texture.SPHERICAL_MODE:
  39191. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  39192. break;
  39193. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  39194. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  39195. break;
  39196. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  39197. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  39198. break;
  39199. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  39200. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  39201. break;
  39202. }
  39203. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  39204. }
  39205. }
  39206. else {
  39207. defines.REFLECTION = false;
  39208. }
  39209. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  39210. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  39211. return false;
  39212. }
  39213. else {
  39214. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  39215. }
  39216. }
  39217. else {
  39218. defines.EMISSIVE = false;
  39219. }
  39220. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  39221. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  39222. return false;
  39223. }
  39224. else {
  39225. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  39226. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  39227. }
  39228. }
  39229. else {
  39230. defines.LIGHTMAP = false;
  39231. }
  39232. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  39233. if (!this._specularTexture.isReadyOrNotBlocking()) {
  39234. return false;
  39235. }
  39236. else {
  39237. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  39238. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  39239. }
  39240. }
  39241. else {
  39242. defines.SPECULAR = false;
  39243. }
  39244. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  39245. // Bump texure can not be not blocking.
  39246. if (!this._bumpTexture.isReady()) {
  39247. return false;
  39248. }
  39249. else {
  39250. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  39251. defines.PARALLAX = this._useParallax;
  39252. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  39253. }
  39254. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  39255. }
  39256. else {
  39257. defines.BUMP = false;
  39258. }
  39259. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  39260. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  39261. return false;
  39262. }
  39263. else {
  39264. defines._needUVs = true;
  39265. defines.REFRACTION = true;
  39266. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  39267. }
  39268. }
  39269. else {
  39270. defines.REFRACTION = false;
  39271. }
  39272. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  39273. }
  39274. else {
  39275. defines.DIFFUSE = false;
  39276. defines.AMBIENT = false;
  39277. defines.OPACITY = false;
  39278. defines.REFLECTION = false;
  39279. defines.EMISSIVE = false;
  39280. defines.LIGHTMAP = false;
  39281. defines.BUMP = false;
  39282. defines.REFRACTION = false;
  39283. }
  39284. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  39285. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  39286. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  39287. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  39288. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  39289. }
  39290. if (defines._areImageProcessingDirty) {
  39291. if (!this._imageProcessingConfiguration.isReady()) {
  39292. return false;
  39293. }
  39294. this._imageProcessingConfiguration.prepareDefines(defines);
  39295. }
  39296. if (defines._areFresnelDirty) {
  39297. if (StandardMaterial.FresnelEnabled) {
  39298. // Fresnel
  39299. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  39300. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  39301. this._reflectionFresnelParameters) {
  39302. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  39303. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  39304. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  39305. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  39306. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  39307. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  39308. defines._needNormals = true;
  39309. defines.FRESNEL = true;
  39310. }
  39311. }
  39312. else {
  39313. defines.FRESNEL = false;
  39314. }
  39315. }
  39316. // Misc.
  39317. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  39318. // Attribs
  39319. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  39320. // Values that need to be evaluated on every frame
  39321. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  39322. // Get correct effect
  39323. if (defines.isDirty) {
  39324. defines.markAsProcessed();
  39325. scene.resetCachedMaterial();
  39326. // Fallbacks
  39327. var fallbacks = new BABYLON.EffectFallbacks();
  39328. if (defines.REFLECTION) {
  39329. fallbacks.addFallback(0, "REFLECTION");
  39330. }
  39331. if (defines.SPECULAR) {
  39332. fallbacks.addFallback(0, "SPECULAR");
  39333. }
  39334. if (defines.BUMP) {
  39335. fallbacks.addFallback(0, "BUMP");
  39336. }
  39337. if (defines.PARALLAX) {
  39338. fallbacks.addFallback(1, "PARALLAX");
  39339. }
  39340. if (defines.PARALLAXOCCLUSION) {
  39341. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  39342. }
  39343. if (defines.SPECULAROVERALPHA) {
  39344. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  39345. }
  39346. if (defines.FOG) {
  39347. fallbacks.addFallback(1, "FOG");
  39348. }
  39349. if (defines.POINTSIZE) {
  39350. fallbacks.addFallback(0, "POINTSIZE");
  39351. }
  39352. if (defines.LOGARITHMICDEPTH) {
  39353. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  39354. }
  39355. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  39356. if (defines.SPECULARTERM) {
  39357. fallbacks.addFallback(0, "SPECULARTERM");
  39358. }
  39359. if (defines.DIFFUSEFRESNEL) {
  39360. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  39361. }
  39362. if (defines.OPACITYFRESNEL) {
  39363. fallbacks.addFallback(2, "OPACITYFRESNEL");
  39364. }
  39365. if (defines.REFLECTIONFRESNEL) {
  39366. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  39367. }
  39368. if (defines.EMISSIVEFRESNEL) {
  39369. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  39370. }
  39371. if (defines.FRESNEL) {
  39372. fallbacks.addFallback(4, "FRESNEL");
  39373. }
  39374. //Attributes
  39375. var attribs = [BABYLON.VertexBuffer.PositionKind];
  39376. if (defines.NORMAL) {
  39377. attribs.push(BABYLON.VertexBuffer.NormalKind);
  39378. }
  39379. if (defines.UV1) {
  39380. attribs.push(BABYLON.VertexBuffer.UVKind);
  39381. }
  39382. if (defines.UV2) {
  39383. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  39384. }
  39385. if (defines.VERTEXCOLOR) {
  39386. attribs.push(BABYLON.VertexBuffer.ColorKind);
  39387. }
  39388. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  39389. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  39390. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  39391. var shaderName = "default";
  39392. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  39393. "vFogInfos", "vFogColor", "pointSize",
  39394. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  39395. "mBones",
  39396. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  39397. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  39398. "vReflectionPosition", "vReflectionSize",
  39399. "logarithmicDepthConstant", "vTangentSpaceParams"
  39400. ];
  39401. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  39402. var uniformBuffers = ["Material", "Scene"];
  39403. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  39404. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  39405. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  39406. uniformsNames: uniforms,
  39407. uniformBuffersNames: uniformBuffers,
  39408. samplers: samplers,
  39409. defines: defines,
  39410. maxSimultaneousLights: this._maxSimultaneousLights
  39411. });
  39412. if (this.customShaderNameResolve) {
  39413. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  39414. }
  39415. var join = defines.toString();
  39416. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  39417. attributes: attribs,
  39418. uniformsNames: uniforms,
  39419. uniformBuffersNames: uniformBuffers,
  39420. samplers: samplers,
  39421. defines: join,
  39422. fallbacks: fallbacks,
  39423. onCompiled: this.onCompiled,
  39424. onError: this.onError,
  39425. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  39426. }, engine), defines);
  39427. this.buildUniformLayout();
  39428. }
  39429. if (!subMesh.effect || !subMesh.effect.isReady()) {
  39430. return false;
  39431. }
  39432. defines._renderId = scene.getRenderId();
  39433. this._wasPreviouslyReady = true;
  39434. return true;
  39435. };
  39436. StandardMaterial.prototype.buildUniformLayout = function () {
  39437. // Order is important !
  39438. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  39439. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  39440. this._uniformBuffer.addUniform("opacityParts", 4);
  39441. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  39442. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  39443. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  39444. this._uniformBuffer.addUniform("refractionRightColor", 4);
  39445. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  39446. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  39447. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  39448. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  39449. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  39450. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  39451. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  39452. this._uniformBuffer.addUniform("vReflectionSize", 3);
  39453. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  39454. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  39455. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  39456. this._uniformBuffer.addUniform("vBumpInfos", 3);
  39457. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  39458. this._uniformBuffer.addUniform("ambientMatrix", 16);
  39459. this._uniformBuffer.addUniform("opacityMatrix", 16);
  39460. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  39461. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  39462. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  39463. this._uniformBuffer.addUniform("specularMatrix", 16);
  39464. this._uniformBuffer.addUniform("bumpMatrix", 16);
  39465. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  39466. this._uniformBuffer.addUniform("refractionMatrix", 16);
  39467. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  39468. this._uniformBuffer.addUniform("vSpecularColor", 4);
  39469. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  39470. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  39471. this._uniformBuffer.addUniform("pointSize", 1);
  39472. this._uniformBuffer.create();
  39473. };
  39474. StandardMaterial.prototype.unbind = function () {
  39475. if (this._activeEffect) {
  39476. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  39477. this._activeEffect.setTexture("reflection2DSampler", null);
  39478. }
  39479. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  39480. this._activeEffect.setTexture("refraction2DSampler", null);
  39481. }
  39482. }
  39483. _super.prototype.unbind.call(this);
  39484. };
  39485. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  39486. var scene = this.getScene();
  39487. var defines = subMesh._materialDefines;
  39488. if (!defines) {
  39489. return;
  39490. }
  39491. var effect = subMesh.effect;
  39492. if (!effect) {
  39493. return;
  39494. }
  39495. this._activeEffect = effect;
  39496. // Matrices
  39497. this.bindOnlyWorldMatrix(world);
  39498. // Normal Matrix
  39499. if (defines.OBJECTSPACE_NORMALMAP) {
  39500. world.toNormalMatrix(this._normalMatrix);
  39501. this.bindOnlyNormalMatrix(this._normalMatrix);
  39502. }
  39503. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  39504. // Bones
  39505. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  39506. if (mustRebind) {
  39507. this._uniformBuffer.bindToEffect(effect, "Material");
  39508. this.bindViewProjection(effect);
  39509. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  39510. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  39511. // Fresnel
  39512. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  39513. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  39514. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  39515. }
  39516. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  39517. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  39518. }
  39519. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  39520. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  39521. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  39522. }
  39523. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  39524. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  39525. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  39526. }
  39527. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  39528. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  39529. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  39530. }
  39531. }
  39532. // Textures
  39533. if (scene.texturesEnabled) {
  39534. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  39535. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  39536. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  39537. }
  39538. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  39539. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  39540. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  39541. }
  39542. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  39543. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  39544. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  39545. }
  39546. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  39547. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  39548. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  39549. if (this._reflectionTexture.boundingBoxSize) {
  39550. var cubeTexture = this._reflectionTexture;
  39551. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  39552. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  39553. }
  39554. }
  39555. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  39556. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  39557. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  39558. }
  39559. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  39560. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  39561. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  39562. }
  39563. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  39564. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  39565. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  39566. }
  39567. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  39568. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  39569. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  39570. if (scene._mirroredCameraPosition) {
  39571. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  39572. }
  39573. else {
  39574. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  39575. }
  39576. }
  39577. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  39578. var depth = 1.0;
  39579. if (!this._refractionTexture.isCube) {
  39580. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  39581. if (this._refractionTexture.depth) {
  39582. depth = this._refractionTexture.depth;
  39583. }
  39584. }
  39585. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  39586. }
  39587. }
  39588. // Point size
  39589. if (this.pointsCloud) {
  39590. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  39591. }
  39592. if (defines.SPECULARTERM) {
  39593. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  39594. }
  39595. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  39596. // Diffuse
  39597. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  39598. }
  39599. // Textures
  39600. if (scene.texturesEnabled) {
  39601. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  39602. effect.setTexture("diffuseSampler", this._diffuseTexture);
  39603. }
  39604. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  39605. effect.setTexture("ambientSampler", this._ambientTexture);
  39606. }
  39607. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  39608. effect.setTexture("opacitySampler", this._opacityTexture);
  39609. }
  39610. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  39611. if (this._reflectionTexture.isCube) {
  39612. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  39613. }
  39614. else {
  39615. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  39616. }
  39617. }
  39618. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  39619. effect.setTexture("emissiveSampler", this._emissiveTexture);
  39620. }
  39621. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  39622. effect.setTexture("lightmapSampler", this._lightmapTexture);
  39623. }
  39624. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  39625. effect.setTexture("specularSampler", this._specularTexture);
  39626. }
  39627. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  39628. effect.setTexture("bumpSampler", this._bumpTexture);
  39629. }
  39630. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  39631. var depth = 1.0;
  39632. if (this._refractionTexture.isCube) {
  39633. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  39634. }
  39635. else {
  39636. effect.setTexture("refraction2DSampler", this._refractionTexture);
  39637. }
  39638. }
  39639. }
  39640. // Clip plane
  39641. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  39642. // Colors
  39643. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  39644. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  39645. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  39646. }
  39647. if (mustRebind || !this.isFrozen) {
  39648. // Lights
  39649. if (scene.lightsEnabled && !this._disableLighting) {
  39650. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  39651. }
  39652. // View
  39653. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  39654. this.bindView(effect);
  39655. }
  39656. // Fog
  39657. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  39658. // Morph targets
  39659. if (defines.NUM_MORPH_INFLUENCERS) {
  39660. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  39661. }
  39662. // Log. depth
  39663. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  39664. // image processing
  39665. if (!this._imageProcessingConfiguration.applyByPostProcess) {
  39666. this._imageProcessingConfiguration.bind(this._activeEffect);
  39667. }
  39668. }
  39669. this._uniformBuffer.update();
  39670. this._afterBind(mesh, this._activeEffect);
  39671. };
  39672. StandardMaterial.prototype.getAnimatables = function () {
  39673. var results = [];
  39674. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  39675. results.push(this._diffuseTexture);
  39676. }
  39677. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  39678. results.push(this._ambientTexture);
  39679. }
  39680. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  39681. results.push(this._opacityTexture);
  39682. }
  39683. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  39684. results.push(this._reflectionTexture);
  39685. }
  39686. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  39687. results.push(this._emissiveTexture);
  39688. }
  39689. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  39690. results.push(this._specularTexture);
  39691. }
  39692. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  39693. results.push(this._bumpTexture);
  39694. }
  39695. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  39696. results.push(this._lightmapTexture);
  39697. }
  39698. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  39699. results.push(this._refractionTexture);
  39700. }
  39701. return results;
  39702. };
  39703. StandardMaterial.prototype.getActiveTextures = function () {
  39704. var activeTextures = _super.prototype.getActiveTextures.call(this);
  39705. if (this._diffuseTexture) {
  39706. activeTextures.push(this._diffuseTexture);
  39707. }
  39708. if (this._ambientTexture) {
  39709. activeTextures.push(this._ambientTexture);
  39710. }
  39711. if (this._opacityTexture) {
  39712. activeTextures.push(this._opacityTexture);
  39713. }
  39714. if (this._reflectionTexture) {
  39715. activeTextures.push(this._reflectionTexture);
  39716. }
  39717. if (this._emissiveTexture) {
  39718. activeTextures.push(this._emissiveTexture);
  39719. }
  39720. if (this._specularTexture) {
  39721. activeTextures.push(this._specularTexture);
  39722. }
  39723. if (this._bumpTexture) {
  39724. activeTextures.push(this._bumpTexture);
  39725. }
  39726. if (this._lightmapTexture) {
  39727. activeTextures.push(this._lightmapTexture);
  39728. }
  39729. if (this._refractionTexture) {
  39730. activeTextures.push(this._refractionTexture);
  39731. }
  39732. return activeTextures;
  39733. };
  39734. StandardMaterial.prototype.hasTexture = function (texture) {
  39735. if (_super.prototype.hasTexture.call(this, texture)) {
  39736. return true;
  39737. }
  39738. if (this._diffuseTexture === texture) {
  39739. return true;
  39740. }
  39741. if (this._ambientTexture === texture) {
  39742. return true;
  39743. }
  39744. if (this._opacityTexture === texture) {
  39745. return true;
  39746. }
  39747. if (this._reflectionTexture === texture) {
  39748. return true;
  39749. }
  39750. if (this._emissiveTexture === texture) {
  39751. return true;
  39752. }
  39753. if (this._specularTexture === texture) {
  39754. return true;
  39755. }
  39756. if (this._bumpTexture === texture) {
  39757. return true;
  39758. }
  39759. if (this._lightmapTexture === texture) {
  39760. return true;
  39761. }
  39762. if (this._refractionTexture === texture) {
  39763. return true;
  39764. }
  39765. return false;
  39766. };
  39767. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  39768. if (forceDisposeTextures) {
  39769. if (this._diffuseTexture) {
  39770. this._diffuseTexture.dispose();
  39771. }
  39772. if (this._ambientTexture) {
  39773. this._ambientTexture.dispose();
  39774. }
  39775. if (this._opacityTexture) {
  39776. this._opacityTexture.dispose();
  39777. }
  39778. if (this._reflectionTexture) {
  39779. this._reflectionTexture.dispose();
  39780. }
  39781. if (this._emissiveTexture) {
  39782. this._emissiveTexture.dispose();
  39783. }
  39784. if (this._specularTexture) {
  39785. this._specularTexture.dispose();
  39786. }
  39787. if (this._bumpTexture) {
  39788. this._bumpTexture.dispose();
  39789. }
  39790. if (this._lightmapTexture) {
  39791. this._lightmapTexture.dispose();
  39792. }
  39793. if (this._refractionTexture) {
  39794. this._refractionTexture.dispose();
  39795. }
  39796. }
  39797. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  39798. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  39799. }
  39800. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  39801. };
  39802. StandardMaterial.prototype.clone = function (name) {
  39803. var _this = this;
  39804. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  39805. result.name = name;
  39806. result.id = name;
  39807. return result;
  39808. };
  39809. StandardMaterial.prototype.serialize = function () {
  39810. return BABYLON.SerializationHelper.Serialize(this);
  39811. };
  39812. // Statics
  39813. StandardMaterial.Parse = function (source, scene, rootUrl) {
  39814. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  39815. };
  39816. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  39817. get: function () {
  39818. return StandardMaterial._DiffuseTextureEnabled;
  39819. },
  39820. set: function (value) {
  39821. if (StandardMaterial._DiffuseTextureEnabled === value) {
  39822. return;
  39823. }
  39824. StandardMaterial._DiffuseTextureEnabled = value;
  39825. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39826. },
  39827. enumerable: true,
  39828. configurable: true
  39829. });
  39830. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  39831. get: function () {
  39832. return StandardMaterial._AmbientTextureEnabled;
  39833. },
  39834. set: function (value) {
  39835. if (StandardMaterial._AmbientTextureEnabled === value) {
  39836. return;
  39837. }
  39838. StandardMaterial._AmbientTextureEnabled = value;
  39839. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39840. },
  39841. enumerable: true,
  39842. configurable: true
  39843. });
  39844. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  39845. get: function () {
  39846. return StandardMaterial._OpacityTextureEnabled;
  39847. },
  39848. set: function (value) {
  39849. if (StandardMaterial._OpacityTextureEnabled === value) {
  39850. return;
  39851. }
  39852. StandardMaterial._OpacityTextureEnabled = value;
  39853. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39854. },
  39855. enumerable: true,
  39856. configurable: true
  39857. });
  39858. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  39859. get: function () {
  39860. return StandardMaterial._ReflectionTextureEnabled;
  39861. },
  39862. set: function (value) {
  39863. if (StandardMaterial._ReflectionTextureEnabled === value) {
  39864. return;
  39865. }
  39866. StandardMaterial._ReflectionTextureEnabled = value;
  39867. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39868. },
  39869. enumerable: true,
  39870. configurable: true
  39871. });
  39872. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  39873. get: function () {
  39874. return StandardMaterial._EmissiveTextureEnabled;
  39875. },
  39876. set: function (value) {
  39877. if (StandardMaterial._EmissiveTextureEnabled === value) {
  39878. return;
  39879. }
  39880. StandardMaterial._EmissiveTextureEnabled = value;
  39881. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39882. },
  39883. enumerable: true,
  39884. configurable: true
  39885. });
  39886. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  39887. get: function () {
  39888. return StandardMaterial._SpecularTextureEnabled;
  39889. },
  39890. set: function (value) {
  39891. if (StandardMaterial._SpecularTextureEnabled === value) {
  39892. return;
  39893. }
  39894. StandardMaterial._SpecularTextureEnabled = value;
  39895. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39896. },
  39897. enumerable: true,
  39898. configurable: true
  39899. });
  39900. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  39901. get: function () {
  39902. return StandardMaterial._BumpTextureEnabled;
  39903. },
  39904. set: function (value) {
  39905. if (StandardMaterial._BumpTextureEnabled === value) {
  39906. return;
  39907. }
  39908. StandardMaterial._BumpTextureEnabled = value;
  39909. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39910. },
  39911. enumerable: true,
  39912. configurable: true
  39913. });
  39914. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  39915. get: function () {
  39916. return StandardMaterial._LightmapTextureEnabled;
  39917. },
  39918. set: function (value) {
  39919. if (StandardMaterial._LightmapTextureEnabled === value) {
  39920. return;
  39921. }
  39922. StandardMaterial._LightmapTextureEnabled = value;
  39923. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39924. },
  39925. enumerable: true,
  39926. configurable: true
  39927. });
  39928. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  39929. get: function () {
  39930. return StandardMaterial._RefractionTextureEnabled;
  39931. },
  39932. set: function (value) {
  39933. if (StandardMaterial._RefractionTextureEnabled === value) {
  39934. return;
  39935. }
  39936. StandardMaterial._RefractionTextureEnabled = value;
  39937. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39938. },
  39939. enumerable: true,
  39940. configurable: true
  39941. });
  39942. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  39943. get: function () {
  39944. return StandardMaterial._ColorGradingTextureEnabled;
  39945. },
  39946. set: function (value) {
  39947. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  39948. return;
  39949. }
  39950. StandardMaterial._ColorGradingTextureEnabled = value;
  39951. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39952. },
  39953. enumerable: true,
  39954. configurable: true
  39955. });
  39956. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  39957. get: function () {
  39958. return StandardMaterial._FresnelEnabled;
  39959. },
  39960. set: function (value) {
  39961. if (StandardMaterial._FresnelEnabled === value) {
  39962. return;
  39963. }
  39964. StandardMaterial._FresnelEnabled = value;
  39965. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  39966. },
  39967. enumerable: true,
  39968. configurable: true
  39969. });
  39970. // Flags used to enable or disable a type of texture for all Standard Materials
  39971. StandardMaterial._DiffuseTextureEnabled = true;
  39972. StandardMaterial._AmbientTextureEnabled = true;
  39973. StandardMaterial._OpacityTextureEnabled = true;
  39974. StandardMaterial._ReflectionTextureEnabled = true;
  39975. StandardMaterial._EmissiveTextureEnabled = true;
  39976. StandardMaterial._SpecularTextureEnabled = true;
  39977. StandardMaterial._BumpTextureEnabled = true;
  39978. StandardMaterial._LightmapTextureEnabled = true;
  39979. StandardMaterial._RefractionTextureEnabled = true;
  39980. StandardMaterial._ColorGradingTextureEnabled = true;
  39981. StandardMaterial._FresnelEnabled = true;
  39982. __decorate([
  39983. BABYLON.serializeAsTexture("diffuseTexture")
  39984. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  39985. __decorate([
  39986. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  39987. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  39988. __decorate([
  39989. BABYLON.serializeAsTexture("ambientTexture")
  39990. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  39991. __decorate([
  39992. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39993. ], StandardMaterial.prototype, "ambientTexture", void 0);
  39994. __decorate([
  39995. BABYLON.serializeAsTexture("opacityTexture")
  39996. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  39997. __decorate([
  39998. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  39999. ], StandardMaterial.prototype, "opacityTexture", void 0);
  40000. __decorate([
  40001. BABYLON.serializeAsTexture("reflectionTexture")
  40002. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  40003. __decorate([
  40004. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40005. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  40006. __decorate([
  40007. BABYLON.serializeAsTexture("emissiveTexture")
  40008. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  40009. __decorate([
  40010. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40011. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  40012. __decorate([
  40013. BABYLON.serializeAsTexture("specularTexture")
  40014. ], StandardMaterial.prototype, "_specularTexture", void 0);
  40015. __decorate([
  40016. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40017. ], StandardMaterial.prototype, "specularTexture", void 0);
  40018. __decorate([
  40019. BABYLON.serializeAsTexture("bumpTexture")
  40020. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  40021. __decorate([
  40022. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40023. ], StandardMaterial.prototype, "bumpTexture", void 0);
  40024. __decorate([
  40025. BABYLON.serializeAsTexture("lightmapTexture")
  40026. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  40027. __decorate([
  40028. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40029. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  40030. __decorate([
  40031. BABYLON.serializeAsTexture("refractionTexture")
  40032. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  40033. __decorate([
  40034. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40035. ], StandardMaterial.prototype, "refractionTexture", void 0);
  40036. __decorate([
  40037. BABYLON.serializeAsColor3("ambient")
  40038. ], StandardMaterial.prototype, "ambientColor", void 0);
  40039. __decorate([
  40040. BABYLON.serializeAsColor3("diffuse")
  40041. ], StandardMaterial.prototype, "diffuseColor", void 0);
  40042. __decorate([
  40043. BABYLON.serializeAsColor3("specular")
  40044. ], StandardMaterial.prototype, "specularColor", void 0);
  40045. __decorate([
  40046. BABYLON.serializeAsColor3("emissive")
  40047. ], StandardMaterial.prototype, "emissiveColor", void 0);
  40048. __decorate([
  40049. BABYLON.serialize()
  40050. ], StandardMaterial.prototype, "specularPower", void 0);
  40051. __decorate([
  40052. BABYLON.serialize("useAlphaFromDiffuseTexture")
  40053. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  40054. __decorate([
  40055. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40056. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  40057. __decorate([
  40058. BABYLON.serialize("useEmissiveAsIllumination")
  40059. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  40060. __decorate([
  40061. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40062. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  40063. __decorate([
  40064. BABYLON.serialize("linkEmissiveWithDiffuse")
  40065. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  40066. __decorate([
  40067. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40068. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  40069. __decorate([
  40070. BABYLON.serialize("useSpecularOverAlpha")
  40071. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  40072. __decorate([
  40073. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40074. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  40075. __decorate([
  40076. BABYLON.serialize("useReflectionOverAlpha")
  40077. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  40078. __decorate([
  40079. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40080. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  40081. __decorate([
  40082. BABYLON.serialize("disableLighting")
  40083. ], StandardMaterial.prototype, "_disableLighting", void 0);
  40084. __decorate([
  40085. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  40086. ], StandardMaterial.prototype, "disableLighting", void 0);
  40087. __decorate([
  40088. BABYLON.serialize("useObjectSpaceNormalMap")
  40089. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  40090. __decorate([
  40091. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40092. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  40093. __decorate([
  40094. BABYLON.serialize("useParallax")
  40095. ], StandardMaterial.prototype, "_useParallax", void 0);
  40096. __decorate([
  40097. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40098. ], StandardMaterial.prototype, "useParallax", void 0);
  40099. __decorate([
  40100. BABYLON.serialize("useParallaxOcclusion")
  40101. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  40102. __decorate([
  40103. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40104. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  40105. __decorate([
  40106. BABYLON.serialize()
  40107. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  40108. __decorate([
  40109. BABYLON.serialize("roughness")
  40110. ], StandardMaterial.prototype, "_roughness", void 0);
  40111. __decorate([
  40112. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40113. ], StandardMaterial.prototype, "roughness", void 0);
  40114. __decorate([
  40115. BABYLON.serialize()
  40116. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  40117. __decorate([
  40118. BABYLON.serialize()
  40119. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  40120. __decorate([
  40121. BABYLON.serialize("useLightmapAsShadowmap")
  40122. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  40123. __decorate([
  40124. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40125. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  40126. __decorate([
  40127. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  40128. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  40129. __decorate([
  40130. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40131. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  40132. __decorate([
  40133. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  40134. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  40135. __decorate([
  40136. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  40137. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  40138. __decorate([
  40139. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  40140. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  40141. __decorate([
  40142. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40143. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  40144. __decorate([
  40145. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  40146. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  40147. __decorate([
  40148. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40149. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  40150. __decorate([
  40151. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  40152. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  40153. __decorate([
  40154. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40155. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  40156. __decorate([
  40157. BABYLON.serialize("useReflectionFresnelFromSpecular")
  40158. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  40159. __decorate([
  40160. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40161. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  40162. __decorate([
  40163. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  40164. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  40165. __decorate([
  40166. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40167. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  40168. __decorate([
  40169. BABYLON.serialize("maxSimultaneousLights")
  40170. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  40171. __decorate([
  40172. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  40173. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  40174. __decorate([
  40175. BABYLON.serialize("invertNormalMapX")
  40176. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  40177. __decorate([
  40178. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40179. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  40180. __decorate([
  40181. BABYLON.serialize("invertNormalMapY")
  40182. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  40183. __decorate([
  40184. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40185. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  40186. __decorate([
  40187. BABYLON.serialize("twoSidedLighting")
  40188. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  40189. __decorate([
  40190. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40191. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  40192. __decorate([
  40193. BABYLON.serialize()
  40194. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  40195. return StandardMaterial;
  40196. }(BABYLON.PushMaterial));
  40197. BABYLON.StandardMaterial = StandardMaterial;
  40198. })(BABYLON || (BABYLON = {}));
  40199. //# sourceMappingURL=babylon.standardMaterial.js.map
  40200. var BABYLON;
  40201. (function (BABYLON) {
  40202. /**
  40203. * Manages the defines for the PBR Material.
  40204. */
  40205. var PBRMaterialDefines = /** @class */ (function (_super) {
  40206. __extends(PBRMaterialDefines, _super);
  40207. /**
  40208. * Initializes the PBR Material defines.
  40209. */
  40210. function PBRMaterialDefines() {
  40211. var _this = _super.call(this) || this;
  40212. _this.PBR = true;
  40213. _this.MAINUV1 = false;
  40214. _this.MAINUV2 = false;
  40215. _this.UV1 = false;
  40216. _this.UV2 = false;
  40217. _this.ALBEDO = false;
  40218. _this.ALBEDODIRECTUV = 0;
  40219. _this.VERTEXCOLOR = false;
  40220. _this.AMBIENT = false;
  40221. _this.AMBIENTDIRECTUV = 0;
  40222. _this.AMBIENTINGRAYSCALE = false;
  40223. _this.OPACITY = false;
  40224. _this.VERTEXALPHA = false;
  40225. _this.OPACITYDIRECTUV = 0;
  40226. _this.OPACITYRGB = false;
  40227. _this.ALPHATEST = false;
  40228. _this.DEPTHPREPASS = false;
  40229. _this.ALPHABLEND = false;
  40230. _this.ALPHAFROMALBEDO = false;
  40231. _this.ALPHATESTVALUE = 0.5;
  40232. _this.SPECULAROVERALPHA = false;
  40233. _this.RADIANCEOVERALPHA = false;
  40234. _this.ALPHAFRESNEL = false;
  40235. _this.LINEARALPHAFRESNEL = false;
  40236. _this.PREMULTIPLYALPHA = false;
  40237. _this.EMISSIVE = false;
  40238. _this.EMISSIVEDIRECTUV = 0;
  40239. _this.REFLECTIVITY = false;
  40240. _this.REFLECTIVITYDIRECTUV = 0;
  40241. _this.SPECULARTERM = false;
  40242. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  40243. _this.MICROSURFACEAUTOMATIC = false;
  40244. _this.LODBASEDMICROSFURACE = false;
  40245. _this.MICROSURFACEMAP = false;
  40246. _this.MICROSURFACEMAPDIRECTUV = 0;
  40247. _this.METALLICWORKFLOW = false;
  40248. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  40249. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  40250. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  40251. _this.AOSTOREINMETALMAPRED = false;
  40252. _this.ENVIRONMENTBRDF = false;
  40253. _this.NORMAL = false;
  40254. _this.TANGENT = false;
  40255. _this.BUMP = false;
  40256. _this.BUMPDIRECTUV = 0;
  40257. _this.OBJECTSPACE_NORMALMAP = false;
  40258. _this.PARALLAX = false;
  40259. _this.PARALLAXOCCLUSION = false;
  40260. _this.NORMALXYSCALE = true;
  40261. _this.LIGHTMAP = false;
  40262. _this.LIGHTMAPDIRECTUV = 0;
  40263. _this.USELIGHTMAPASSHADOWMAP = false;
  40264. _this.REFLECTION = false;
  40265. _this.REFLECTIONMAP_3D = false;
  40266. _this.REFLECTIONMAP_SPHERICAL = false;
  40267. _this.REFLECTIONMAP_PLANAR = false;
  40268. _this.REFLECTIONMAP_CUBIC = false;
  40269. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  40270. _this.REFLECTIONMAP_PROJECTION = false;
  40271. _this.REFLECTIONMAP_SKYBOX = false;
  40272. _this.REFLECTIONMAP_EXPLICIT = false;
  40273. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  40274. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  40275. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  40276. _this.INVERTCUBICMAP = false;
  40277. _this.USESPHERICALFROMREFLECTIONMAP = false;
  40278. _this.USESPHERICALINVERTEX = false;
  40279. _this.REFLECTIONMAP_OPPOSITEZ = false;
  40280. _this.LODINREFLECTIONALPHA = false;
  40281. _this.GAMMAREFLECTION = false;
  40282. _this.RADIANCEOCCLUSION = false;
  40283. _this.HORIZONOCCLUSION = false;
  40284. _this.REFRACTION = false;
  40285. _this.REFRACTIONMAP_3D = false;
  40286. _this.REFRACTIONMAP_OPPOSITEZ = false;
  40287. _this.LODINREFRACTIONALPHA = false;
  40288. _this.GAMMAREFRACTION = false;
  40289. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  40290. _this.INSTANCES = false;
  40291. _this.NUM_BONE_INFLUENCERS = 0;
  40292. _this.BonesPerMesh = 0;
  40293. _this.NONUNIFORMSCALING = false;
  40294. _this.MORPHTARGETS = false;
  40295. _this.MORPHTARGETS_NORMAL = false;
  40296. _this.MORPHTARGETS_TANGENT = false;
  40297. _this.NUM_MORPH_INFLUENCERS = 0;
  40298. _this.IMAGEPROCESSING = false;
  40299. _this.VIGNETTE = false;
  40300. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  40301. _this.VIGNETTEBLENDMODEOPAQUE = false;
  40302. _this.TONEMAPPING = false;
  40303. _this.CONTRAST = false;
  40304. _this.COLORCURVES = false;
  40305. _this.COLORGRADING = false;
  40306. _this.COLORGRADING3D = false;
  40307. _this.SAMPLER3DGREENDEPTH = false;
  40308. _this.SAMPLER3DBGRMAP = false;
  40309. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  40310. _this.EXPOSURE = false;
  40311. _this.USEPHYSICALLIGHTFALLOFF = false;
  40312. _this.TWOSIDEDLIGHTING = false;
  40313. _this.SHADOWFLOAT = false;
  40314. _this.CLIPPLANE = false;
  40315. _this.POINTSIZE = false;
  40316. _this.FOG = false;
  40317. _this.LOGARITHMICDEPTH = false;
  40318. _this.FORCENORMALFORWARD = false;
  40319. _this.rebuild();
  40320. return _this;
  40321. }
  40322. /**
  40323. * Resets the PBR Material defines.
  40324. */
  40325. PBRMaterialDefines.prototype.reset = function () {
  40326. _super.prototype.reset.call(this);
  40327. this.ALPHATESTVALUE = 0.5;
  40328. this.PBR = true;
  40329. };
  40330. return PBRMaterialDefines;
  40331. }(BABYLON.MaterialDefines));
  40332. /**
  40333. * The Physically based material base class of BJS.
  40334. *
  40335. * This offers the main features of a standard PBR material.
  40336. * For more information, please refer to the documentation :
  40337. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  40338. */
  40339. var PBRBaseMaterial = /** @class */ (function (_super) {
  40340. __extends(PBRBaseMaterial, _super);
  40341. /**
  40342. * Instantiates a new PBRMaterial instance.
  40343. *
  40344. * @param name The material name
  40345. * @param scene The scene the material will be use in.
  40346. */
  40347. function PBRBaseMaterial(name, scene) {
  40348. var _this = _super.call(this, name, scene) || this;
  40349. /**
  40350. * Intensity of the direct lights e.g. the four lights available in your scene.
  40351. * This impacts both the direct diffuse and specular highlights.
  40352. */
  40353. _this._directIntensity = 1.0;
  40354. /**
  40355. * Intensity of the emissive part of the material.
  40356. * This helps controlling the emissive effect without modifying the emissive color.
  40357. */
  40358. _this._emissiveIntensity = 1.0;
  40359. /**
  40360. * Intensity of the environment e.g. how much the environment will light the object
  40361. * either through harmonics for rough material or through the refelction for shiny ones.
  40362. */
  40363. _this._environmentIntensity = 1.0;
  40364. /**
  40365. * This is a special control allowing the reduction of the specular highlights coming from the
  40366. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  40367. */
  40368. _this._specularIntensity = 1.0;
  40369. /**
  40370. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  40371. */
  40372. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  40373. /**
  40374. * Debug Control allowing disabling the bump map on this material.
  40375. */
  40376. _this._disableBumpMap = false;
  40377. /**
  40378. * AKA Occlusion Texture Intensity in other nomenclature.
  40379. */
  40380. _this._ambientTextureStrength = 1.0;
  40381. /**
  40382. * The color of a material in ambient lighting.
  40383. */
  40384. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  40385. /**
  40386. * AKA Diffuse Color in other nomenclature.
  40387. */
  40388. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  40389. /**
  40390. * AKA Specular Color in other nomenclature.
  40391. */
  40392. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  40393. /**
  40394. * The color applied when light is reflected from a material.
  40395. */
  40396. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  40397. /**
  40398. * The color applied when light is emitted from a material.
  40399. */
  40400. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  40401. /**
  40402. * AKA Glossiness in other nomenclature.
  40403. */
  40404. _this._microSurface = 0.9;
  40405. /**
  40406. * source material index of refraction (IOR)' / 'destination material IOR.
  40407. */
  40408. _this._indexOfRefraction = 0.66;
  40409. /**
  40410. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  40411. */
  40412. _this._invertRefractionY = false;
  40413. /**
  40414. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  40415. * Materials half opaque for instance using refraction could benefit from this control.
  40416. */
  40417. _this._linkRefractionWithTransparency = false;
  40418. /**
  40419. * Specifies that the material will use the light map as a show map.
  40420. */
  40421. _this._useLightmapAsShadowmap = false;
  40422. /**
  40423. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  40424. * makes the reflect vector face the model (under horizon).
  40425. */
  40426. _this._useHorizonOcclusion = true;
  40427. /**
  40428. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  40429. * too much the area relying on ambient texture to define their ambient occlusion.
  40430. */
  40431. _this._useRadianceOcclusion = true;
  40432. /**
  40433. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  40434. */
  40435. _this._useAlphaFromAlbedoTexture = false;
  40436. /**
  40437. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  40438. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  40439. */
  40440. _this._useSpecularOverAlpha = true;
  40441. /**
  40442. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  40443. */
  40444. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  40445. /**
  40446. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  40447. */
  40448. _this._useRoughnessFromMetallicTextureAlpha = true;
  40449. /**
  40450. * Specifies if the metallic texture contains the roughness information in its green channel.
  40451. */
  40452. _this._useRoughnessFromMetallicTextureGreen = false;
  40453. /**
  40454. * Specifies if the metallic texture contains the metallness information in its blue channel.
  40455. */
  40456. _this._useMetallnessFromMetallicTextureBlue = false;
  40457. /**
  40458. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  40459. */
  40460. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  40461. /**
  40462. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  40463. */
  40464. _this._useAmbientInGrayScale = false;
  40465. /**
  40466. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  40467. * The material will try to infer what glossiness each pixel should be.
  40468. */
  40469. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  40470. /**
  40471. * BJS is using an harcoded light falloff based on a manually sets up range.
  40472. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  40473. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  40474. */
  40475. _this._usePhysicalLightFalloff = true;
  40476. /**
  40477. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  40478. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  40479. */
  40480. _this._useRadianceOverAlpha = true;
  40481. /**
  40482. * Allows using an object space normal map (instead of tangent space).
  40483. */
  40484. _this._useObjectSpaceNormalMap = false;
  40485. /**
  40486. * Allows using the bump map in parallax mode.
  40487. */
  40488. _this._useParallax = false;
  40489. /**
  40490. * Allows using the bump map in parallax occlusion mode.
  40491. */
  40492. _this._useParallaxOcclusion = false;
  40493. /**
  40494. * Controls the scale bias of the parallax mode.
  40495. */
  40496. _this._parallaxScaleBias = 0.05;
  40497. /**
  40498. * If sets to true, disables all the lights affecting the material.
  40499. */
  40500. _this._disableLighting = false;
  40501. /**
  40502. * Number of Simultaneous lights allowed on the material.
  40503. */
  40504. _this._maxSimultaneousLights = 4;
  40505. /**
  40506. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  40507. */
  40508. _this._invertNormalMapX = false;
  40509. /**
  40510. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  40511. */
  40512. _this._invertNormalMapY = false;
  40513. /**
  40514. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  40515. */
  40516. _this._twoSidedLighting = false;
  40517. /**
  40518. * Defines the alpha limits in alpha test mode.
  40519. */
  40520. _this._alphaCutOff = 0.4;
  40521. /**
  40522. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  40523. */
  40524. _this._forceAlphaTest = false;
  40525. /**
  40526. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  40527. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  40528. */
  40529. _this._useAlphaFresnel = false;
  40530. /**
  40531. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  40532. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  40533. */
  40534. _this._useLinearAlphaFresnel = false;
  40535. /**
  40536. * The transparency mode of the material.
  40537. */
  40538. _this._transparencyMode = null;
  40539. /**
  40540. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  40541. * from cos thetav and roughness:
  40542. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  40543. */
  40544. _this._environmentBRDFTexture = null;
  40545. /**
  40546. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  40547. */
  40548. _this._forceIrradianceInFragment = false;
  40549. /**
  40550. * Force normal to face away from face.
  40551. */
  40552. _this._forceNormalForward = false;
  40553. /**
  40554. * Force metallic workflow.
  40555. */
  40556. _this._forceMetallicWorkflow = false;
  40557. /**
  40558. * Stores the available render targets.
  40559. */
  40560. _this._renderTargets = new BABYLON.SmartArray(16);
  40561. /**
  40562. * Sets the global ambient color for the material used in lighting calculations.
  40563. */
  40564. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  40565. // Setup the default processing configuration to the scene.
  40566. _this._attachImageProcessingConfiguration(null);
  40567. _this.getRenderTargetTextures = function () {
  40568. _this._renderTargets.reset();
  40569. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  40570. _this._renderTargets.push(_this._reflectionTexture);
  40571. }
  40572. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  40573. _this._renderTargets.push(_this._refractionTexture);
  40574. }
  40575. return _this._renderTargets;
  40576. };
  40577. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  40578. return _this;
  40579. }
  40580. /**
  40581. * Attaches a new image processing configuration to the PBR Material.
  40582. * @param configuration
  40583. */
  40584. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  40585. var _this = this;
  40586. if (configuration === this._imageProcessingConfiguration) {
  40587. return;
  40588. }
  40589. // Detaches observer.
  40590. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  40591. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  40592. }
  40593. // Pick the scene configuration if needed.
  40594. if (!configuration) {
  40595. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  40596. }
  40597. else {
  40598. this._imageProcessingConfiguration = configuration;
  40599. }
  40600. // Attaches observer.
  40601. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  40602. _this._markAllSubMeshesAsImageProcessingDirty();
  40603. });
  40604. };
  40605. /**
  40606. * Gets the name of the material class.
  40607. */
  40608. PBRBaseMaterial.prototype.getClassName = function () {
  40609. return "PBRBaseMaterial";
  40610. };
  40611. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  40612. /**
  40613. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  40614. */
  40615. get: function () {
  40616. return this._useLogarithmicDepth;
  40617. },
  40618. /**
  40619. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  40620. */
  40621. set: function (value) {
  40622. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  40623. },
  40624. enumerable: true,
  40625. configurable: true
  40626. });
  40627. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  40628. /**
  40629. * Gets the current transparency mode.
  40630. */
  40631. get: function () {
  40632. return this._transparencyMode;
  40633. },
  40634. /**
  40635. * Sets the transparency mode of the material.
  40636. */
  40637. set: function (value) {
  40638. if (this._transparencyMode === value) {
  40639. return;
  40640. }
  40641. this._transparencyMode = value;
  40642. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  40643. this._markAllSubMeshesAsTexturesAndMiscDirty();
  40644. },
  40645. enumerable: true,
  40646. configurable: true
  40647. });
  40648. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  40649. /**
  40650. * Returns true if alpha blending should be disabled.
  40651. */
  40652. get: function () {
  40653. return (this._linkRefractionWithTransparency ||
  40654. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  40655. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  40656. },
  40657. enumerable: true,
  40658. configurable: true
  40659. });
  40660. /**
  40661. * Specifies whether or not this material should be rendered in alpha blend mode.
  40662. */
  40663. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  40664. if (this._disableAlphaBlending) {
  40665. return false;
  40666. }
  40667. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  40668. };
  40669. /**
  40670. * Specifies if the mesh will require alpha blending.
  40671. * @param mesh - BJS mesh.
  40672. */
  40673. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  40674. if (this._disableAlphaBlending) {
  40675. return false;
  40676. }
  40677. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  40678. };
  40679. /**
  40680. * Specifies whether or not this material should be rendered in alpha test mode.
  40681. */
  40682. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  40683. if (this._forceAlphaTest) {
  40684. return true;
  40685. }
  40686. if (this._linkRefractionWithTransparency) {
  40687. return false;
  40688. }
  40689. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  40690. };
  40691. /**
  40692. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  40693. */
  40694. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  40695. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  40696. };
  40697. /**
  40698. * Gets the texture used for the alpha test.
  40699. */
  40700. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  40701. return this._albedoTexture;
  40702. };
  40703. /**
  40704. * Specifies that the submesh is ready to be used.
  40705. * @param mesh - BJS mesh.
  40706. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  40707. * @param useInstances - Specifies that instances should be used.
  40708. * @returns - boolean indicating that the submesh is ready or not.
  40709. */
  40710. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  40711. if (subMesh.effect && this.isFrozen) {
  40712. if (this._wasPreviouslyReady) {
  40713. return true;
  40714. }
  40715. }
  40716. if (!subMesh._materialDefines) {
  40717. subMesh._materialDefines = new PBRMaterialDefines();
  40718. }
  40719. var defines = subMesh._materialDefines;
  40720. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  40721. if (defines._renderId === this.getScene().getRenderId()) {
  40722. return true;
  40723. }
  40724. }
  40725. var scene = this.getScene();
  40726. var engine = scene.getEngine();
  40727. if (defines._areTexturesDirty) {
  40728. if (scene.texturesEnabled) {
  40729. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  40730. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  40731. return false;
  40732. }
  40733. }
  40734. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  40735. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  40736. return false;
  40737. }
  40738. }
  40739. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  40740. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  40741. return false;
  40742. }
  40743. }
  40744. var reflectionTexture = this._getReflectionTexture();
  40745. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  40746. if (!reflectionTexture.isReadyOrNotBlocking()) {
  40747. return false;
  40748. }
  40749. }
  40750. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  40751. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  40752. return false;
  40753. }
  40754. }
  40755. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  40756. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  40757. return false;
  40758. }
  40759. }
  40760. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  40761. if (this._metallicTexture) {
  40762. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  40763. return false;
  40764. }
  40765. }
  40766. else if (this._reflectivityTexture) {
  40767. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  40768. return false;
  40769. }
  40770. }
  40771. if (this._microSurfaceTexture) {
  40772. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  40773. return false;
  40774. }
  40775. }
  40776. }
  40777. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  40778. // Bump texture cannot be not blocking.
  40779. if (!this._bumpTexture.isReady()) {
  40780. return false;
  40781. }
  40782. }
  40783. var refractionTexture = this._getRefractionTexture();
  40784. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  40785. if (!refractionTexture.isReadyOrNotBlocking()) {
  40786. return false;
  40787. }
  40788. }
  40789. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  40790. // This is blocking.
  40791. if (!this._environmentBRDFTexture.isReady()) {
  40792. return false;
  40793. }
  40794. }
  40795. }
  40796. }
  40797. if (defines._areImageProcessingDirty) {
  40798. if (!this._imageProcessingConfiguration.isReady()) {
  40799. return false;
  40800. }
  40801. }
  40802. if (!engine.getCaps().standardDerivatives) {
  40803. var bufferMesh = null;
  40804. if (mesh.getClassName() === "InstancedMesh") {
  40805. bufferMesh = mesh.sourceMesh;
  40806. }
  40807. else if (mesh.getClassName() === "Mesh") {
  40808. bufferMesh = mesh;
  40809. }
  40810. if (bufferMesh && bufferMesh.geometry && bufferMesh.geometry.isReady() && !bufferMesh.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  40811. bufferMesh.createNormals(true);
  40812. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + bufferMesh.name);
  40813. }
  40814. }
  40815. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  40816. if (effect) {
  40817. scene.resetCachedMaterial();
  40818. subMesh.setEffect(effect, defines);
  40819. this.buildUniformLayout();
  40820. }
  40821. if (!subMesh.effect || !subMesh.effect.isReady()) {
  40822. return false;
  40823. }
  40824. defines._renderId = scene.getRenderId();
  40825. this._wasPreviouslyReady = true;
  40826. return true;
  40827. };
  40828. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  40829. if (onCompiled === void 0) { onCompiled = null; }
  40830. if (onError === void 0) { onError = null; }
  40831. if (useInstances === void 0) { useInstances = null; }
  40832. if (useClipPlane === void 0) { useClipPlane = null; }
  40833. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  40834. if (!defines.isDirty) {
  40835. return null;
  40836. }
  40837. defines.markAsProcessed();
  40838. var scene = this.getScene();
  40839. var engine = scene.getEngine();
  40840. // Fallbacks
  40841. var fallbacks = new BABYLON.EffectFallbacks();
  40842. var fallbackRank = 0;
  40843. if (defines.USESPHERICALINVERTEX) {
  40844. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  40845. }
  40846. if (defines.FOG) {
  40847. fallbacks.addFallback(fallbackRank, "FOG");
  40848. }
  40849. if (defines.POINTSIZE) {
  40850. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  40851. }
  40852. if (defines.LOGARITHMICDEPTH) {
  40853. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  40854. }
  40855. if (defines.PARALLAX) {
  40856. fallbacks.addFallback(fallbackRank, "PARALLAX");
  40857. }
  40858. if (defines.PARALLAXOCCLUSION) {
  40859. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  40860. }
  40861. if (defines.ENVIRONMENTBRDF) {
  40862. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  40863. }
  40864. if (defines.TANGENT) {
  40865. fallbacks.addFallback(fallbackRank++, "TANGENT");
  40866. }
  40867. if (defines.BUMP) {
  40868. fallbacks.addFallback(fallbackRank++, "BUMP");
  40869. }
  40870. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  40871. if (defines.SPECULARTERM) {
  40872. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  40873. }
  40874. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  40875. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  40876. }
  40877. if (defines.LIGHTMAP) {
  40878. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  40879. }
  40880. if (defines.NORMAL) {
  40881. fallbacks.addFallback(fallbackRank++, "NORMAL");
  40882. }
  40883. if (defines.AMBIENT) {
  40884. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  40885. }
  40886. if (defines.EMISSIVE) {
  40887. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  40888. }
  40889. if (defines.VERTEXCOLOR) {
  40890. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  40891. }
  40892. if (defines.NUM_BONE_INFLUENCERS > 0) {
  40893. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  40894. }
  40895. if (defines.MORPHTARGETS) {
  40896. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  40897. }
  40898. //Attributes
  40899. var attribs = [BABYLON.VertexBuffer.PositionKind];
  40900. if (defines.NORMAL) {
  40901. attribs.push(BABYLON.VertexBuffer.NormalKind);
  40902. }
  40903. if (defines.TANGENT) {
  40904. attribs.push(BABYLON.VertexBuffer.TangentKind);
  40905. }
  40906. if (defines.UV1) {
  40907. attribs.push(BABYLON.VertexBuffer.UVKind);
  40908. }
  40909. if (defines.UV2) {
  40910. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  40911. }
  40912. if (defines.VERTEXCOLOR) {
  40913. attribs.push(BABYLON.VertexBuffer.ColorKind);
  40914. }
  40915. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  40916. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  40917. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  40918. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  40919. "vFogInfos", "vFogColor", "pointSize",
  40920. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  40921. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  40922. "mBones",
  40923. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  40924. "vLightingIntensity",
  40925. "logarithmicDepthConstant",
  40926. "vSphericalX", "vSphericalY", "vSphericalZ",
  40927. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  40928. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  40929. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  40930. "vTangentSpaceParams"
  40931. ];
  40932. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  40933. "bumpSampler", "lightmapSampler", "opacitySampler",
  40934. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  40935. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  40936. "microSurfaceSampler", "environmentBrdfSampler"];
  40937. var uniformBuffers = ["Material", "Scene"];
  40938. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  40939. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  40940. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  40941. uniformsNames: uniforms,
  40942. uniformBuffersNames: uniformBuffers,
  40943. samplers: samplers,
  40944. defines: defines,
  40945. maxSimultaneousLights: this._maxSimultaneousLights
  40946. });
  40947. var join = defines.toString();
  40948. return engine.createEffect("pbr", {
  40949. attributes: attribs,
  40950. uniformsNames: uniforms,
  40951. uniformBuffersNames: uniformBuffers,
  40952. samplers: samplers,
  40953. defines: join,
  40954. fallbacks: fallbacks,
  40955. onCompiled: onCompiled,
  40956. onError: onError,
  40957. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  40958. }, engine);
  40959. };
  40960. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  40961. if (useInstances === void 0) { useInstances = null; }
  40962. if (useClipPlane === void 0) { useClipPlane = null; }
  40963. var scene = this.getScene();
  40964. var engine = scene.getEngine();
  40965. // Lights
  40966. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  40967. defines._needNormals = true;
  40968. // Textures
  40969. if (defines._areTexturesDirty) {
  40970. defines._needUVs = false;
  40971. if (scene.texturesEnabled) {
  40972. if (scene.getEngine().getCaps().textureLOD) {
  40973. defines.LODBASEDMICROSFURACE = true;
  40974. }
  40975. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  40976. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  40977. }
  40978. else {
  40979. defines.ALBEDO = false;
  40980. }
  40981. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  40982. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  40983. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  40984. }
  40985. else {
  40986. defines.AMBIENT = false;
  40987. }
  40988. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  40989. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  40990. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  40991. }
  40992. else {
  40993. defines.OPACITY = false;
  40994. }
  40995. var reflectionTexture = this._getReflectionTexture();
  40996. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  40997. defines.REFLECTION = true;
  40998. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  40999. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  41000. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  41001. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  41002. defines.INVERTCUBICMAP = true;
  41003. }
  41004. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  41005. switch (reflectionTexture.coordinatesMode) {
  41006. case BABYLON.Texture.CUBIC_MODE:
  41007. case BABYLON.Texture.INVCUBIC_MODE:
  41008. defines.REFLECTIONMAP_CUBIC = true;
  41009. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  41010. break;
  41011. case BABYLON.Texture.EXPLICIT_MODE:
  41012. defines.REFLECTIONMAP_EXPLICIT = true;
  41013. break;
  41014. case BABYLON.Texture.PLANAR_MODE:
  41015. defines.REFLECTIONMAP_PLANAR = true;
  41016. break;
  41017. case BABYLON.Texture.PROJECTION_MODE:
  41018. defines.REFLECTIONMAP_PROJECTION = true;
  41019. break;
  41020. case BABYLON.Texture.SKYBOX_MODE:
  41021. defines.REFLECTIONMAP_SKYBOX = true;
  41022. break;
  41023. case BABYLON.Texture.SPHERICAL_MODE:
  41024. defines.REFLECTIONMAP_SPHERICAL = true;
  41025. break;
  41026. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  41027. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  41028. break;
  41029. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  41030. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  41031. break;
  41032. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  41033. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  41034. break;
  41035. }
  41036. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  41037. if (reflectionTexture.sphericalPolynomial) {
  41038. defines.USESPHERICALFROMREFLECTIONMAP = true;
  41039. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  41040. defines.USESPHERICALINVERTEX = false;
  41041. }
  41042. else {
  41043. defines.USESPHERICALINVERTEX = true;
  41044. }
  41045. }
  41046. }
  41047. }
  41048. else {
  41049. defines.REFLECTION = false;
  41050. defines.REFLECTIONMAP_3D = false;
  41051. defines.REFLECTIONMAP_SPHERICAL = false;
  41052. defines.REFLECTIONMAP_PLANAR = false;
  41053. defines.REFLECTIONMAP_CUBIC = false;
  41054. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  41055. defines.REFLECTIONMAP_PROJECTION = false;
  41056. defines.REFLECTIONMAP_SKYBOX = false;
  41057. defines.REFLECTIONMAP_EXPLICIT = false;
  41058. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  41059. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  41060. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  41061. defines.INVERTCUBICMAP = false;
  41062. defines.USESPHERICALFROMREFLECTIONMAP = false;
  41063. defines.USESPHERICALINVERTEX = false;
  41064. defines.REFLECTIONMAP_OPPOSITEZ = false;
  41065. defines.LODINREFLECTIONALPHA = false;
  41066. defines.GAMMAREFLECTION = false;
  41067. }
  41068. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  41069. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  41070. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  41071. }
  41072. else {
  41073. defines.LIGHTMAP = false;
  41074. }
  41075. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  41076. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  41077. }
  41078. else {
  41079. defines.EMISSIVE = false;
  41080. }
  41081. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  41082. if (this._metallicTexture) {
  41083. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  41084. defines.METALLICWORKFLOW = true;
  41085. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  41086. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  41087. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  41088. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  41089. }
  41090. else if (this._reflectivityTexture) {
  41091. defines.METALLICWORKFLOW = false;
  41092. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  41093. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  41094. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  41095. }
  41096. else {
  41097. defines.METALLICWORKFLOW = false;
  41098. defines.REFLECTIVITY = false;
  41099. }
  41100. if (this._microSurfaceTexture) {
  41101. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  41102. }
  41103. else {
  41104. defines.MICROSURFACEMAP = false;
  41105. }
  41106. }
  41107. else {
  41108. defines.REFLECTIVITY = false;
  41109. defines.MICROSURFACEMAP = false;
  41110. }
  41111. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  41112. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  41113. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41114. defines.PARALLAX = true;
  41115. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  41116. }
  41117. else {
  41118. defines.PARALLAX = false;
  41119. }
  41120. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  41121. }
  41122. else {
  41123. defines.BUMP = false;
  41124. }
  41125. var refractionTexture = this._getRefractionTexture();
  41126. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  41127. defines.REFRACTION = true;
  41128. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  41129. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  41130. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  41131. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  41132. if (this._linkRefractionWithTransparency) {
  41133. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  41134. }
  41135. }
  41136. else {
  41137. defines.REFRACTION = false;
  41138. }
  41139. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41140. defines.ENVIRONMENTBRDF = true;
  41141. }
  41142. else {
  41143. defines.ENVIRONMENTBRDF = false;
  41144. }
  41145. if (this._shouldUseAlphaFromAlbedoTexture()) {
  41146. defines.ALPHAFROMALBEDO = true;
  41147. }
  41148. else {
  41149. defines.ALPHAFROMALBEDO = false;
  41150. }
  41151. }
  41152. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  41153. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  41154. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  41155. if (this._forceMetallicWorkflow || (this._metallic !== undefined && this._metallic !== null) || (this._roughness !== undefined && this._roughness !== null)) {
  41156. defines.METALLICWORKFLOW = true;
  41157. }
  41158. else {
  41159. defines.METALLICWORKFLOW = false;
  41160. }
  41161. if (!this.backFaceCulling && this._twoSidedLighting) {
  41162. defines.TWOSIDEDLIGHTING = true;
  41163. }
  41164. else {
  41165. defines.TWOSIDEDLIGHTING = false;
  41166. }
  41167. defines.ALPHATESTVALUE = this._alphaCutOff;
  41168. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  41169. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  41170. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  41171. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  41172. }
  41173. if (defines._areImageProcessingDirty) {
  41174. this._imageProcessingConfiguration.prepareDefines(defines);
  41175. }
  41176. defines.FORCENORMALFORWARD = this._forceNormalForward;
  41177. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  41178. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  41179. // Misc.
  41180. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  41181. // Values that need to be evaluated on every frame
  41182. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  41183. // Attribs
  41184. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  41185. };
  41186. /**
  41187. * Force shader compilation
  41188. */
  41189. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  41190. var _this = this;
  41191. var localOptions = __assign({ clipPlane: false }, options);
  41192. var defines = new PBRMaterialDefines();
  41193. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  41194. if (effect.isReady()) {
  41195. if (onCompiled) {
  41196. onCompiled(this);
  41197. }
  41198. }
  41199. else {
  41200. effect.onCompileObservable.add(function () {
  41201. if (onCompiled) {
  41202. onCompiled(_this);
  41203. }
  41204. });
  41205. }
  41206. };
  41207. /**
  41208. * Initializes the uniform buffer layout for the shader.
  41209. */
  41210. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  41211. // Order is important !
  41212. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  41213. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  41214. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  41215. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  41216. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  41217. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  41218. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  41219. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  41220. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  41221. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  41222. this._uniformBuffer.addUniform("vReflectionSize", 3);
  41223. this._uniformBuffer.addUniform("vBumpInfos", 3);
  41224. this._uniformBuffer.addUniform("albedoMatrix", 16);
  41225. this._uniformBuffer.addUniform("ambientMatrix", 16);
  41226. this._uniformBuffer.addUniform("opacityMatrix", 16);
  41227. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  41228. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  41229. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  41230. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  41231. this._uniformBuffer.addUniform("bumpMatrix", 16);
  41232. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  41233. this._uniformBuffer.addUniform("refractionMatrix", 16);
  41234. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  41235. this._uniformBuffer.addUniform("vReflectionColor", 3);
  41236. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  41237. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  41238. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  41239. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  41240. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  41241. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  41242. this._uniformBuffer.addUniform("pointSize", 1);
  41243. this._uniformBuffer.create();
  41244. };
  41245. /**
  41246. * Unbinds the textures.
  41247. */
  41248. PBRBaseMaterial.prototype.unbind = function () {
  41249. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  41250. this._uniformBuffer.setTexture("reflectionSampler", null);
  41251. }
  41252. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  41253. this._uniformBuffer.setTexture("refractionSampler", null);
  41254. }
  41255. _super.prototype.unbind.call(this);
  41256. };
  41257. /**
  41258. * Binds the submesh data.
  41259. * @param world - The world matrix.
  41260. * @param mesh - The BJS mesh.
  41261. * @param subMesh - A submesh of the BJS mesh.
  41262. */
  41263. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  41264. var scene = this.getScene();
  41265. var defines = subMesh._materialDefines;
  41266. if (!defines) {
  41267. return;
  41268. }
  41269. var effect = subMesh.effect;
  41270. if (!effect) {
  41271. return;
  41272. }
  41273. this._activeEffect = effect;
  41274. // Matrices
  41275. this.bindOnlyWorldMatrix(world);
  41276. // Normal Matrix
  41277. if (defines.OBJECTSPACE_NORMALMAP) {
  41278. world.toNormalMatrix(this._normalMatrix);
  41279. this.bindOnlyNormalMatrix(this._normalMatrix);
  41280. }
  41281. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  41282. // Bones
  41283. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  41284. var reflectionTexture = null;
  41285. if (mustRebind) {
  41286. this._uniformBuffer.bindToEffect(effect, "Material");
  41287. this.bindViewProjection(effect);
  41288. reflectionTexture = this._getReflectionTexture();
  41289. var refractionTexture = this._getRefractionTexture();
  41290. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  41291. // Texture uniforms
  41292. if (scene.texturesEnabled) {
  41293. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41294. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  41295. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  41296. }
  41297. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  41298. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  41299. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  41300. }
  41301. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  41302. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  41303. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  41304. }
  41305. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41306. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  41307. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  41308. if (reflectionTexture.boundingBoxSize) {
  41309. var cubeTexture = reflectionTexture;
  41310. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  41311. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  41312. }
  41313. var polynomials = reflectionTexture.sphericalPolynomial;
  41314. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  41315. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  41316. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  41317. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  41318. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  41319. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  41320. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  41321. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  41322. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  41323. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  41324. }
  41325. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  41326. }
  41327. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  41328. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  41329. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  41330. }
  41331. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  41332. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  41333. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  41334. }
  41335. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  41336. if (this._metallicTexture) {
  41337. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  41338. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  41339. }
  41340. else if (this._reflectivityTexture) {
  41341. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  41342. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  41343. }
  41344. if (this._microSurfaceTexture) {
  41345. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  41346. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  41347. }
  41348. }
  41349. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  41350. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  41351. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  41352. if (scene._mirroredCameraPosition) {
  41353. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  41354. }
  41355. else {
  41356. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  41357. }
  41358. }
  41359. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  41360. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  41361. var depth = 1.0;
  41362. if (!refractionTexture.isCube) {
  41363. if (refractionTexture.depth) {
  41364. depth = refractionTexture.depth;
  41365. }
  41366. }
  41367. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  41368. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  41369. }
  41370. }
  41371. // Point size
  41372. if (this.pointsCloud) {
  41373. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  41374. }
  41375. // Colors
  41376. if (defines.METALLICWORKFLOW) {
  41377. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  41378. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  41379. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  41380. }
  41381. else {
  41382. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  41383. }
  41384. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  41385. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  41386. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  41387. // Misc
  41388. this._lightingInfos.x = this._directIntensity;
  41389. this._lightingInfos.y = this._emissiveIntensity;
  41390. this._lightingInfos.z = this._environmentIntensity;
  41391. this._lightingInfos.w = this._specularIntensity;
  41392. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  41393. }
  41394. // Textures
  41395. if (scene.texturesEnabled) {
  41396. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41397. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  41398. }
  41399. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  41400. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  41401. }
  41402. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  41403. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  41404. }
  41405. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41406. if (defines.LODBASEDMICROSFURACE) {
  41407. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  41408. }
  41409. else {
  41410. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  41411. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  41412. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  41413. }
  41414. }
  41415. if (defines.ENVIRONMENTBRDF) {
  41416. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  41417. }
  41418. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  41419. if (defines.LODBASEDMICROSFURACE) {
  41420. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  41421. }
  41422. else {
  41423. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  41424. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  41425. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  41426. }
  41427. }
  41428. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  41429. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  41430. }
  41431. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  41432. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  41433. }
  41434. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  41435. if (this._metallicTexture) {
  41436. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  41437. }
  41438. else if (this._reflectivityTexture) {
  41439. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  41440. }
  41441. if (this._microSurfaceTexture) {
  41442. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  41443. }
  41444. }
  41445. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  41446. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  41447. }
  41448. }
  41449. // Clip plane
  41450. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  41451. // Colors
  41452. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  41453. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  41454. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  41455. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  41456. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  41457. }
  41458. if (mustRebind || !this.isFrozen) {
  41459. // Lights
  41460. if (scene.lightsEnabled && !this._disableLighting) {
  41461. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  41462. }
  41463. // View
  41464. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  41465. this.bindView(effect);
  41466. }
  41467. // Fog
  41468. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  41469. // Morph targets
  41470. if (defines.NUM_MORPH_INFLUENCERS) {
  41471. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  41472. }
  41473. // image processing
  41474. this._imageProcessingConfiguration.bind(this._activeEffect);
  41475. // Log. depth
  41476. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  41477. }
  41478. this._uniformBuffer.update();
  41479. this._afterBind(mesh);
  41480. };
  41481. /**
  41482. * Returns the animatable textures.
  41483. * @returns - Array of animatable textures.
  41484. */
  41485. PBRBaseMaterial.prototype.getAnimatables = function () {
  41486. var results = [];
  41487. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  41488. results.push(this._albedoTexture);
  41489. }
  41490. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  41491. results.push(this._ambientTexture);
  41492. }
  41493. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  41494. results.push(this._opacityTexture);
  41495. }
  41496. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  41497. results.push(this._reflectionTexture);
  41498. }
  41499. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  41500. results.push(this._emissiveTexture);
  41501. }
  41502. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  41503. results.push(this._metallicTexture);
  41504. }
  41505. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  41506. results.push(this._reflectivityTexture);
  41507. }
  41508. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  41509. results.push(this._bumpTexture);
  41510. }
  41511. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  41512. results.push(this._lightmapTexture);
  41513. }
  41514. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  41515. results.push(this._refractionTexture);
  41516. }
  41517. return results;
  41518. };
  41519. /**
  41520. * Returns the texture used for reflections.
  41521. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  41522. */
  41523. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  41524. if (this._reflectionTexture) {
  41525. return this._reflectionTexture;
  41526. }
  41527. return this.getScene().environmentTexture;
  41528. };
  41529. /**
  41530. * Returns the texture used for refraction or null if none is used.
  41531. * @returns - Refection texture if present. If no refraction texture and refraction
  41532. * is linked with transparency, returns environment texture. Otherwise, returns null.
  41533. */
  41534. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  41535. if (this._refractionTexture) {
  41536. return this._refractionTexture;
  41537. }
  41538. if (this._linkRefractionWithTransparency) {
  41539. return this.getScene().environmentTexture;
  41540. }
  41541. return null;
  41542. };
  41543. /**
  41544. * Disposes the resources of the material.
  41545. * @param forceDisposeEffect - Forces the disposal of effects.
  41546. * @param forceDisposeTextures - Forces the disposal of all textures.
  41547. */
  41548. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  41549. if (forceDisposeTextures) {
  41550. if (this._albedoTexture) {
  41551. this._albedoTexture.dispose();
  41552. }
  41553. if (this._ambientTexture) {
  41554. this._ambientTexture.dispose();
  41555. }
  41556. if (this._opacityTexture) {
  41557. this._opacityTexture.dispose();
  41558. }
  41559. if (this._reflectionTexture) {
  41560. this._reflectionTexture.dispose();
  41561. }
  41562. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  41563. this._environmentBRDFTexture.dispose();
  41564. }
  41565. if (this._emissiveTexture) {
  41566. this._emissiveTexture.dispose();
  41567. }
  41568. if (this._metallicTexture) {
  41569. this._metallicTexture.dispose();
  41570. }
  41571. if (this._reflectivityTexture) {
  41572. this._reflectivityTexture.dispose();
  41573. }
  41574. if (this._bumpTexture) {
  41575. this._bumpTexture.dispose();
  41576. }
  41577. if (this._lightmapTexture) {
  41578. this._lightmapTexture.dispose();
  41579. }
  41580. if (this._refractionTexture) {
  41581. this._refractionTexture.dispose();
  41582. }
  41583. }
  41584. this._renderTargets.dispose();
  41585. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  41586. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  41587. }
  41588. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  41589. };
  41590. /**
  41591. * Stores the reflectivity values based on metallic roughness workflow.
  41592. */
  41593. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  41594. __decorate([
  41595. BABYLON.serializeAsImageProcessingConfiguration()
  41596. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  41597. __decorate([
  41598. BABYLON.serialize()
  41599. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  41600. __decorate([
  41601. BABYLON.serialize()
  41602. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  41603. return PBRBaseMaterial;
  41604. }(BABYLON.PushMaterial));
  41605. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  41606. })(BABYLON || (BABYLON = {}));
  41607. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  41608. var BABYLON;
  41609. (function (BABYLON) {
  41610. /**
  41611. * The Physically based simple base material of BJS.
  41612. *
  41613. * This enables better naming and convention enforcements on top of the pbrMaterial.
  41614. * It is used as the base class for both the specGloss and metalRough conventions.
  41615. */
  41616. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  41617. __extends(PBRBaseSimpleMaterial, _super);
  41618. /**
  41619. * Instantiates a new PBRMaterial instance.
  41620. *
  41621. * @param name The material name
  41622. * @param scene The scene the material will be use in.
  41623. */
  41624. function PBRBaseSimpleMaterial(name, scene) {
  41625. var _this = _super.call(this, name, scene) || this;
  41626. /**
  41627. * Number of Simultaneous lights allowed on the material.
  41628. */
  41629. _this.maxSimultaneousLights = 4;
  41630. /**
  41631. * If sets to true, disables all the lights affecting the material.
  41632. */
  41633. _this.disableLighting = false;
  41634. /**
  41635. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  41636. */
  41637. _this.invertNormalMapX = false;
  41638. /**
  41639. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  41640. */
  41641. _this.invertNormalMapY = false;
  41642. /**
  41643. * Emissivie color used to self-illuminate the model.
  41644. */
  41645. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  41646. /**
  41647. * Occlusion Channel Strenght.
  41648. */
  41649. _this.occlusionStrength = 1.0;
  41650. _this.useLightmapAsShadowmap = false;
  41651. _this._useAlphaFromAlbedoTexture = true;
  41652. _this._useAmbientInGrayScale = true;
  41653. return _this;
  41654. }
  41655. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  41656. /**
  41657. * Gets the current double sided mode.
  41658. */
  41659. get: function () {
  41660. return this._twoSidedLighting;
  41661. },
  41662. /**
  41663. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  41664. */
  41665. set: function (value) {
  41666. if (this._twoSidedLighting === value) {
  41667. return;
  41668. }
  41669. this._twoSidedLighting = value;
  41670. this.backFaceCulling = !value;
  41671. this._markAllSubMeshesAsTexturesDirty();
  41672. },
  41673. enumerable: true,
  41674. configurable: true
  41675. });
  41676. /**
  41677. * Return the active textures of the material.
  41678. */
  41679. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  41680. var activeTextures = _super.prototype.getActiveTextures.call(this);
  41681. if (this.environmentTexture) {
  41682. activeTextures.push(this.environmentTexture);
  41683. }
  41684. if (this.normalTexture) {
  41685. activeTextures.push(this.normalTexture);
  41686. }
  41687. if (this.emissiveTexture) {
  41688. activeTextures.push(this.emissiveTexture);
  41689. }
  41690. if (this.occlusionTexture) {
  41691. activeTextures.push(this.occlusionTexture);
  41692. }
  41693. if (this.lightmapTexture) {
  41694. activeTextures.push(this.lightmapTexture);
  41695. }
  41696. return activeTextures;
  41697. };
  41698. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  41699. if (_super.prototype.hasTexture.call(this, texture)) {
  41700. return true;
  41701. }
  41702. if (this.lightmapTexture === texture) {
  41703. return true;
  41704. }
  41705. return false;
  41706. };
  41707. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  41708. return "PBRBaseSimpleMaterial";
  41709. };
  41710. __decorate([
  41711. BABYLON.serialize(),
  41712. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  41713. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  41714. __decorate([
  41715. BABYLON.serialize(),
  41716. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  41717. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  41718. __decorate([
  41719. BABYLON.serializeAsTexture(),
  41720. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  41721. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  41722. __decorate([
  41723. BABYLON.serialize(),
  41724. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41725. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  41726. __decorate([
  41727. BABYLON.serialize(),
  41728. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41729. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  41730. __decorate([
  41731. BABYLON.serializeAsTexture(),
  41732. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  41733. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  41734. __decorate([
  41735. BABYLON.serializeAsColor3("emissive"),
  41736. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41737. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  41738. __decorate([
  41739. BABYLON.serializeAsTexture(),
  41740. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41741. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  41742. __decorate([
  41743. BABYLON.serialize(),
  41744. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  41745. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  41746. __decorate([
  41747. BABYLON.serializeAsTexture(),
  41748. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  41749. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  41750. __decorate([
  41751. BABYLON.serialize(),
  41752. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  41753. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  41754. __decorate([
  41755. BABYLON.serialize()
  41756. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  41757. __decorate([
  41758. BABYLON.serializeAsTexture(),
  41759. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  41760. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  41761. __decorate([
  41762. BABYLON.serialize(),
  41763. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41764. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  41765. return PBRBaseSimpleMaterial;
  41766. }(BABYLON.PBRBaseMaterial));
  41767. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  41768. })(BABYLON || (BABYLON = {}));
  41769. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  41770. var BABYLON;
  41771. (function (BABYLON) {
  41772. /**
  41773. * The Physically based material of BJS.
  41774. *
  41775. * This offers the main features of a standard PBR material.
  41776. * For more information, please refer to the documentation :
  41777. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  41778. */
  41779. var PBRMaterial = /** @class */ (function (_super) {
  41780. __extends(PBRMaterial, _super);
  41781. /**
  41782. * Instantiates a new PBRMaterial instance.
  41783. *
  41784. * @param name The material name
  41785. * @param scene The scene the material will be use in.
  41786. */
  41787. function PBRMaterial(name, scene) {
  41788. var _this = _super.call(this, name, scene) || this;
  41789. /**
  41790. * Intensity of the direct lights e.g. the four lights available in your scene.
  41791. * This impacts both the direct diffuse and specular highlights.
  41792. */
  41793. _this.directIntensity = 1.0;
  41794. /**
  41795. * Intensity of the emissive part of the material.
  41796. * This helps controlling the emissive effect without modifying the emissive color.
  41797. */
  41798. _this.emissiveIntensity = 1.0;
  41799. /**
  41800. * Intensity of the environment e.g. how much the environment will light the object
  41801. * either through harmonics for rough material or through the refelction for shiny ones.
  41802. */
  41803. _this.environmentIntensity = 1.0;
  41804. /**
  41805. * This is a special control allowing the reduction of the specular highlights coming from the
  41806. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  41807. */
  41808. _this.specularIntensity = 1.0;
  41809. /**
  41810. * Debug Control allowing disabling the bump map on this material.
  41811. */
  41812. _this.disableBumpMap = false;
  41813. /**
  41814. * AKA Occlusion Texture Intensity in other nomenclature.
  41815. */
  41816. _this.ambientTextureStrength = 1.0;
  41817. /**
  41818. * The color of a material in ambient lighting.
  41819. */
  41820. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  41821. /**
  41822. * AKA Diffuse Color in other nomenclature.
  41823. */
  41824. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  41825. /**
  41826. * AKA Specular Color in other nomenclature.
  41827. */
  41828. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  41829. /**
  41830. * The color reflected from the material.
  41831. */
  41832. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  41833. /**
  41834. * The color emitted from the material.
  41835. */
  41836. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  41837. /**
  41838. * AKA Glossiness in other nomenclature.
  41839. */
  41840. _this.microSurface = 1.0;
  41841. /**
  41842. * source material index of refraction (IOR)' / 'destination material IOR.
  41843. */
  41844. _this.indexOfRefraction = 0.66;
  41845. /**
  41846. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  41847. */
  41848. _this.invertRefractionY = false;
  41849. /**
  41850. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  41851. * Materials half opaque for instance using refraction could benefit from this control.
  41852. */
  41853. _this.linkRefractionWithTransparency = false;
  41854. _this.useLightmapAsShadowmap = false;
  41855. /**
  41856. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  41857. */
  41858. _this.useAlphaFromAlbedoTexture = false;
  41859. /**
  41860. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  41861. */
  41862. _this.forceAlphaTest = false;
  41863. /**
  41864. * Defines the alpha limits in alpha test mode.
  41865. */
  41866. _this.alphaCutOff = 0.4;
  41867. /**
  41868. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  41869. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  41870. */
  41871. _this.useSpecularOverAlpha = true;
  41872. /**
  41873. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  41874. */
  41875. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  41876. /**
  41877. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  41878. */
  41879. _this.useRoughnessFromMetallicTextureAlpha = true;
  41880. /**
  41881. * Specifies if the metallic texture contains the roughness information in its green channel.
  41882. */
  41883. _this.useRoughnessFromMetallicTextureGreen = false;
  41884. /**
  41885. * Specifies if the metallic texture contains the metallness information in its blue channel.
  41886. */
  41887. _this.useMetallnessFromMetallicTextureBlue = false;
  41888. /**
  41889. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  41890. */
  41891. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  41892. /**
  41893. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  41894. */
  41895. _this.useAmbientInGrayScale = false;
  41896. /**
  41897. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  41898. * The material will try to infer what glossiness each pixel should be.
  41899. */
  41900. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  41901. /**
  41902. * BJS is using an harcoded light falloff based on a manually sets up range.
  41903. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  41904. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  41905. */
  41906. _this.usePhysicalLightFalloff = true;
  41907. /**
  41908. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  41909. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  41910. */
  41911. _this.useRadianceOverAlpha = true;
  41912. /**
  41913. * Allows using an object space normal map (instead of tangent space).
  41914. */
  41915. _this.useObjectSpaceNormalMap = false;
  41916. /**
  41917. * Allows using the bump map in parallax mode.
  41918. */
  41919. _this.useParallax = false;
  41920. /**
  41921. * Allows using the bump map in parallax occlusion mode.
  41922. */
  41923. _this.useParallaxOcclusion = false;
  41924. /**
  41925. * Controls the scale bias of the parallax mode.
  41926. */
  41927. _this.parallaxScaleBias = 0.05;
  41928. /**
  41929. * If sets to true, disables all the lights affecting the material.
  41930. */
  41931. _this.disableLighting = false;
  41932. /**
  41933. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  41934. */
  41935. _this.forceIrradianceInFragment = false;
  41936. /**
  41937. * Number of Simultaneous lights allowed on the material.
  41938. */
  41939. _this.maxSimultaneousLights = 4;
  41940. /**
  41941. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  41942. */
  41943. _this.invertNormalMapX = false;
  41944. /**
  41945. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  41946. */
  41947. _this.invertNormalMapY = false;
  41948. /**
  41949. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  41950. */
  41951. _this.twoSidedLighting = false;
  41952. /**
  41953. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  41954. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  41955. */
  41956. _this.useAlphaFresnel = false;
  41957. /**
  41958. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  41959. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  41960. */
  41961. _this.useLinearAlphaFresnel = false;
  41962. /**
  41963. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  41964. * And/Or occlude the blended part.
  41965. */
  41966. _this.environmentBRDFTexture = null;
  41967. /**
  41968. * Force normal to face away from face.
  41969. */
  41970. _this.forceNormalForward = false;
  41971. /**
  41972. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  41973. * makes the reflect vector face the model (under horizon).
  41974. */
  41975. _this.useHorizonOcclusion = true;
  41976. /**
  41977. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  41978. * too much the area relying on ambient texture to define their ambient occlusion.
  41979. */
  41980. _this.useRadianceOcclusion = true;
  41981. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  41982. return _this;
  41983. }
  41984. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  41985. /**
  41986. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  41987. */
  41988. get: function () {
  41989. return this._PBRMATERIAL_OPAQUE;
  41990. },
  41991. enumerable: true,
  41992. configurable: true
  41993. });
  41994. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  41995. /**
  41996. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  41997. */
  41998. get: function () {
  41999. return this._PBRMATERIAL_ALPHATEST;
  42000. },
  42001. enumerable: true,
  42002. configurable: true
  42003. });
  42004. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  42005. /**
  42006. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  42007. */
  42008. get: function () {
  42009. return this._PBRMATERIAL_ALPHABLEND;
  42010. },
  42011. enumerable: true,
  42012. configurable: true
  42013. });
  42014. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  42015. /**
  42016. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  42017. * They are also discarded below the alpha cutoff threshold to improve performances.
  42018. */
  42019. get: function () {
  42020. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  42021. },
  42022. enumerable: true,
  42023. configurable: true
  42024. });
  42025. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  42026. /**
  42027. * Gets the image processing configuration used either in this material.
  42028. */
  42029. get: function () {
  42030. return this._imageProcessingConfiguration;
  42031. },
  42032. /**
  42033. * Sets the Default image processing configuration used either in the this material.
  42034. *
  42035. * If sets to null, the scene one is in use.
  42036. */
  42037. set: function (value) {
  42038. this._attachImageProcessingConfiguration(value);
  42039. // Ensure the effect will be rebuilt.
  42040. this._markAllSubMeshesAsTexturesDirty();
  42041. },
  42042. enumerable: true,
  42043. configurable: true
  42044. });
  42045. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  42046. /**
  42047. * Gets wether the color curves effect is enabled.
  42048. */
  42049. get: function () {
  42050. return this.imageProcessingConfiguration.colorCurvesEnabled;
  42051. },
  42052. /**
  42053. * Sets wether the color curves effect is enabled.
  42054. */
  42055. set: function (value) {
  42056. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  42057. },
  42058. enumerable: true,
  42059. configurable: true
  42060. });
  42061. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  42062. /**
  42063. * Gets wether the color grading effect is enabled.
  42064. */
  42065. get: function () {
  42066. return this.imageProcessingConfiguration.colorGradingEnabled;
  42067. },
  42068. /**
  42069. * Gets wether the color grading effect is enabled.
  42070. */
  42071. set: function (value) {
  42072. this.imageProcessingConfiguration.colorGradingEnabled = value;
  42073. },
  42074. enumerable: true,
  42075. configurable: true
  42076. });
  42077. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  42078. /**
  42079. * Gets wether tonemapping is enabled or not.
  42080. */
  42081. get: function () {
  42082. return this._imageProcessingConfiguration.toneMappingEnabled;
  42083. },
  42084. /**
  42085. * Sets wether tonemapping is enabled or not
  42086. */
  42087. set: function (value) {
  42088. this._imageProcessingConfiguration.toneMappingEnabled = value;
  42089. },
  42090. enumerable: true,
  42091. configurable: true
  42092. });
  42093. ;
  42094. ;
  42095. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  42096. /**
  42097. * The camera exposure used on this material.
  42098. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42099. * This corresponds to a photographic exposure.
  42100. */
  42101. get: function () {
  42102. return this._imageProcessingConfiguration.exposure;
  42103. },
  42104. /**
  42105. * The camera exposure used on this material.
  42106. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42107. * This corresponds to a photographic exposure.
  42108. */
  42109. set: function (value) {
  42110. this._imageProcessingConfiguration.exposure = value;
  42111. },
  42112. enumerable: true,
  42113. configurable: true
  42114. });
  42115. ;
  42116. ;
  42117. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  42118. /**
  42119. * Gets The camera contrast used on this material.
  42120. */
  42121. get: function () {
  42122. return this._imageProcessingConfiguration.contrast;
  42123. },
  42124. /**
  42125. * Sets The camera contrast used on this material.
  42126. */
  42127. set: function (value) {
  42128. this._imageProcessingConfiguration.contrast = value;
  42129. },
  42130. enumerable: true,
  42131. configurable: true
  42132. });
  42133. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  42134. /**
  42135. * Gets the Color Grading 2D Lookup Texture.
  42136. */
  42137. get: function () {
  42138. return this._imageProcessingConfiguration.colorGradingTexture;
  42139. },
  42140. /**
  42141. * Sets the Color Grading 2D Lookup Texture.
  42142. */
  42143. set: function (value) {
  42144. this._imageProcessingConfiguration.colorGradingTexture = value;
  42145. },
  42146. enumerable: true,
  42147. configurable: true
  42148. });
  42149. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  42150. /**
  42151. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42152. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42153. * 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;
  42154. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42155. */
  42156. get: function () {
  42157. return this._imageProcessingConfiguration.colorCurves;
  42158. },
  42159. /**
  42160. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42161. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42162. * 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;
  42163. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42164. */
  42165. set: function (value) {
  42166. this._imageProcessingConfiguration.colorCurves = value;
  42167. },
  42168. enumerable: true,
  42169. configurable: true
  42170. });
  42171. /**
  42172. * Returns the name of this material class.
  42173. */
  42174. PBRMaterial.prototype.getClassName = function () {
  42175. return "PBRMaterial";
  42176. };
  42177. /**
  42178. * Returns an array of the actively used textures.
  42179. * @returns - Array of BaseTextures
  42180. */
  42181. PBRMaterial.prototype.getActiveTextures = function () {
  42182. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42183. if (this._albedoTexture) {
  42184. activeTextures.push(this._albedoTexture);
  42185. }
  42186. if (this._ambientTexture) {
  42187. activeTextures.push(this._ambientTexture);
  42188. }
  42189. if (this._opacityTexture) {
  42190. activeTextures.push(this._opacityTexture);
  42191. }
  42192. if (this._reflectionTexture) {
  42193. activeTextures.push(this._reflectionTexture);
  42194. }
  42195. if (this._emissiveTexture) {
  42196. activeTextures.push(this._emissiveTexture);
  42197. }
  42198. if (this._reflectivityTexture) {
  42199. activeTextures.push(this._reflectivityTexture);
  42200. }
  42201. if (this._metallicTexture) {
  42202. activeTextures.push(this._metallicTexture);
  42203. }
  42204. if (this._microSurfaceTexture) {
  42205. activeTextures.push(this._microSurfaceTexture);
  42206. }
  42207. if (this._bumpTexture) {
  42208. activeTextures.push(this._bumpTexture);
  42209. }
  42210. if (this._lightmapTexture) {
  42211. activeTextures.push(this._lightmapTexture);
  42212. }
  42213. if (this._refractionTexture) {
  42214. activeTextures.push(this._refractionTexture);
  42215. }
  42216. return activeTextures;
  42217. };
  42218. /**
  42219. * Checks to see if a texture is used in the material.
  42220. * @param texture - Base texture to use.
  42221. * @returns - Boolean specifying if a texture is used in the material.
  42222. */
  42223. PBRMaterial.prototype.hasTexture = function (texture) {
  42224. if (_super.prototype.hasTexture.call(this, texture)) {
  42225. return true;
  42226. }
  42227. if (this._albedoTexture === texture) {
  42228. return true;
  42229. }
  42230. if (this._ambientTexture === texture) {
  42231. return true;
  42232. }
  42233. if (this._opacityTexture === texture) {
  42234. return true;
  42235. }
  42236. if (this._reflectionTexture === texture) {
  42237. return true;
  42238. }
  42239. if (this._reflectivityTexture === texture) {
  42240. return true;
  42241. }
  42242. if (this._metallicTexture === texture) {
  42243. return true;
  42244. }
  42245. if (this._microSurfaceTexture === texture) {
  42246. return true;
  42247. }
  42248. if (this._bumpTexture === texture) {
  42249. return true;
  42250. }
  42251. if (this._lightmapTexture === texture) {
  42252. return true;
  42253. }
  42254. if (this._refractionTexture === texture) {
  42255. return true;
  42256. }
  42257. return false;
  42258. };
  42259. /**
  42260. * Makes a duplicate of the current material.
  42261. * @param name - name to use for the new material.
  42262. */
  42263. PBRMaterial.prototype.clone = function (name) {
  42264. var _this = this;
  42265. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  42266. clone.id = name;
  42267. clone.name = name;
  42268. return clone;
  42269. };
  42270. /**
  42271. * Serializes this PBR Material.
  42272. * @returns - An object with the serialized material.
  42273. */
  42274. PBRMaterial.prototype.serialize = function () {
  42275. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  42276. serializationObject.customType = "BABYLON.PBRMaterial";
  42277. return serializationObject;
  42278. };
  42279. // Statics
  42280. /**
  42281. * Parses a PBR Material from a serialized object.
  42282. * @param source - Serialized object.
  42283. * @param scene - BJS scene instance.
  42284. * @param rootUrl - url for the scene object
  42285. * @returns - PBRMaterial
  42286. */
  42287. PBRMaterial.Parse = function (source, scene, rootUrl) {
  42288. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  42289. };
  42290. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  42291. /**
  42292. * Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  42293. */
  42294. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  42295. /**
  42296. * Represents the value for Alpha Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  42297. */
  42298. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  42299. /**
  42300. * Represents the value for Alpha Test and Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  42301. * They are also discarded below the alpha cutoff threshold to improve performances.
  42302. */
  42303. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  42304. __decorate([
  42305. BABYLON.serialize(),
  42306. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42307. ], PBRMaterial.prototype, "directIntensity", void 0);
  42308. __decorate([
  42309. BABYLON.serialize(),
  42310. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42311. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  42312. __decorate([
  42313. BABYLON.serialize(),
  42314. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42315. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  42316. __decorate([
  42317. BABYLON.serialize(),
  42318. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42319. ], PBRMaterial.prototype, "specularIntensity", void 0);
  42320. __decorate([
  42321. BABYLON.serialize(),
  42322. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42323. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  42324. __decorate([
  42325. BABYLON.serializeAsTexture(),
  42326. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42327. ], PBRMaterial.prototype, "albedoTexture", void 0);
  42328. __decorate([
  42329. BABYLON.serializeAsTexture(),
  42330. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42331. ], PBRMaterial.prototype, "ambientTexture", void 0);
  42332. __decorate([
  42333. BABYLON.serialize(),
  42334. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42335. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  42336. __decorate([
  42337. BABYLON.serializeAsTexture(),
  42338. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42339. ], PBRMaterial.prototype, "opacityTexture", void 0);
  42340. __decorate([
  42341. BABYLON.serializeAsTexture(),
  42342. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42343. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  42344. __decorate([
  42345. BABYLON.serializeAsTexture(),
  42346. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42347. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  42348. __decorate([
  42349. BABYLON.serializeAsTexture(),
  42350. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42351. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  42352. __decorate([
  42353. BABYLON.serializeAsTexture(),
  42354. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42355. ], PBRMaterial.prototype, "metallicTexture", void 0);
  42356. __decorate([
  42357. BABYLON.serialize(),
  42358. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42359. ], PBRMaterial.prototype, "metallic", void 0);
  42360. __decorate([
  42361. BABYLON.serialize(),
  42362. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42363. ], PBRMaterial.prototype, "roughness", void 0);
  42364. __decorate([
  42365. BABYLON.serializeAsTexture(),
  42366. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42367. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  42368. __decorate([
  42369. BABYLON.serializeAsTexture(),
  42370. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42371. ], PBRMaterial.prototype, "bumpTexture", void 0);
  42372. __decorate([
  42373. BABYLON.serializeAsTexture(),
  42374. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  42375. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  42376. __decorate([
  42377. BABYLON.serializeAsTexture(),
  42378. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42379. ], PBRMaterial.prototype, "refractionTexture", void 0);
  42380. __decorate([
  42381. BABYLON.serializeAsColor3("ambient"),
  42382. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42383. ], PBRMaterial.prototype, "ambientColor", void 0);
  42384. __decorate([
  42385. BABYLON.serializeAsColor3("albedo"),
  42386. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42387. ], PBRMaterial.prototype, "albedoColor", void 0);
  42388. __decorate([
  42389. BABYLON.serializeAsColor3("reflectivity"),
  42390. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42391. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  42392. __decorate([
  42393. BABYLON.serializeAsColor3("reflection"),
  42394. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42395. ], PBRMaterial.prototype, "reflectionColor", void 0);
  42396. __decorate([
  42397. BABYLON.serializeAsColor3("emissive"),
  42398. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42399. ], PBRMaterial.prototype, "emissiveColor", void 0);
  42400. __decorate([
  42401. BABYLON.serialize(),
  42402. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42403. ], PBRMaterial.prototype, "microSurface", void 0);
  42404. __decorate([
  42405. BABYLON.serialize(),
  42406. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42407. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  42408. __decorate([
  42409. BABYLON.serialize(),
  42410. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42411. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  42412. __decorate([
  42413. BABYLON.serialize(),
  42414. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42415. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  42416. __decorate([
  42417. BABYLON.serialize(),
  42418. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42419. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  42420. __decorate([
  42421. BABYLON.serialize(),
  42422. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42423. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  42424. __decorate([
  42425. BABYLON.serialize(),
  42426. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42427. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  42428. __decorate([
  42429. BABYLON.serialize(),
  42430. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42431. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  42432. __decorate([
  42433. BABYLON.serialize(),
  42434. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42435. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  42436. __decorate([
  42437. BABYLON.serialize(),
  42438. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42439. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  42440. __decorate([
  42441. BABYLON.serialize(),
  42442. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42443. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  42444. __decorate([
  42445. BABYLON.serialize(),
  42446. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42447. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  42448. __decorate([
  42449. BABYLON.serialize(),
  42450. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42451. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  42452. __decorate([
  42453. BABYLON.serialize(),
  42454. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42455. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  42456. __decorate([
  42457. BABYLON.serialize(),
  42458. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42459. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  42460. __decorate([
  42461. BABYLON.serialize(),
  42462. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42463. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  42464. __decorate([
  42465. BABYLON.serialize(),
  42466. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42467. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  42468. __decorate([
  42469. BABYLON.serialize(),
  42470. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42471. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  42472. __decorate([
  42473. BABYLON.serialize(),
  42474. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42475. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  42476. __decorate([
  42477. BABYLON.serialize(),
  42478. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42479. ], PBRMaterial.prototype, "useParallax", void 0);
  42480. __decorate([
  42481. BABYLON.serialize(),
  42482. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42483. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  42484. __decorate([
  42485. BABYLON.serialize(),
  42486. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42487. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  42488. __decorate([
  42489. BABYLON.serialize(),
  42490. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42491. ], PBRMaterial.prototype, "disableLighting", void 0);
  42492. __decorate([
  42493. BABYLON.serialize(),
  42494. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42495. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  42496. __decorate([
  42497. BABYLON.serialize(),
  42498. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42499. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  42500. __decorate([
  42501. BABYLON.serialize(),
  42502. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42503. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  42504. __decorate([
  42505. BABYLON.serialize(),
  42506. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42507. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  42508. __decorate([
  42509. BABYLON.serialize(),
  42510. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42511. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  42512. __decorate([
  42513. BABYLON.serialize(),
  42514. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42515. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  42516. __decorate([
  42517. BABYLON.serialize(),
  42518. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42519. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  42520. __decorate([
  42521. BABYLON.serializeAsTexture(),
  42522. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42523. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  42524. __decorate([
  42525. BABYLON.serialize(),
  42526. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42527. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  42528. __decorate([
  42529. BABYLON.serialize(),
  42530. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42531. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  42532. __decorate([
  42533. BABYLON.serialize(),
  42534. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42535. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  42536. return PBRMaterial;
  42537. }(BABYLON.PBRBaseMaterial));
  42538. BABYLON.PBRMaterial = PBRMaterial;
  42539. })(BABYLON || (BABYLON = {}));
  42540. //# sourceMappingURL=babylon.pbrMaterial.js.map
  42541. var BABYLON;
  42542. (function (BABYLON) {
  42543. /**
  42544. * The PBR material of BJS following the metal roughness convention.
  42545. *
  42546. * This fits to the PBR convention in the GLTF definition:
  42547. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  42548. */
  42549. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  42550. __extends(PBRMetallicRoughnessMaterial, _super);
  42551. /**
  42552. * Instantiates a new PBRMetalRoughnessMaterial instance.
  42553. *
  42554. * @param name The material name
  42555. * @param scene The scene the material will be use in.
  42556. */
  42557. function PBRMetallicRoughnessMaterial(name, scene) {
  42558. var _this = _super.call(this, name, scene) || this;
  42559. _this._useRoughnessFromMetallicTextureAlpha = false;
  42560. _this._useRoughnessFromMetallicTextureGreen = true;
  42561. _this._useMetallnessFromMetallicTextureBlue = true;
  42562. _this._forceMetallicWorkflow = true;
  42563. return _this;
  42564. }
  42565. /**
  42566. * Return the currrent class name of the material.
  42567. */
  42568. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  42569. return "PBRMetallicRoughnessMaterial";
  42570. };
  42571. /**
  42572. * Return the active textures of the material.
  42573. */
  42574. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  42575. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42576. if (this.baseTexture) {
  42577. activeTextures.push(this.baseTexture);
  42578. }
  42579. if (this.metallicRoughnessTexture) {
  42580. activeTextures.push(this.metallicRoughnessTexture);
  42581. }
  42582. return activeTextures;
  42583. };
  42584. /**
  42585. * Checks to see if a texture is used in the material.
  42586. * @param texture - Base texture to use.
  42587. * @returns - Boolean specifying if a texture is used in the material.
  42588. */
  42589. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  42590. if (_super.prototype.hasTexture.call(this, texture)) {
  42591. return true;
  42592. }
  42593. if (this.baseTexture === texture) {
  42594. return true;
  42595. }
  42596. if (this.metallicRoughnessTexture === texture) {
  42597. return true;
  42598. }
  42599. return false;
  42600. };
  42601. /**
  42602. * Makes a duplicate of the current material.
  42603. * @param name - name to use for the new material.
  42604. */
  42605. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  42606. var _this = this;
  42607. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  42608. clone.id = name;
  42609. clone.name = name;
  42610. return clone;
  42611. };
  42612. /**
  42613. * Serialize the material to a parsable JSON object.
  42614. */
  42615. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  42616. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  42617. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  42618. return serializationObject;
  42619. };
  42620. /**
  42621. * Parses a JSON object correponding to the serialize function.
  42622. */
  42623. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  42624. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  42625. };
  42626. __decorate([
  42627. BABYLON.serializeAsColor3(),
  42628. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  42629. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  42630. __decorate([
  42631. BABYLON.serializeAsTexture(),
  42632. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  42633. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  42634. __decorate([
  42635. BABYLON.serialize(),
  42636. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42637. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  42638. __decorate([
  42639. BABYLON.serialize(),
  42640. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42641. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  42642. __decorate([
  42643. BABYLON.serializeAsTexture(),
  42644. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  42645. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  42646. return PBRMetallicRoughnessMaterial;
  42647. }(BABYLON.PBRBaseSimpleMaterial));
  42648. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  42649. })(BABYLON || (BABYLON = {}));
  42650. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  42651. var BABYLON;
  42652. (function (BABYLON) {
  42653. /**
  42654. * The PBR material of BJS following the specular glossiness convention.
  42655. *
  42656. * This fits to the PBR convention in the GLTF definition:
  42657. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  42658. */
  42659. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  42660. __extends(PBRSpecularGlossinessMaterial, _super);
  42661. /**
  42662. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  42663. *
  42664. * @param name The material name
  42665. * @param scene The scene the material will be use in.
  42666. */
  42667. function PBRSpecularGlossinessMaterial(name, scene) {
  42668. var _this = _super.call(this, name, scene) || this;
  42669. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  42670. return _this;
  42671. }
  42672. /**
  42673. * Return the currrent class name of the material.
  42674. */
  42675. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  42676. return "PBRSpecularGlossinessMaterial";
  42677. };
  42678. /**
  42679. * Return the active textures of the material.
  42680. */
  42681. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  42682. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42683. if (this.diffuseTexture) {
  42684. activeTextures.push(this.diffuseTexture);
  42685. }
  42686. if (this.specularGlossinessTexture) {
  42687. activeTextures.push(this.specularGlossinessTexture);
  42688. }
  42689. return activeTextures;
  42690. };
  42691. /**
  42692. * Checks to see if a texture is used in the material.
  42693. * @param texture - Base texture to use.
  42694. * @returns - Boolean specifying if a texture is used in the material.
  42695. */
  42696. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  42697. if (_super.prototype.hasTexture.call(this, texture)) {
  42698. return true;
  42699. }
  42700. if (this.diffuseTexture === texture) {
  42701. return true;
  42702. }
  42703. if (this.specularGlossinessTexture === texture) {
  42704. return true;
  42705. }
  42706. return false;
  42707. };
  42708. /**
  42709. * Makes a duplicate of the current material.
  42710. * @param name - name to use for the new material.
  42711. */
  42712. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  42713. var _this = this;
  42714. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  42715. clone.id = name;
  42716. clone.name = name;
  42717. return clone;
  42718. };
  42719. /**
  42720. * Serialize the material to a parsable JSON object.
  42721. */
  42722. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  42723. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  42724. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  42725. return serializationObject;
  42726. };
  42727. /**
  42728. * Parses a JSON object correponding to the serialize function.
  42729. */
  42730. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  42731. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  42732. };
  42733. __decorate([
  42734. BABYLON.serializeAsColor3("diffuse"),
  42735. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  42736. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  42737. __decorate([
  42738. BABYLON.serializeAsTexture(),
  42739. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  42740. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  42741. __decorate([
  42742. BABYLON.serializeAsColor3("specular"),
  42743. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  42744. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  42745. __decorate([
  42746. BABYLON.serialize(),
  42747. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  42748. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  42749. __decorate([
  42750. BABYLON.serializeAsTexture(),
  42751. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  42752. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  42753. return PBRSpecularGlossinessMaterial;
  42754. }(BABYLON.PBRBaseSimpleMaterial));
  42755. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  42756. })(BABYLON || (BABYLON = {}));
  42757. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  42758. var BABYLON;
  42759. (function (BABYLON) {
  42760. BABYLON.CameraInputTypes = {};
  42761. var CameraInputsManager = /** @class */ (function () {
  42762. function CameraInputsManager(camera) {
  42763. this.attached = {};
  42764. this.camera = camera;
  42765. this.checkInputs = function () { };
  42766. }
  42767. /**
  42768. * Add an input method to a camera.
  42769. * builtin inputs example: camera.inputs.addGamepad();
  42770. * custom inputs example: camera.inputs.add(new BABYLON.FreeCameraGamepadInput());
  42771. * @param input camera input method
  42772. */
  42773. CameraInputsManager.prototype.add = function (input) {
  42774. var type = input.getSimpleName();
  42775. if (this.attached[type]) {
  42776. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  42777. return;
  42778. }
  42779. this.attached[type] = input;
  42780. input.camera = this.camera;
  42781. //for checkInputs, we are dynamically creating a function
  42782. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  42783. if (input.checkInputs) {
  42784. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  42785. }
  42786. if (this.attachedElement) {
  42787. input.attachControl(this.attachedElement);
  42788. }
  42789. };
  42790. /**
  42791. * Remove a specific input method from a camera
  42792. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  42793. * @param inputToRemove camera input method
  42794. */
  42795. CameraInputsManager.prototype.remove = function (inputToRemove) {
  42796. for (var cam in this.attached) {
  42797. var input = this.attached[cam];
  42798. if (input === inputToRemove) {
  42799. input.detachControl(this.attachedElement);
  42800. input.camera = null;
  42801. delete this.attached[cam];
  42802. this.rebuildInputCheck();
  42803. }
  42804. }
  42805. };
  42806. CameraInputsManager.prototype.removeByType = function (inputType) {
  42807. for (var cam in this.attached) {
  42808. var input = this.attached[cam];
  42809. if (input.getClassName() === inputType) {
  42810. input.detachControl(this.attachedElement);
  42811. input.camera = null;
  42812. delete this.attached[cam];
  42813. this.rebuildInputCheck();
  42814. }
  42815. }
  42816. };
  42817. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  42818. var current = this.checkInputs;
  42819. return function () {
  42820. current();
  42821. fn();
  42822. };
  42823. };
  42824. CameraInputsManager.prototype.attachInput = function (input) {
  42825. if (this.attachedElement) {
  42826. input.attachControl(this.attachedElement, this.noPreventDefault);
  42827. }
  42828. };
  42829. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  42830. if (noPreventDefault === void 0) { noPreventDefault = false; }
  42831. if (this.attachedElement) {
  42832. return;
  42833. }
  42834. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  42835. this.attachedElement = element;
  42836. this.noPreventDefault = noPreventDefault;
  42837. for (var cam in this.attached) {
  42838. this.attached[cam].attachControl(element, noPreventDefault);
  42839. }
  42840. };
  42841. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  42842. if (disconnect === void 0) { disconnect = false; }
  42843. if (this.attachedElement !== element) {
  42844. return;
  42845. }
  42846. for (var cam in this.attached) {
  42847. this.attached[cam].detachControl(element);
  42848. if (disconnect) {
  42849. this.attached[cam].camera = null;
  42850. }
  42851. }
  42852. this.attachedElement = null;
  42853. };
  42854. CameraInputsManager.prototype.rebuildInputCheck = function () {
  42855. this.checkInputs = function () { };
  42856. for (var cam in this.attached) {
  42857. var input = this.attached[cam];
  42858. if (input.checkInputs) {
  42859. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  42860. }
  42861. }
  42862. };
  42863. /**
  42864. * Remove all attached input methods from a camera
  42865. */
  42866. CameraInputsManager.prototype.clear = function () {
  42867. if (this.attachedElement) {
  42868. this.detachElement(this.attachedElement, true);
  42869. }
  42870. this.attached = {};
  42871. this.attachedElement = null;
  42872. this.checkInputs = function () { };
  42873. };
  42874. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  42875. var inputs = {};
  42876. for (var cam in this.attached) {
  42877. var input = this.attached[cam];
  42878. var res = BABYLON.SerializationHelper.Serialize(input);
  42879. inputs[input.getClassName()] = res;
  42880. }
  42881. serializedCamera.inputsmgr = inputs;
  42882. };
  42883. CameraInputsManager.prototype.parse = function (parsedCamera) {
  42884. var parsedInputs = parsedCamera.inputsmgr;
  42885. if (parsedInputs) {
  42886. this.clear();
  42887. for (var n in parsedInputs) {
  42888. var construct = BABYLON.CameraInputTypes[n];
  42889. if (construct) {
  42890. var parsedinput = parsedInputs[n];
  42891. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  42892. this.add(input);
  42893. }
  42894. }
  42895. }
  42896. else {
  42897. //2016-03-08 this part is for managing backward compatibility
  42898. for (var n in this.attached) {
  42899. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  42900. if (construct) {
  42901. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  42902. this.remove(this.attached[n]);
  42903. this.add(input);
  42904. }
  42905. }
  42906. }
  42907. };
  42908. return CameraInputsManager;
  42909. }());
  42910. BABYLON.CameraInputsManager = CameraInputsManager;
  42911. })(BABYLON || (BABYLON = {}));
  42912. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  42913. var BABYLON;
  42914. (function (BABYLON) {
  42915. var TargetCamera = /** @class */ (function (_super) {
  42916. __extends(TargetCamera, _super);
  42917. function TargetCamera(name, position, scene) {
  42918. var _this = _super.call(this, name, position, scene) || this;
  42919. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  42920. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  42921. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  42922. _this.speed = 2.0;
  42923. _this.noRotationConstraint = false;
  42924. _this.lockedTarget = null;
  42925. _this._currentTarget = BABYLON.Vector3.Zero();
  42926. _this._viewMatrix = BABYLON.Matrix.Zero();
  42927. _this._camMatrix = BABYLON.Matrix.Zero();
  42928. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  42929. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  42930. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  42931. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  42932. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  42933. _this._lookAtTemp = BABYLON.Matrix.Zero();
  42934. _this._tempMatrix = BABYLON.Matrix.Zero();
  42935. return _this;
  42936. }
  42937. TargetCamera.prototype.getFrontPosition = function (distance) {
  42938. this.getWorldMatrix();
  42939. var direction = this.getTarget().subtract(this.position);
  42940. direction.normalize();
  42941. direction.scaleInPlace(distance);
  42942. return this.globalPosition.add(direction);
  42943. };
  42944. TargetCamera.prototype._getLockedTargetPosition = function () {
  42945. if (!this.lockedTarget) {
  42946. return null;
  42947. }
  42948. if (this.lockedTarget.absolutePosition) {
  42949. this.lockedTarget.computeWorldMatrix();
  42950. }
  42951. return this.lockedTarget.absolutePosition || this.lockedTarget;
  42952. };
  42953. TargetCamera.prototype.storeState = function () {
  42954. this._storedPosition = this.position.clone();
  42955. this._storedRotation = this.rotation.clone();
  42956. if (this.rotationQuaternion) {
  42957. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  42958. }
  42959. return _super.prototype.storeState.call(this);
  42960. };
  42961. /**
  42962. * Restored camera state. You must call storeState() first
  42963. */
  42964. TargetCamera.prototype._restoreStateValues = function () {
  42965. if (!_super.prototype._restoreStateValues.call(this)) {
  42966. return false;
  42967. }
  42968. this.position = this._storedPosition.clone();
  42969. this.rotation = this._storedRotation.clone();
  42970. if (this.rotationQuaternion) {
  42971. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  42972. }
  42973. this.cameraDirection.copyFromFloats(0, 0, 0);
  42974. this.cameraRotation.copyFromFloats(0, 0);
  42975. return true;
  42976. };
  42977. // Cache
  42978. TargetCamera.prototype._initCache = function () {
  42979. _super.prototype._initCache.call(this);
  42980. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  42981. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  42982. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  42983. };
  42984. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  42985. if (!ignoreParentClass) {
  42986. _super.prototype._updateCache.call(this);
  42987. }
  42988. var lockedTargetPosition = this._getLockedTargetPosition();
  42989. if (!lockedTargetPosition) {
  42990. this._cache.lockedTarget = null;
  42991. }
  42992. else {
  42993. if (!this._cache.lockedTarget) {
  42994. this._cache.lockedTarget = lockedTargetPosition.clone();
  42995. }
  42996. else {
  42997. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  42998. }
  42999. }
  43000. this._cache.rotation.copyFrom(this.rotation);
  43001. if (this.rotationQuaternion)
  43002. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  43003. };
  43004. // Synchronized
  43005. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  43006. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  43007. return false;
  43008. }
  43009. var lockedTargetPosition = this._getLockedTargetPosition();
  43010. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  43011. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  43012. };
  43013. // Methods
  43014. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  43015. var engine = this.getEngine();
  43016. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  43017. };
  43018. // Target
  43019. TargetCamera.prototype.setTarget = function (target) {
  43020. this.upVector.normalize();
  43021. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  43022. this._camMatrix.invert();
  43023. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  43024. var vDir = target.subtract(this.position);
  43025. if (vDir.x >= 0.0) {
  43026. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  43027. }
  43028. else {
  43029. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  43030. }
  43031. this.rotation.z = 0;
  43032. if (isNaN(this.rotation.x)) {
  43033. this.rotation.x = 0;
  43034. }
  43035. if (isNaN(this.rotation.y)) {
  43036. this.rotation.y = 0;
  43037. }
  43038. if (isNaN(this.rotation.z)) {
  43039. this.rotation.z = 0;
  43040. }
  43041. if (this.rotationQuaternion) {
  43042. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  43043. }
  43044. };
  43045. /**
  43046. * Return the current target position of the camera. This value is expressed in local space.
  43047. */
  43048. TargetCamera.prototype.getTarget = function () {
  43049. return this._currentTarget;
  43050. };
  43051. TargetCamera.prototype._decideIfNeedsToMove = function () {
  43052. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  43053. };
  43054. TargetCamera.prototype._updatePosition = function () {
  43055. if (this.parent) {
  43056. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  43057. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  43058. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  43059. return;
  43060. }
  43061. this.position.addInPlace(this.cameraDirection);
  43062. };
  43063. TargetCamera.prototype._checkInputs = function () {
  43064. var needToMove = this._decideIfNeedsToMove();
  43065. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  43066. // Move
  43067. if (needToMove) {
  43068. this._updatePosition();
  43069. }
  43070. // Rotate
  43071. if (needToRotate) {
  43072. this.rotation.x += this.cameraRotation.x;
  43073. this.rotation.y += this.cameraRotation.y;
  43074. //rotate, if quaternion is set and rotation was used
  43075. if (this.rotationQuaternion) {
  43076. var len = this.rotation.lengthSquared();
  43077. if (len) {
  43078. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  43079. }
  43080. }
  43081. if (!this.noRotationConstraint) {
  43082. var limit = (Math.PI / 2) * 0.95;
  43083. if (this.rotation.x > limit)
  43084. this.rotation.x = limit;
  43085. if (this.rotation.x < -limit)
  43086. this.rotation.x = -limit;
  43087. }
  43088. }
  43089. // Inertia
  43090. if (needToMove) {
  43091. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  43092. this.cameraDirection.x = 0;
  43093. }
  43094. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  43095. this.cameraDirection.y = 0;
  43096. }
  43097. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  43098. this.cameraDirection.z = 0;
  43099. }
  43100. this.cameraDirection.scaleInPlace(this.inertia);
  43101. }
  43102. if (needToRotate) {
  43103. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  43104. this.cameraRotation.x = 0;
  43105. }
  43106. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  43107. this.cameraRotation.y = 0;
  43108. }
  43109. this.cameraRotation.scaleInPlace(this.inertia);
  43110. }
  43111. _super.prototype._checkInputs.call(this);
  43112. };
  43113. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  43114. if (this.rotationQuaternion) {
  43115. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  43116. }
  43117. else {
  43118. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  43119. }
  43120. //update the up vector!
  43121. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  43122. };
  43123. TargetCamera.prototype._getViewMatrix = function () {
  43124. if (this.lockedTarget) {
  43125. this.setTarget(this._getLockedTargetPosition());
  43126. }
  43127. // Compute
  43128. this._updateCameraRotationMatrix();
  43129. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  43130. // Computing target and final matrix
  43131. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  43132. if (this.getScene().useRightHandedSystem) {
  43133. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  43134. }
  43135. else {
  43136. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  43137. }
  43138. return this._viewMatrix;
  43139. };
  43140. /**
  43141. * @override
  43142. * Override Camera.createRigCamera
  43143. */
  43144. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  43145. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  43146. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  43147. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  43148. if (!this.rotationQuaternion) {
  43149. this.rotationQuaternion = new BABYLON.Quaternion();
  43150. }
  43151. rigCamera._cameraRigParams = {};
  43152. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  43153. }
  43154. return rigCamera;
  43155. }
  43156. return null;
  43157. };
  43158. /**
  43159. * @override
  43160. * Override Camera._updateRigCameras
  43161. */
  43162. TargetCamera.prototype._updateRigCameras = function () {
  43163. var camLeft = this._rigCameras[0];
  43164. var camRight = this._rigCameras[1];
  43165. switch (this.cameraRigMode) {
  43166. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  43167. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  43168. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  43169. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  43170. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  43171. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  43172. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  43173. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  43174. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  43175. camLeft.setTarget(this.getTarget());
  43176. camRight.setTarget(this.getTarget());
  43177. break;
  43178. case BABYLON.Camera.RIG_MODE_VR:
  43179. if (camLeft.rotationQuaternion) {
  43180. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  43181. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  43182. }
  43183. else {
  43184. camLeft.rotation.copyFrom(this.rotation);
  43185. camRight.rotation.copyFrom(this.rotation);
  43186. }
  43187. camLeft.position.copyFrom(this.position);
  43188. camRight.position.copyFrom(this.position);
  43189. break;
  43190. }
  43191. _super.prototype._updateRigCameras.call(this);
  43192. };
  43193. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  43194. if (!this._rigCamTransformMatrix) {
  43195. this._rigCamTransformMatrix = new BABYLON.Matrix();
  43196. }
  43197. var target = this.getTarget();
  43198. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  43199. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  43200. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  43201. };
  43202. TargetCamera.prototype.getClassName = function () {
  43203. return "TargetCamera";
  43204. };
  43205. __decorate([
  43206. BABYLON.serializeAsVector3()
  43207. ], TargetCamera.prototype, "rotation", void 0);
  43208. __decorate([
  43209. BABYLON.serialize()
  43210. ], TargetCamera.prototype, "speed", void 0);
  43211. __decorate([
  43212. BABYLON.serializeAsMeshReference("lockedTargetId")
  43213. ], TargetCamera.prototype, "lockedTarget", void 0);
  43214. return TargetCamera;
  43215. }(BABYLON.Camera));
  43216. BABYLON.TargetCamera = TargetCamera;
  43217. })(BABYLON || (BABYLON = {}));
  43218. //# sourceMappingURL=babylon.targetCamera.js.map
  43219. var BABYLON;
  43220. (function (BABYLON) {
  43221. var FreeCameraMouseInput = /** @class */ (function () {
  43222. function FreeCameraMouseInput(touchEnabled) {
  43223. if (touchEnabled === void 0) { touchEnabled = true; }
  43224. this.touchEnabled = touchEnabled;
  43225. this.buttons = [0, 1, 2];
  43226. this.angularSensibility = 2000.0;
  43227. this.previousPosition = null;
  43228. }
  43229. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  43230. var _this = this;
  43231. var engine = this.camera.getEngine();
  43232. if (!this._pointerInput) {
  43233. this._pointerInput = function (p, s) {
  43234. var evt = p.event;
  43235. if (engine.isInVRExclusivePointerMode) {
  43236. return;
  43237. }
  43238. if (!_this.touchEnabled && evt.pointerType === "touch") {
  43239. return;
  43240. }
  43241. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  43242. return;
  43243. }
  43244. var srcElement = (evt.srcElement || evt.target);
  43245. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  43246. try {
  43247. srcElement.setPointerCapture(evt.pointerId);
  43248. }
  43249. catch (e) {
  43250. //Nothing to do with the error. Execution will continue.
  43251. }
  43252. _this.previousPosition = {
  43253. x: evt.clientX,
  43254. y: evt.clientY
  43255. };
  43256. if (!noPreventDefault) {
  43257. evt.preventDefault();
  43258. element.focus();
  43259. }
  43260. }
  43261. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  43262. try {
  43263. srcElement.releasePointerCapture(evt.pointerId);
  43264. }
  43265. catch (e) {
  43266. //Nothing to do with the error.
  43267. }
  43268. _this.previousPosition = null;
  43269. if (!noPreventDefault) {
  43270. evt.preventDefault();
  43271. }
  43272. }
  43273. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  43274. if (!_this.previousPosition || engine.isPointerLock) {
  43275. return;
  43276. }
  43277. var offsetX = evt.clientX - _this.previousPosition.x;
  43278. var offsetY = evt.clientY - _this.previousPosition.y;
  43279. if (_this.camera.getScene().useRightHandedSystem) {
  43280. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  43281. }
  43282. else {
  43283. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  43284. }
  43285. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  43286. _this.previousPosition = {
  43287. x: evt.clientX,
  43288. y: evt.clientY
  43289. };
  43290. if (!noPreventDefault) {
  43291. evt.preventDefault();
  43292. }
  43293. }
  43294. };
  43295. }
  43296. this._onMouseMove = function (evt) {
  43297. if (!engine.isPointerLock) {
  43298. return;
  43299. }
  43300. if (engine.isInVRExclusivePointerMode) {
  43301. return;
  43302. }
  43303. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  43304. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  43305. if (_this.camera.getScene().useRightHandedSystem) {
  43306. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  43307. }
  43308. else {
  43309. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  43310. }
  43311. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  43312. _this.previousPosition = null;
  43313. if (!noPreventDefault) {
  43314. evt.preventDefault();
  43315. }
  43316. };
  43317. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  43318. element.addEventListener("mousemove", this._onMouseMove, false);
  43319. };
  43320. FreeCameraMouseInput.prototype.detachControl = function (element) {
  43321. if (this._observer && element) {
  43322. this.camera.getScene().onPointerObservable.remove(this._observer);
  43323. if (this._onMouseMove) {
  43324. element.removeEventListener("mousemove", this._onMouseMove);
  43325. }
  43326. this._observer = null;
  43327. this._onMouseMove = null;
  43328. this.previousPosition = null;
  43329. }
  43330. };
  43331. FreeCameraMouseInput.prototype.getClassName = function () {
  43332. return "FreeCameraMouseInput";
  43333. };
  43334. FreeCameraMouseInput.prototype.getSimpleName = function () {
  43335. return "mouse";
  43336. };
  43337. __decorate([
  43338. BABYLON.serialize()
  43339. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  43340. __decorate([
  43341. BABYLON.serialize()
  43342. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  43343. return FreeCameraMouseInput;
  43344. }());
  43345. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  43346. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  43347. })(BABYLON || (BABYLON = {}));
  43348. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  43349. var BABYLON;
  43350. (function (BABYLON) {
  43351. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  43352. function FreeCameraKeyboardMoveInput() {
  43353. this._keys = new Array();
  43354. this.keysUp = [38];
  43355. this.keysDown = [40];
  43356. this.keysLeft = [37];
  43357. this.keysRight = [39];
  43358. }
  43359. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  43360. var _this = this;
  43361. if (this._onCanvasBlurObserver) {
  43362. return;
  43363. }
  43364. this._scene = this.camera.getScene();
  43365. this._engine = this._scene.getEngine();
  43366. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  43367. _this._keys = [];
  43368. });
  43369. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  43370. var evt = info.event;
  43371. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  43372. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  43373. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  43374. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  43375. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  43376. var index = _this._keys.indexOf(evt.keyCode);
  43377. if (index === -1) {
  43378. _this._keys.push(evt.keyCode);
  43379. }
  43380. if (!noPreventDefault) {
  43381. evt.preventDefault();
  43382. }
  43383. }
  43384. }
  43385. else {
  43386. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  43387. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  43388. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  43389. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  43390. var index = _this._keys.indexOf(evt.keyCode);
  43391. if (index >= 0) {
  43392. _this._keys.splice(index, 1);
  43393. }
  43394. if (!noPreventDefault) {
  43395. evt.preventDefault();
  43396. }
  43397. }
  43398. }
  43399. });
  43400. };
  43401. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  43402. if (this._scene) {
  43403. if (this._onKeyboardObserver) {
  43404. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  43405. }
  43406. if (this._onCanvasBlurObserver) {
  43407. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  43408. }
  43409. this._onKeyboardObserver = null;
  43410. this._onCanvasBlurObserver = null;
  43411. }
  43412. this._keys = [];
  43413. };
  43414. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  43415. if (this._onKeyboardObserver) {
  43416. var camera = this.camera;
  43417. // Keyboard
  43418. for (var index = 0; index < this._keys.length; index++) {
  43419. var keyCode = this._keys[index];
  43420. var speed = camera._computeLocalCameraSpeed();
  43421. if (this.keysLeft.indexOf(keyCode) !== -1) {
  43422. camera._localDirection.copyFromFloats(-speed, 0, 0);
  43423. }
  43424. else if (this.keysUp.indexOf(keyCode) !== -1) {
  43425. camera._localDirection.copyFromFloats(0, 0, speed);
  43426. }
  43427. else if (this.keysRight.indexOf(keyCode) !== -1) {
  43428. camera._localDirection.copyFromFloats(speed, 0, 0);
  43429. }
  43430. else if (this.keysDown.indexOf(keyCode) !== -1) {
  43431. camera._localDirection.copyFromFloats(0, 0, -speed);
  43432. }
  43433. if (camera.getScene().useRightHandedSystem) {
  43434. camera._localDirection.z *= -1;
  43435. }
  43436. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  43437. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  43438. camera.cameraDirection.addInPlace(camera._transformedDirection);
  43439. }
  43440. }
  43441. };
  43442. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  43443. return "FreeCameraKeyboardMoveInput";
  43444. };
  43445. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  43446. this._keys = [];
  43447. };
  43448. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  43449. return "keyboard";
  43450. };
  43451. __decorate([
  43452. BABYLON.serialize()
  43453. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  43454. __decorate([
  43455. BABYLON.serialize()
  43456. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  43457. __decorate([
  43458. BABYLON.serialize()
  43459. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  43460. __decorate([
  43461. BABYLON.serialize()
  43462. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  43463. return FreeCameraKeyboardMoveInput;
  43464. }());
  43465. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  43466. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  43467. })(BABYLON || (BABYLON = {}));
  43468. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  43469. var BABYLON;
  43470. (function (BABYLON) {
  43471. var FreeCameraInputsManager = /** @class */ (function (_super) {
  43472. __extends(FreeCameraInputsManager, _super);
  43473. function FreeCameraInputsManager(camera) {
  43474. return _super.call(this, camera) || this;
  43475. }
  43476. FreeCameraInputsManager.prototype.addKeyboard = function () {
  43477. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  43478. return this;
  43479. };
  43480. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  43481. if (touchEnabled === void 0) { touchEnabled = true; }
  43482. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  43483. return this;
  43484. };
  43485. FreeCameraInputsManager.prototype.addGamepad = function () {
  43486. this.add(new BABYLON.FreeCameraGamepadInput());
  43487. return this;
  43488. };
  43489. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  43490. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  43491. return this;
  43492. };
  43493. FreeCameraInputsManager.prototype.addTouch = function () {
  43494. this.add(new BABYLON.FreeCameraTouchInput());
  43495. return this;
  43496. };
  43497. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  43498. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  43499. return this;
  43500. };
  43501. return FreeCameraInputsManager;
  43502. }(BABYLON.CameraInputsManager));
  43503. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  43504. })(BABYLON || (BABYLON = {}));
  43505. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  43506. var BABYLON;
  43507. (function (BABYLON) {
  43508. var FreeCamera = /** @class */ (function (_super) {
  43509. __extends(FreeCamera, _super);
  43510. function FreeCamera(name, position, scene) {
  43511. var _this = _super.call(this, name, position, scene) || this;
  43512. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  43513. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  43514. _this.checkCollisions = false;
  43515. _this.applyGravity = false;
  43516. _this._needMoveForGravity = false;
  43517. _this._oldPosition = BABYLON.Vector3.Zero();
  43518. _this._diffPosition = BABYLON.Vector3.Zero();
  43519. _this._newPosition = BABYLON.Vector3.Zero();
  43520. // Collisions
  43521. _this._collisionMask = -1;
  43522. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  43523. if (collidedMesh === void 0) { collidedMesh = null; }
  43524. //TODO move this to the collision coordinator!
  43525. if (_this.getScene().workerCollisions)
  43526. newPosition.multiplyInPlace(_this._collider._radius);
  43527. var updatePosition = function (newPos) {
  43528. _this._newPosition.copyFrom(newPos);
  43529. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  43530. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  43531. _this.position.addInPlace(_this._diffPosition);
  43532. if (_this.onCollide && collidedMesh) {
  43533. _this.onCollide(collidedMesh);
  43534. }
  43535. }
  43536. };
  43537. updatePosition(newPosition);
  43538. };
  43539. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  43540. _this.inputs.addKeyboard().addMouse();
  43541. return _this;
  43542. }
  43543. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  43544. //-- begin properties for backward compatibility for inputs
  43545. /**
  43546. * Gets the input sensibility for a mouse input. (default is 2000.0)
  43547. * Higher values reduce sensitivity.
  43548. */
  43549. get: function () {
  43550. var mouse = this.inputs.attached["mouse"];
  43551. if (mouse)
  43552. return mouse.angularSensibility;
  43553. return 0;
  43554. },
  43555. /**
  43556. * Sets the input sensibility for a mouse input. (default is 2000.0)
  43557. * Higher values reduce sensitivity.
  43558. */
  43559. set: function (value) {
  43560. var mouse = this.inputs.attached["mouse"];
  43561. if (mouse)
  43562. mouse.angularSensibility = value;
  43563. },
  43564. enumerable: true,
  43565. configurable: true
  43566. });
  43567. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  43568. get: function () {
  43569. var keyboard = this.inputs.attached["keyboard"];
  43570. if (keyboard)
  43571. return keyboard.keysUp;
  43572. return [];
  43573. },
  43574. set: function (value) {
  43575. var keyboard = this.inputs.attached["keyboard"];
  43576. if (keyboard)
  43577. keyboard.keysUp = value;
  43578. },
  43579. enumerable: true,
  43580. configurable: true
  43581. });
  43582. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  43583. get: function () {
  43584. var keyboard = this.inputs.attached["keyboard"];
  43585. if (keyboard)
  43586. return keyboard.keysDown;
  43587. return [];
  43588. },
  43589. set: function (value) {
  43590. var keyboard = this.inputs.attached["keyboard"];
  43591. if (keyboard)
  43592. keyboard.keysDown = value;
  43593. },
  43594. enumerable: true,
  43595. configurable: true
  43596. });
  43597. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  43598. get: function () {
  43599. var keyboard = this.inputs.attached["keyboard"];
  43600. if (keyboard)
  43601. return keyboard.keysLeft;
  43602. return [];
  43603. },
  43604. set: function (value) {
  43605. var keyboard = this.inputs.attached["keyboard"];
  43606. if (keyboard)
  43607. keyboard.keysLeft = value;
  43608. },
  43609. enumerable: true,
  43610. configurable: true
  43611. });
  43612. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  43613. get: function () {
  43614. var keyboard = this.inputs.attached["keyboard"];
  43615. if (keyboard)
  43616. return keyboard.keysRight;
  43617. return [];
  43618. },
  43619. set: function (value) {
  43620. var keyboard = this.inputs.attached["keyboard"];
  43621. if (keyboard)
  43622. keyboard.keysRight = value;
  43623. },
  43624. enumerable: true,
  43625. configurable: true
  43626. });
  43627. // Controls
  43628. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  43629. this.inputs.attachElement(element, noPreventDefault);
  43630. };
  43631. FreeCamera.prototype.detachControl = function (element) {
  43632. this.inputs.detachElement(element);
  43633. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  43634. this.cameraRotation = new BABYLON.Vector2(0, 0);
  43635. };
  43636. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  43637. get: function () {
  43638. return this._collisionMask;
  43639. },
  43640. set: function (mask) {
  43641. this._collisionMask = !isNaN(mask) ? mask : -1;
  43642. },
  43643. enumerable: true,
  43644. configurable: true
  43645. });
  43646. FreeCamera.prototype._collideWithWorld = function (displacement) {
  43647. var globalPosition;
  43648. if (this.parent) {
  43649. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  43650. }
  43651. else {
  43652. globalPosition = this.position;
  43653. }
  43654. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  43655. this._oldPosition.addInPlace(this.ellipsoidOffset);
  43656. if (!this._collider) {
  43657. this._collider = new BABYLON.Collider();
  43658. }
  43659. this._collider._radius = this.ellipsoid;
  43660. this._collider.collisionMask = this._collisionMask;
  43661. //no need for clone, as long as gravity is not on.
  43662. var actualDisplacement = displacement;
  43663. //add gravity to the direction to prevent the dual-collision checking
  43664. if (this.applyGravity) {
  43665. //this prevents mending with cameraDirection, a global variable of the free camera class.
  43666. actualDisplacement = displacement.add(this.getScene().gravity);
  43667. }
  43668. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  43669. };
  43670. FreeCamera.prototype._checkInputs = function () {
  43671. if (!this._localDirection) {
  43672. this._localDirection = BABYLON.Vector3.Zero();
  43673. this._transformedDirection = BABYLON.Vector3.Zero();
  43674. }
  43675. this.inputs.checkInputs();
  43676. _super.prototype._checkInputs.call(this);
  43677. };
  43678. FreeCamera.prototype._decideIfNeedsToMove = function () {
  43679. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  43680. };
  43681. FreeCamera.prototype._updatePosition = function () {
  43682. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  43683. this._collideWithWorld(this.cameraDirection);
  43684. }
  43685. else {
  43686. _super.prototype._updatePosition.call(this);
  43687. }
  43688. };
  43689. FreeCamera.prototype.dispose = function () {
  43690. this.inputs.clear();
  43691. _super.prototype.dispose.call(this);
  43692. };
  43693. FreeCamera.prototype.getClassName = function () {
  43694. return "FreeCamera";
  43695. };
  43696. __decorate([
  43697. BABYLON.serializeAsVector3()
  43698. ], FreeCamera.prototype, "ellipsoid", void 0);
  43699. __decorate([
  43700. BABYLON.serializeAsVector3()
  43701. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  43702. __decorate([
  43703. BABYLON.serialize()
  43704. ], FreeCamera.prototype, "checkCollisions", void 0);
  43705. __decorate([
  43706. BABYLON.serialize()
  43707. ], FreeCamera.prototype, "applyGravity", void 0);
  43708. return FreeCamera;
  43709. }(BABYLON.TargetCamera));
  43710. BABYLON.FreeCamera = FreeCamera;
  43711. })(BABYLON || (BABYLON = {}));
  43712. //# sourceMappingURL=babylon.freeCamera.js.map
  43713. var BABYLON;
  43714. (function (BABYLON) {
  43715. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  43716. function ArcRotateCameraKeyboardMoveInput() {
  43717. this._keys = new Array();
  43718. this.keysUp = [38];
  43719. this.keysDown = [40];
  43720. this.keysLeft = [37];
  43721. this.keysRight = [39];
  43722. this.keysReset = [220];
  43723. this.panningSensibility = 50.0;
  43724. this.zoomingSensibility = 25.0;
  43725. this.useAltToZoom = true;
  43726. }
  43727. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  43728. var _this = this;
  43729. if (this._onCanvasBlurObserver) {
  43730. return;
  43731. }
  43732. this._scene = this.camera.getScene();
  43733. this._engine = this._scene.getEngine();
  43734. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  43735. _this._keys = [];
  43736. });
  43737. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  43738. var evt = info.event;
  43739. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  43740. _this._ctrlPressed = evt.ctrlKey;
  43741. _this._altPressed = evt.altKey;
  43742. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  43743. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  43744. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  43745. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  43746. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  43747. var index = _this._keys.indexOf(evt.keyCode);
  43748. if (index === -1) {
  43749. _this._keys.push(evt.keyCode);
  43750. }
  43751. if (evt.preventDefault) {
  43752. if (!noPreventDefault) {
  43753. evt.preventDefault();
  43754. }
  43755. }
  43756. }
  43757. }
  43758. else {
  43759. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  43760. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  43761. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  43762. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  43763. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  43764. var index = _this._keys.indexOf(evt.keyCode);
  43765. if (index >= 0) {
  43766. _this._keys.splice(index, 1);
  43767. }
  43768. if (evt.preventDefault) {
  43769. if (!noPreventDefault) {
  43770. evt.preventDefault();
  43771. }
  43772. }
  43773. }
  43774. }
  43775. });
  43776. };
  43777. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  43778. if (this._scene) {
  43779. if (this._onKeyboardObserver) {
  43780. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  43781. }
  43782. if (this._onCanvasBlurObserver) {
  43783. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  43784. }
  43785. this._onKeyboardObserver = null;
  43786. this._onCanvasBlurObserver = null;
  43787. }
  43788. this._keys = [];
  43789. };
  43790. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  43791. if (this._onKeyboardObserver) {
  43792. var camera = this.camera;
  43793. for (var index = 0; index < this._keys.length; index++) {
  43794. var keyCode = this._keys[index];
  43795. if (this.keysLeft.indexOf(keyCode) !== -1) {
  43796. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  43797. camera.inertialPanningX -= 1 / this.panningSensibility;
  43798. }
  43799. else {
  43800. camera.inertialAlphaOffset -= 0.01;
  43801. }
  43802. }
  43803. else if (this.keysUp.indexOf(keyCode) !== -1) {
  43804. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  43805. camera.inertialPanningY += 1 / this.panningSensibility;
  43806. }
  43807. else if (this._altPressed && this.useAltToZoom) {
  43808. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  43809. }
  43810. else {
  43811. camera.inertialBetaOffset -= 0.01;
  43812. }
  43813. }
  43814. else if (this.keysRight.indexOf(keyCode) !== -1) {
  43815. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  43816. camera.inertialPanningX += 1 / this.panningSensibility;
  43817. }
  43818. else {
  43819. camera.inertialAlphaOffset += 0.01;
  43820. }
  43821. }
  43822. else if (this.keysDown.indexOf(keyCode) !== -1) {
  43823. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  43824. camera.inertialPanningY -= 1 / this.panningSensibility;
  43825. }
  43826. else if (this._altPressed && this.useAltToZoom) {
  43827. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  43828. }
  43829. else {
  43830. camera.inertialBetaOffset += 0.01;
  43831. }
  43832. }
  43833. else if (this.keysReset.indexOf(keyCode) !== -1) {
  43834. camera.restoreState();
  43835. }
  43836. }
  43837. }
  43838. };
  43839. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  43840. return "ArcRotateCameraKeyboardMoveInput";
  43841. };
  43842. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  43843. return "keyboard";
  43844. };
  43845. __decorate([
  43846. BABYLON.serialize()
  43847. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  43848. __decorate([
  43849. BABYLON.serialize()
  43850. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  43851. __decorate([
  43852. BABYLON.serialize()
  43853. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  43854. __decorate([
  43855. BABYLON.serialize()
  43856. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  43857. __decorate([
  43858. BABYLON.serialize()
  43859. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  43860. __decorate([
  43861. BABYLON.serialize()
  43862. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  43863. __decorate([
  43864. BABYLON.serialize()
  43865. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  43866. __decorate([
  43867. BABYLON.serialize()
  43868. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  43869. return ArcRotateCameraKeyboardMoveInput;
  43870. }());
  43871. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  43872. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  43873. })(BABYLON || (BABYLON = {}));
  43874. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  43875. var BABYLON;
  43876. (function (BABYLON) {
  43877. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  43878. function ArcRotateCameraMouseWheelInput() {
  43879. this.wheelPrecision = 3.0;
  43880. /**
  43881. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  43882. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  43883. */
  43884. this.wheelDeltaPercentage = 0;
  43885. }
  43886. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  43887. var _this = this;
  43888. this._wheel = function (p, s) {
  43889. //sanity check - this should be a PointerWheel event.
  43890. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  43891. return;
  43892. var event = p.event;
  43893. var delta = 0;
  43894. if (event.wheelDelta) {
  43895. delta = _this.wheelDeltaPercentage ? (event.wheelDelta * 0.01) * _this.camera.radius * _this.wheelDeltaPercentage : event.wheelDelta / (_this.wheelPrecision * 40);
  43896. }
  43897. else if (event.detail) {
  43898. delta = -event.detail / _this.wheelPrecision;
  43899. }
  43900. if (delta)
  43901. _this.camera.inertialRadiusOffset += delta;
  43902. if (event.preventDefault) {
  43903. if (!noPreventDefault) {
  43904. event.preventDefault();
  43905. }
  43906. }
  43907. };
  43908. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  43909. };
  43910. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  43911. if (this._observer && element) {
  43912. this.camera.getScene().onPointerObservable.remove(this._observer);
  43913. this._observer = null;
  43914. this._wheel = null;
  43915. }
  43916. };
  43917. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  43918. return "ArcRotateCameraMouseWheelInput";
  43919. };
  43920. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  43921. return "mousewheel";
  43922. };
  43923. __decorate([
  43924. BABYLON.serialize()
  43925. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  43926. __decorate([
  43927. BABYLON.serialize()
  43928. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  43929. return ArcRotateCameraMouseWheelInput;
  43930. }());
  43931. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  43932. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  43933. })(BABYLON || (BABYLON = {}));
  43934. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  43935. var BABYLON;
  43936. (function (BABYLON) {
  43937. var ArcRotateCameraPointersInput = /** @class */ (function () {
  43938. function ArcRotateCameraPointersInput() {
  43939. this.buttons = [0, 1, 2];
  43940. this.angularSensibilityX = 1000.0;
  43941. this.angularSensibilityY = 1000.0;
  43942. this.pinchPrecision = 12.0;
  43943. /**
  43944. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  43945. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  43946. */
  43947. this.pinchDeltaPercentage = 0;
  43948. this.panningSensibility = 1000.0;
  43949. this.multiTouchPanning = true;
  43950. this.multiTouchPanAndZoom = true;
  43951. this._isPanClick = false;
  43952. this.pinchInwards = true;
  43953. }
  43954. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  43955. var _this = this;
  43956. var engine = this.camera.getEngine();
  43957. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  43958. var pointA = null;
  43959. var pointB = null;
  43960. var previousPinchSquaredDistance = 0;
  43961. var initialDistance = 0;
  43962. var twoFingerActivityCount = 0;
  43963. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  43964. this._pointerInput = function (p, s) {
  43965. var evt = p.event;
  43966. var isTouch = p.event.pointerType === "touch";
  43967. if (engine.isInVRExclusivePointerMode) {
  43968. return;
  43969. }
  43970. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  43971. return;
  43972. }
  43973. var srcElement = (evt.srcElement || evt.target);
  43974. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  43975. try {
  43976. srcElement.setPointerCapture(evt.pointerId);
  43977. }
  43978. catch (e) {
  43979. //Nothing to do with the error. Execution will continue.
  43980. }
  43981. // Manage panning with pan button click
  43982. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  43983. // manage pointers
  43984. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  43985. if (pointA === null) {
  43986. pointA = cacheSoloPointer;
  43987. }
  43988. else if (pointB === null) {
  43989. pointB = cacheSoloPointer;
  43990. }
  43991. if (!noPreventDefault) {
  43992. evt.preventDefault();
  43993. element.focus();
  43994. }
  43995. }
  43996. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  43997. _this.camera.restoreState();
  43998. }
  43999. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  44000. try {
  44001. srcElement.releasePointerCapture(evt.pointerId);
  44002. }
  44003. catch (e) {
  44004. //Nothing to do with the error.
  44005. }
  44006. cacheSoloPointer = null;
  44007. previousPinchSquaredDistance = 0;
  44008. previousMultiTouchPanPosition.isPaning = false;
  44009. previousMultiTouchPanPosition.isPinching = false;
  44010. twoFingerActivityCount = 0;
  44011. initialDistance = 0;
  44012. if (!isTouch) {
  44013. pointB = null; // Mouse and pen are mono pointer
  44014. }
  44015. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  44016. //but emptying completly pointers collection is required to fix a bug on iPhone :
  44017. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  44018. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  44019. if (engine.badOS) {
  44020. pointA = pointB = null;
  44021. }
  44022. else {
  44023. //only remove the impacted pointer in case of multitouch allowing on most
  44024. //platforms switching from rotate to zoom and pan seamlessly.
  44025. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  44026. pointA = pointB;
  44027. pointB = null;
  44028. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  44029. }
  44030. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  44031. pointB = null;
  44032. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  44033. }
  44034. else {
  44035. pointA = pointB = null;
  44036. }
  44037. }
  44038. if (!noPreventDefault) {
  44039. evt.preventDefault();
  44040. }
  44041. }
  44042. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  44043. if (!noPreventDefault) {
  44044. evt.preventDefault();
  44045. }
  44046. // One button down
  44047. if (pointA && pointB === null && cacheSoloPointer) {
  44048. if (_this.panningSensibility !== 0 &&
  44049. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  44050. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  44051. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  44052. }
  44053. else {
  44054. var offsetX = evt.clientX - cacheSoloPointer.x;
  44055. var offsetY = evt.clientY - cacheSoloPointer.y;
  44056. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  44057. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  44058. }
  44059. cacheSoloPointer.x = evt.clientX;
  44060. cacheSoloPointer.y = evt.clientY;
  44061. }
  44062. else if (pointA && pointB) {
  44063. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  44064. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  44065. ed.x = evt.clientX;
  44066. ed.y = evt.clientY;
  44067. var direction = _this.pinchInwards ? 1 : -1;
  44068. var distX = pointA.x - pointB.x;
  44069. var distY = pointA.y - pointB.y;
  44070. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  44071. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  44072. if (previousPinchSquaredDistance === 0) {
  44073. initialDistance = pinchDistance;
  44074. previousPinchSquaredDistance = pinchSquaredDistance;
  44075. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  44076. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  44077. return;
  44078. }
  44079. if (_this.multiTouchPanAndZoom) {
  44080. if (_this.pinchDeltaPercentage) {
  44081. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  44082. }
  44083. else {
  44084. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  44085. (_this.pinchPrecision *
  44086. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  44087. direction);
  44088. }
  44089. if (_this.panningSensibility !== 0) {
  44090. var pointersCenterX = (pointA.x + pointB.x) / 2;
  44091. var pointersCenterY = (pointA.y + pointB.y) / 2;
  44092. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  44093. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  44094. previousMultiTouchPanPosition.x = pointersCenterX;
  44095. previousMultiTouchPanPosition.y = pointersCenterY;
  44096. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  44097. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  44098. }
  44099. }
  44100. else {
  44101. twoFingerActivityCount++;
  44102. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  44103. if (_this.pinchDeltaPercentage) {
  44104. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  44105. }
  44106. else {
  44107. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  44108. (_this.pinchPrecision *
  44109. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  44110. direction);
  44111. }
  44112. previousMultiTouchPanPosition.isPaning = false;
  44113. previousMultiTouchPanPosition.isPinching = true;
  44114. }
  44115. else {
  44116. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  44117. if (!previousMultiTouchPanPosition.isPaning) {
  44118. previousMultiTouchPanPosition.isPaning = true;
  44119. previousMultiTouchPanPosition.isPinching = false;
  44120. previousMultiTouchPanPosition.x = ed.x;
  44121. previousMultiTouchPanPosition.y = ed.y;
  44122. return;
  44123. }
  44124. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  44125. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  44126. }
  44127. }
  44128. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  44129. previousMultiTouchPanPosition.x = ed.x;
  44130. previousMultiTouchPanPosition.y = ed.y;
  44131. }
  44132. }
  44133. previousPinchSquaredDistance = pinchSquaredDistance;
  44134. }
  44135. }
  44136. };
  44137. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  44138. this._onContextMenu = function (evt) {
  44139. evt.preventDefault();
  44140. };
  44141. if (!this.camera._useCtrlForPanning) {
  44142. element.addEventListener("contextmenu", this._onContextMenu, false);
  44143. }
  44144. this._onLostFocus = function () {
  44145. //this._keys = [];
  44146. pointA = pointB = null;
  44147. previousPinchSquaredDistance = 0;
  44148. previousMultiTouchPanPosition.isPaning = false;
  44149. previousMultiTouchPanPosition.isPinching = false;
  44150. twoFingerActivityCount = 0;
  44151. cacheSoloPointer = null;
  44152. initialDistance = 0;
  44153. };
  44154. this._onMouseMove = function (evt) {
  44155. if (!engine.isPointerLock) {
  44156. return;
  44157. }
  44158. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  44159. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  44160. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  44161. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  44162. if (!noPreventDefault) {
  44163. evt.preventDefault();
  44164. }
  44165. };
  44166. this._onGestureStart = function (e) {
  44167. if (window.MSGesture === undefined) {
  44168. return;
  44169. }
  44170. if (!_this._MSGestureHandler) {
  44171. _this._MSGestureHandler = new MSGesture();
  44172. _this._MSGestureHandler.target = element;
  44173. }
  44174. _this._MSGestureHandler.addPointer(e.pointerId);
  44175. };
  44176. this._onGesture = function (e) {
  44177. _this.camera.radius *= e.scale;
  44178. if (e.preventDefault) {
  44179. if (!noPreventDefault) {
  44180. e.stopPropagation();
  44181. e.preventDefault();
  44182. }
  44183. }
  44184. };
  44185. element.addEventListener("mousemove", this._onMouseMove, false);
  44186. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  44187. element.addEventListener("MSGestureChange", this._onGesture, false);
  44188. BABYLON.Tools.RegisterTopRootEvents([
  44189. { name: "blur", handler: this._onLostFocus }
  44190. ]);
  44191. };
  44192. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  44193. if (this._onLostFocus) {
  44194. BABYLON.Tools.UnregisterTopRootEvents([
  44195. { name: "blur", handler: this._onLostFocus }
  44196. ]);
  44197. }
  44198. if (element && this._observer) {
  44199. this.camera.getScene().onPointerObservable.remove(this._observer);
  44200. this._observer = null;
  44201. if (this._onContextMenu) {
  44202. element.removeEventListener("contextmenu", this._onContextMenu);
  44203. }
  44204. if (this._onMouseMove) {
  44205. element.removeEventListener("mousemove", this._onMouseMove);
  44206. }
  44207. if (this._onGestureStart) {
  44208. element.removeEventListener("MSPointerDown", this._onGestureStart);
  44209. }
  44210. if (this._onGesture) {
  44211. element.removeEventListener("MSGestureChange", this._onGesture);
  44212. }
  44213. this._isPanClick = false;
  44214. this.pinchInwards = true;
  44215. this._onMouseMove = null;
  44216. this._onGestureStart = null;
  44217. this._onGesture = null;
  44218. this._MSGestureHandler = null;
  44219. this._onLostFocus = null;
  44220. this._onContextMenu = null;
  44221. }
  44222. };
  44223. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  44224. return "ArcRotateCameraPointersInput";
  44225. };
  44226. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  44227. return "pointers";
  44228. };
  44229. __decorate([
  44230. BABYLON.serialize()
  44231. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  44232. __decorate([
  44233. BABYLON.serialize()
  44234. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  44235. __decorate([
  44236. BABYLON.serialize()
  44237. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  44238. __decorate([
  44239. BABYLON.serialize()
  44240. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  44241. __decorate([
  44242. BABYLON.serialize()
  44243. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  44244. __decorate([
  44245. BABYLON.serialize()
  44246. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  44247. __decorate([
  44248. BABYLON.serialize()
  44249. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  44250. __decorate([
  44251. BABYLON.serialize()
  44252. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  44253. return ArcRotateCameraPointersInput;
  44254. }());
  44255. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  44256. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  44257. })(BABYLON || (BABYLON = {}));
  44258. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  44259. var BABYLON;
  44260. (function (BABYLON) {
  44261. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  44262. __extends(ArcRotateCameraInputsManager, _super);
  44263. function ArcRotateCameraInputsManager(camera) {
  44264. return _super.call(this, camera) || this;
  44265. }
  44266. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  44267. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  44268. return this;
  44269. };
  44270. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  44271. this.add(new BABYLON.ArcRotateCameraPointersInput());
  44272. return this;
  44273. };
  44274. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  44275. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  44276. return this;
  44277. };
  44278. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  44279. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  44280. return this;
  44281. };
  44282. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  44283. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  44284. return this;
  44285. };
  44286. return ArcRotateCameraInputsManager;
  44287. }(BABYLON.CameraInputsManager));
  44288. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  44289. })(BABYLON || (BABYLON = {}));
  44290. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  44291. var BABYLON;
  44292. (function (BABYLON) {
  44293. var ArcRotateCamera = /** @class */ (function (_super) {
  44294. __extends(ArcRotateCamera, _super);
  44295. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  44296. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  44297. _this.inertialAlphaOffset = 0;
  44298. _this.inertialBetaOffset = 0;
  44299. _this.inertialRadiusOffset = 0;
  44300. _this.lowerAlphaLimit = null;
  44301. _this.upperAlphaLimit = null;
  44302. _this.lowerBetaLimit = 0.01;
  44303. _this.upperBetaLimit = Math.PI;
  44304. _this.lowerRadiusLimit = null;
  44305. _this.upperRadiusLimit = null;
  44306. _this.inertialPanningX = 0;
  44307. _this.inertialPanningY = 0;
  44308. _this.pinchToPanMaxDistance = 20;
  44309. _this.panningDistanceLimit = null;
  44310. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  44311. _this.panningInertia = 0.9;
  44312. //-- end properties for backward compatibility for inputs
  44313. _this.zoomOnFactor = 1;
  44314. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  44315. _this.allowUpsideDown = true;
  44316. _this._viewMatrix = new BABYLON.Matrix();
  44317. // Panning
  44318. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  44319. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  44320. _this.checkCollisions = false;
  44321. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  44322. _this._previousPosition = BABYLON.Vector3.Zero();
  44323. _this._collisionVelocity = BABYLON.Vector3.Zero();
  44324. _this._newPosition = BABYLON.Vector3.Zero();
  44325. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  44326. if (collidedMesh === void 0) { collidedMesh = null; }
  44327. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  44328. newPosition.multiplyInPlace(_this._collider._radius);
  44329. }
  44330. if (!collidedMesh) {
  44331. _this._previousPosition.copyFrom(_this.position);
  44332. }
  44333. else {
  44334. _this.setPosition(newPosition);
  44335. if (_this.onCollide) {
  44336. _this.onCollide(collidedMesh);
  44337. }
  44338. }
  44339. // Recompute because of constraints
  44340. var cosa = Math.cos(_this.alpha);
  44341. var sina = Math.sin(_this.alpha);
  44342. var cosb = Math.cos(_this.beta);
  44343. var sinb = Math.sin(_this.beta);
  44344. if (sinb === 0) {
  44345. sinb = 0.0001;
  44346. }
  44347. var target = _this._getTargetPosition();
  44348. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  44349. _this.position.copyFrom(_this._newPosition);
  44350. var up = _this.upVector;
  44351. if (_this.allowUpsideDown && _this.beta < 0) {
  44352. up = up.clone();
  44353. up = up.negate();
  44354. }
  44355. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  44356. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  44357. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  44358. _this._collisionTriggered = false;
  44359. };
  44360. _this._target = BABYLON.Vector3.Zero();
  44361. if (target) {
  44362. _this.setTarget(target);
  44363. }
  44364. _this.alpha = alpha;
  44365. _this.beta = beta;
  44366. _this.radius = radius;
  44367. _this.getViewMatrix();
  44368. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  44369. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  44370. return _this;
  44371. }
  44372. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  44373. get: function () {
  44374. return this._target;
  44375. },
  44376. set: function (value) {
  44377. this.setTarget(value);
  44378. },
  44379. enumerable: true,
  44380. configurable: true
  44381. });
  44382. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  44383. //-- begin properties for backward compatibility for inputs
  44384. get: function () {
  44385. var pointers = this.inputs.attached["pointers"];
  44386. if (pointers)
  44387. return pointers.angularSensibilityX;
  44388. return 0;
  44389. },
  44390. set: function (value) {
  44391. var pointers = this.inputs.attached["pointers"];
  44392. if (pointers) {
  44393. pointers.angularSensibilityX = value;
  44394. }
  44395. },
  44396. enumerable: true,
  44397. configurable: true
  44398. });
  44399. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  44400. get: function () {
  44401. var pointers = this.inputs.attached["pointers"];
  44402. if (pointers)
  44403. return pointers.angularSensibilityY;
  44404. return 0;
  44405. },
  44406. set: function (value) {
  44407. var pointers = this.inputs.attached["pointers"];
  44408. if (pointers) {
  44409. pointers.angularSensibilityY = value;
  44410. }
  44411. },
  44412. enumerable: true,
  44413. configurable: true
  44414. });
  44415. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  44416. get: function () {
  44417. var pointers = this.inputs.attached["pointers"];
  44418. if (pointers)
  44419. return pointers.pinchPrecision;
  44420. return 0;
  44421. },
  44422. set: function (value) {
  44423. var pointers = this.inputs.attached["pointers"];
  44424. if (pointers) {
  44425. pointers.pinchPrecision = value;
  44426. }
  44427. },
  44428. enumerable: true,
  44429. configurable: true
  44430. });
  44431. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  44432. get: function () {
  44433. var pointers = this.inputs.attached["pointers"];
  44434. if (pointers)
  44435. return pointers.pinchDeltaPercentage;
  44436. return 0;
  44437. },
  44438. set: function (value) {
  44439. var pointers = this.inputs.attached["pointers"];
  44440. if (pointers) {
  44441. pointers.pinchDeltaPercentage = value;
  44442. }
  44443. },
  44444. enumerable: true,
  44445. configurable: true
  44446. });
  44447. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  44448. get: function () {
  44449. var pointers = this.inputs.attached["pointers"];
  44450. if (pointers)
  44451. return pointers.panningSensibility;
  44452. return 0;
  44453. },
  44454. set: function (value) {
  44455. var pointers = this.inputs.attached["pointers"];
  44456. if (pointers) {
  44457. pointers.panningSensibility = value;
  44458. }
  44459. },
  44460. enumerable: true,
  44461. configurable: true
  44462. });
  44463. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  44464. get: function () {
  44465. var keyboard = this.inputs.attached["keyboard"];
  44466. if (keyboard)
  44467. return keyboard.keysUp;
  44468. return [];
  44469. },
  44470. set: function (value) {
  44471. var keyboard = this.inputs.attached["keyboard"];
  44472. if (keyboard)
  44473. keyboard.keysUp = value;
  44474. },
  44475. enumerable: true,
  44476. configurable: true
  44477. });
  44478. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  44479. get: function () {
  44480. var keyboard = this.inputs.attached["keyboard"];
  44481. if (keyboard)
  44482. return keyboard.keysDown;
  44483. return [];
  44484. },
  44485. set: function (value) {
  44486. var keyboard = this.inputs.attached["keyboard"];
  44487. if (keyboard)
  44488. keyboard.keysDown = value;
  44489. },
  44490. enumerable: true,
  44491. configurable: true
  44492. });
  44493. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  44494. get: function () {
  44495. var keyboard = this.inputs.attached["keyboard"];
  44496. if (keyboard)
  44497. return keyboard.keysLeft;
  44498. return [];
  44499. },
  44500. set: function (value) {
  44501. var keyboard = this.inputs.attached["keyboard"];
  44502. if (keyboard)
  44503. keyboard.keysLeft = value;
  44504. },
  44505. enumerable: true,
  44506. configurable: true
  44507. });
  44508. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  44509. get: function () {
  44510. var keyboard = this.inputs.attached["keyboard"];
  44511. if (keyboard)
  44512. return keyboard.keysRight;
  44513. return [];
  44514. },
  44515. set: function (value) {
  44516. var keyboard = this.inputs.attached["keyboard"];
  44517. if (keyboard)
  44518. keyboard.keysRight = value;
  44519. },
  44520. enumerable: true,
  44521. configurable: true
  44522. });
  44523. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  44524. get: function () {
  44525. var mousewheel = this.inputs.attached["mousewheel"];
  44526. if (mousewheel)
  44527. return mousewheel.wheelPrecision;
  44528. return 0;
  44529. },
  44530. set: function (value) {
  44531. var mousewheel = this.inputs.attached["mousewheel"];
  44532. if (mousewheel)
  44533. mousewheel.wheelPrecision = value;
  44534. },
  44535. enumerable: true,
  44536. configurable: true
  44537. });
  44538. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  44539. get: function () {
  44540. var mousewheel = this.inputs.attached["mousewheel"];
  44541. if (mousewheel)
  44542. return mousewheel.wheelDeltaPercentage;
  44543. return 0;
  44544. },
  44545. set: function (value) {
  44546. var mousewheel = this.inputs.attached["mousewheel"];
  44547. if (mousewheel)
  44548. mousewheel.wheelDeltaPercentage = value;
  44549. },
  44550. enumerable: true,
  44551. configurable: true
  44552. });
  44553. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  44554. get: function () {
  44555. return this._bouncingBehavior;
  44556. },
  44557. enumerable: true,
  44558. configurable: true
  44559. });
  44560. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  44561. get: function () {
  44562. return this._bouncingBehavior != null;
  44563. },
  44564. set: function (value) {
  44565. if (value === this.useBouncingBehavior) {
  44566. return;
  44567. }
  44568. if (value) {
  44569. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  44570. this.addBehavior(this._bouncingBehavior);
  44571. }
  44572. else if (this._bouncingBehavior) {
  44573. this.removeBehavior(this._bouncingBehavior);
  44574. this._bouncingBehavior = null;
  44575. }
  44576. },
  44577. enumerable: true,
  44578. configurable: true
  44579. });
  44580. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  44581. get: function () {
  44582. return this._framingBehavior;
  44583. },
  44584. enumerable: true,
  44585. configurable: true
  44586. });
  44587. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  44588. get: function () {
  44589. return this._framingBehavior != null;
  44590. },
  44591. set: function (value) {
  44592. if (value === this.useFramingBehavior) {
  44593. return;
  44594. }
  44595. if (value) {
  44596. this._framingBehavior = new BABYLON.FramingBehavior();
  44597. this.addBehavior(this._framingBehavior);
  44598. }
  44599. else if (this._framingBehavior) {
  44600. this.removeBehavior(this._framingBehavior);
  44601. this._framingBehavior = null;
  44602. }
  44603. },
  44604. enumerable: true,
  44605. configurable: true
  44606. });
  44607. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  44608. get: function () {
  44609. return this._autoRotationBehavior;
  44610. },
  44611. enumerable: true,
  44612. configurable: true
  44613. });
  44614. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  44615. get: function () {
  44616. return this._autoRotationBehavior != null;
  44617. },
  44618. set: function (value) {
  44619. if (value === this.useAutoRotationBehavior) {
  44620. return;
  44621. }
  44622. if (value) {
  44623. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  44624. this.addBehavior(this._autoRotationBehavior);
  44625. }
  44626. else if (this._autoRotationBehavior) {
  44627. this.removeBehavior(this._autoRotationBehavior);
  44628. this._autoRotationBehavior = null;
  44629. }
  44630. },
  44631. enumerable: true,
  44632. configurable: true
  44633. });
  44634. // Cache
  44635. ArcRotateCamera.prototype._initCache = function () {
  44636. _super.prototype._initCache.call(this);
  44637. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  44638. this._cache.alpha = undefined;
  44639. this._cache.beta = undefined;
  44640. this._cache.radius = undefined;
  44641. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  44642. };
  44643. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  44644. if (!ignoreParentClass) {
  44645. _super.prototype._updateCache.call(this);
  44646. }
  44647. this._cache._target.copyFrom(this._getTargetPosition());
  44648. this._cache.alpha = this.alpha;
  44649. this._cache.beta = this.beta;
  44650. this._cache.radius = this.radius;
  44651. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  44652. };
  44653. ArcRotateCamera.prototype._getTargetPosition = function () {
  44654. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  44655. var pos = this._targetHost.getAbsolutePosition();
  44656. if (this._targetBoundingCenter) {
  44657. pos.addToRef(this._targetBoundingCenter, this._target);
  44658. }
  44659. else {
  44660. this._target.copyFrom(pos);
  44661. }
  44662. }
  44663. var lockedTargetPosition = this._getLockedTargetPosition();
  44664. if (lockedTargetPosition) {
  44665. return lockedTargetPosition;
  44666. }
  44667. return this._target;
  44668. };
  44669. ArcRotateCamera.prototype.storeState = function () {
  44670. this._storedAlpha = this.alpha;
  44671. this._storedBeta = this.beta;
  44672. this._storedRadius = this.radius;
  44673. this._storedTarget = this._getTargetPosition().clone();
  44674. return _super.prototype.storeState.call(this);
  44675. };
  44676. /**
  44677. * Restored camera state. You must call storeState() first
  44678. */
  44679. ArcRotateCamera.prototype._restoreStateValues = function () {
  44680. if (!_super.prototype._restoreStateValues.call(this)) {
  44681. return false;
  44682. }
  44683. this.alpha = this._storedAlpha;
  44684. this.beta = this._storedBeta;
  44685. this.radius = this._storedRadius;
  44686. this.setTarget(this._storedTarget.clone());
  44687. this.inertialAlphaOffset = 0;
  44688. this.inertialBetaOffset = 0;
  44689. this.inertialRadiusOffset = 0;
  44690. this.inertialPanningX = 0;
  44691. this.inertialPanningY = 0;
  44692. return true;
  44693. };
  44694. // Synchronized
  44695. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  44696. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  44697. return false;
  44698. return this._cache._target.equals(this._getTargetPosition())
  44699. && this._cache.alpha === this.alpha
  44700. && this._cache.beta === this.beta
  44701. && this._cache.radius === this.radius
  44702. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  44703. };
  44704. // Methods
  44705. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  44706. var _this = this;
  44707. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  44708. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  44709. this._useCtrlForPanning = useCtrlForPanning;
  44710. this._panningMouseButton = panningMouseButton;
  44711. this.inputs.attachElement(element, noPreventDefault);
  44712. this._reset = function () {
  44713. _this.inertialAlphaOffset = 0;
  44714. _this.inertialBetaOffset = 0;
  44715. _this.inertialRadiusOffset = 0;
  44716. _this.inertialPanningX = 0;
  44717. _this.inertialPanningY = 0;
  44718. };
  44719. };
  44720. ArcRotateCamera.prototype.detachControl = function (element) {
  44721. this.inputs.detachElement(element);
  44722. if (this._reset) {
  44723. this._reset();
  44724. }
  44725. };
  44726. ArcRotateCamera.prototype._checkInputs = function () {
  44727. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  44728. if (this._collisionTriggered) {
  44729. return;
  44730. }
  44731. this.inputs.checkInputs();
  44732. // Inertia
  44733. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  44734. if (this.getScene().useRightHandedSystem) {
  44735. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  44736. }
  44737. else {
  44738. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  44739. }
  44740. this.beta += this.inertialBetaOffset;
  44741. this.radius -= this.inertialRadiusOffset;
  44742. this.inertialAlphaOffset *= this.inertia;
  44743. this.inertialBetaOffset *= this.inertia;
  44744. this.inertialRadiusOffset *= this.inertia;
  44745. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  44746. this.inertialAlphaOffset = 0;
  44747. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  44748. this.inertialBetaOffset = 0;
  44749. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  44750. this.inertialRadiusOffset = 0;
  44751. }
  44752. // Panning inertia
  44753. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  44754. if (!this._localDirection) {
  44755. this._localDirection = BABYLON.Vector3.Zero();
  44756. this._transformedDirection = BABYLON.Vector3.Zero();
  44757. }
  44758. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  44759. this._localDirection.multiplyInPlace(this.panningAxis);
  44760. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  44761. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  44762. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  44763. if (!this.panningAxis.y) {
  44764. this._transformedDirection.y = 0;
  44765. }
  44766. if (!this._targetHost) {
  44767. if (this.panningDistanceLimit) {
  44768. this._transformedDirection.addInPlace(this._target);
  44769. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  44770. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  44771. this._target.copyFrom(this._transformedDirection);
  44772. }
  44773. }
  44774. else {
  44775. this._target.addInPlace(this._transformedDirection);
  44776. }
  44777. }
  44778. this.inertialPanningX *= this.panningInertia;
  44779. this.inertialPanningY *= this.panningInertia;
  44780. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  44781. this.inertialPanningX = 0;
  44782. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  44783. this.inertialPanningY = 0;
  44784. }
  44785. // Limits
  44786. this._checkLimits();
  44787. _super.prototype._checkInputs.call(this);
  44788. };
  44789. ArcRotateCamera.prototype._checkLimits = function () {
  44790. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  44791. if (this.allowUpsideDown && this.beta > Math.PI) {
  44792. this.beta = this.beta - (2 * Math.PI);
  44793. }
  44794. }
  44795. else {
  44796. if (this.beta < this.lowerBetaLimit) {
  44797. this.beta = this.lowerBetaLimit;
  44798. }
  44799. }
  44800. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  44801. if (this.allowUpsideDown && this.beta < -Math.PI) {
  44802. this.beta = this.beta + (2 * Math.PI);
  44803. }
  44804. }
  44805. else {
  44806. if (this.beta > this.upperBetaLimit) {
  44807. this.beta = this.upperBetaLimit;
  44808. }
  44809. }
  44810. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  44811. this.alpha = this.lowerAlphaLimit;
  44812. }
  44813. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  44814. this.alpha = this.upperAlphaLimit;
  44815. }
  44816. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  44817. this.radius = this.lowerRadiusLimit;
  44818. }
  44819. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  44820. this.radius = this.upperRadiusLimit;
  44821. }
  44822. };
  44823. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  44824. var radiusv3 = this.position.subtract(this._getTargetPosition());
  44825. this.radius = radiusv3.length();
  44826. if (this.radius === 0) {
  44827. this.radius = 0.0001; // Just to avoid division by zero
  44828. }
  44829. // Alpha
  44830. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  44831. if (radiusv3.z < 0) {
  44832. this.alpha = 2 * Math.PI - this.alpha;
  44833. }
  44834. // Beta
  44835. this.beta = Math.acos(radiusv3.y / this.radius);
  44836. this._checkLimits();
  44837. };
  44838. ArcRotateCamera.prototype.setPosition = function (position) {
  44839. if (this.position.equals(position)) {
  44840. return;
  44841. }
  44842. this.position.copyFrom(position);
  44843. this.rebuildAnglesAndRadius();
  44844. };
  44845. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  44846. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  44847. if (allowSamePosition === void 0) { allowSamePosition = false; }
  44848. if (target.getBoundingInfo) {
  44849. if (toBoundingCenter) {
  44850. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  44851. }
  44852. else {
  44853. this._targetBoundingCenter = null;
  44854. }
  44855. this._targetHost = target;
  44856. this._target = this._getTargetPosition();
  44857. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  44858. }
  44859. else {
  44860. var newTarget = target;
  44861. var currentTarget = this._getTargetPosition();
  44862. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  44863. return;
  44864. }
  44865. this._targetHost = null;
  44866. this._target = newTarget;
  44867. this._targetBoundingCenter = null;
  44868. this.onMeshTargetChangedObservable.notifyObservers(null);
  44869. }
  44870. this.rebuildAnglesAndRadius();
  44871. };
  44872. ArcRotateCamera.prototype._getViewMatrix = function () {
  44873. // Compute
  44874. var cosa = Math.cos(this.alpha);
  44875. var sina = Math.sin(this.alpha);
  44876. var cosb = Math.cos(this.beta);
  44877. var sinb = Math.sin(this.beta);
  44878. if (sinb === 0) {
  44879. sinb = 0.0001;
  44880. }
  44881. var target = this._getTargetPosition();
  44882. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  44883. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  44884. if (!this._collider) {
  44885. this._collider = new BABYLON.Collider();
  44886. }
  44887. this._collider._radius = this.collisionRadius;
  44888. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  44889. this._collisionTriggered = true;
  44890. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  44891. }
  44892. else {
  44893. this.position.copyFrom(this._newPosition);
  44894. var up = this.upVector;
  44895. if (this.allowUpsideDown && sinb < 0) {
  44896. up = up.clone();
  44897. up = up.negate();
  44898. }
  44899. if (this.getScene().useRightHandedSystem) {
  44900. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  44901. }
  44902. else {
  44903. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  44904. }
  44905. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  44906. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  44907. }
  44908. this._currentTarget = target;
  44909. return this._viewMatrix;
  44910. };
  44911. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  44912. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  44913. meshes = meshes || this.getScene().meshes;
  44914. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  44915. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  44916. this.radius = distance * this.zoomOnFactor;
  44917. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  44918. };
  44919. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  44920. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  44921. var meshesOrMinMaxVector;
  44922. var distance;
  44923. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  44924. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  44925. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  44926. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  44927. }
  44928. else {
  44929. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  44930. meshesOrMinMaxVector = minMaxVectorAndDistance;
  44931. distance = minMaxVectorAndDistance.distance;
  44932. }
  44933. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  44934. if (!doNotUpdateMaxZ) {
  44935. this.maxZ = distance * 2;
  44936. }
  44937. };
  44938. /**
  44939. * @override
  44940. * Override Camera.createRigCamera
  44941. */
  44942. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  44943. var alphaShift = 0;
  44944. switch (this.cameraRigMode) {
  44945. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  44946. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  44947. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  44948. case BABYLON.Camera.RIG_MODE_VR:
  44949. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  44950. break;
  44951. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  44952. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  44953. break;
  44954. }
  44955. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  44956. rigCam._cameraRigParams = {};
  44957. return rigCam;
  44958. };
  44959. /**
  44960. * @override
  44961. * Override Camera._updateRigCameras
  44962. */
  44963. ArcRotateCamera.prototype._updateRigCameras = function () {
  44964. var camLeft = this._rigCameras[0];
  44965. var camRight = this._rigCameras[1];
  44966. camLeft.beta = camRight.beta = this.beta;
  44967. camLeft.radius = camRight.radius = this.radius;
  44968. switch (this.cameraRigMode) {
  44969. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  44970. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  44971. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  44972. case BABYLON.Camera.RIG_MODE_VR:
  44973. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  44974. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  44975. break;
  44976. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  44977. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  44978. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  44979. break;
  44980. }
  44981. _super.prototype._updateRigCameras.call(this);
  44982. };
  44983. ArcRotateCamera.prototype.dispose = function () {
  44984. this.inputs.clear();
  44985. _super.prototype.dispose.call(this);
  44986. };
  44987. ArcRotateCamera.prototype.getClassName = function () {
  44988. return "ArcRotateCamera";
  44989. };
  44990. __decorate([
  44991. BABYLON.serialize()
  44992. ], ArcRotateCamera.prototype, "alpha", void 0);
  44993. __decorate([
  44994. BABYLON.serialize()
  44995. ], ArcRotateCamera.prototype, "beta", void 0);
  44996. __decorate([
  44997. BABYLON.serialize()
  44998. ], ArcRotateCamera.prototype, "radius", void 0);
  44999. __decorate([
  45000. BABYLON.serializeAsVector3("target")
  45001. ], ArcRotateCamera.prototype, "_target", void 0);
  45002. __decorate([
  45003. BABYLON.serialize()
  45004. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  45005. __decorate([
  45006. BABYLON.serialize()
  45007. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  45008. __decorate([
  45009. BABYLON.serialize()
  45010. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  45011. __decorate([
  45012. BABYLON.serialize()
  45013. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  45014. __decorate([
  45015. BABYLON.serialize()
  45016. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  45017. __decorate([
  45018. BABYLON.serialize()
  45019. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  45020. __decorate([
  45021. BABYLON.serialize()
  45022. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  45023. __decorate([
  45024. BABYLON.serialize()
  45025. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  45026. __decorate([
  45027. BABYLON.serialize()
  45028. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  45029. __decorate([
  45030. BABYLON.serialize()
  45031. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  45032. __decorate([
  45033. BABYLON.serialize()
  45034. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  45035. __decorate([
  45036. BABYLON.serialize()
  45037. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  45038. __decorate([
  45039. BABYLON.serialize()
  45040. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  45041. __decorate([
  45042. BABYLON.serializeAsVector3()
  45043. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  45044. __decorate([
  45045. BABYLON.serialize()
  45046. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  45047. __decorate([
  45048. BABYLON.serialize()
  45049. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  45050. __decorate([
  45051. BABYLON.serialize()
  45052. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  45053. return ArcRotateCamera;
  45054. }(BABYLON.TargetCamera));
  45055. BABYLON.ArcRotateCamera = ArcRotateCamera;
  45056. })(BABYLON || (BABYLON = {}));
  45057. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  45058. var BABYLON;
  45059. (function (BABYLON) {
  45060. /**
  45061. * The HemisphericLight simulates the ambient environment light,
  45062. * so the passed direction is the light reflection direction, not the incoming direction.
  45063. */
  45064. var HemisphericLight = /** @class */ (function (_super) {
  45065. __extends(HemisphericLight, _super);
  45066. /**
  45067. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  45068. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  45069. * The HemisphericLight can't cast shadows.
  45070. * Documentation : http://doc.babylonjs.com/tutorials/lights
  45071. * @param name The friendly name of the light
  45072. * @param direction The direction of the light reflection
  45073. * @param scene The scene the light belongs to
  45074. */
  45075. function HemisphericLight(name, direction, scene) {
  45076. var _this = _super.call(this, name, scene) || this;
  45077. /**
  45078. * The groundColor is the light in the opposite direction to the one specified during creation.
  45079. * You can think of the diffuse and specular light as coming from the centre of the object in the given direction and the groundColor light in the opposite direction.
  45080. */
  45081. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  45082. _this.direction = direction || BABYLON.Vector3.Up();
  45083. return _this;
  45084. }
  45085. HemisphericLight.prototype._buildUniformLayout = function () {
  45086. this._uniformBuffer.addUniform("vLightData", 4);
  45087. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  45088. this._uniformBuffer.addUniform("vLightSpecular", 3);
  45089. this._uniformBuffer.addUniform("vLightGround", 3);
  45090. this._uniformBuffer.addUniform("shadowsInfo", 3);
  45091. this._uniformBuffer.addUniform("depthValues", 2);
  45092. this._uniformBuffer.create();
  45093. };
  45094. /**
  45095. * Returns the string "HemisphericLight".
  45096. * @return The class name
  45097. */
  45098. HemisphericLight.prototype.getClassName = function () {
  45099. return "HemisphericLight";
  45100. };
  45101. /**
  45102. * Sets the HemisphericLight direction towards the passed target (Vector3).
  45103. * Returns the updated direction.
  45104. * @param target The target the direction should point to
  45105. * @return The computed direction
  45106. */
  45107. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  45108. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  45109. return this.direction;
  45110. };
  45111. /**
  45112. * Returns the shadow generator associated to the light.
  45113. * @returns Always null for hemispheric lights because it does not support shadows.
  45114. */
  45115. HemisphericLight.prototype.getShadowGenerator = function () {
  45116. return null;
  45117. };
  45118. /**
  45119. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  45120. * @param effect The effect to update
  45121. * @param lightIndex The index of the light in the effect to update
  45122. * @returns The hemispheric light
  45123. */
  45124. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  45125. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  45126. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  45127. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  45128. return this;
  45129. };
  45130. /**
  45131. * @ignore internal use only.
  45132. */
  45133. HemisphericLight.prototype._getWorldMatrix = function () {
  45134. if (!this._worldMatrix) {
  45135. this._worldMatrix = BABYLON.Matrix.Identity();
  45136. }
  45137. return this._worldMatrix;
  45138. };
  45139. /**
  45140. * Returns the integer 3.
  45141. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  45142. */
  45143. HemisphericLight.prototype.getTypeID = function () {
  45144. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  45145. };
  45146. __decorate([
  45147. BABYLON.serializeAsColor3()
  45148. ], HemisphericLight.prototype, "groundColor", void 0);
  45149. __decorate([
  45150. BABYLON.serializeAsVector3()
  45151. ], HemisphericLight.prototype, "direction", void 0);
  45152. return HemisphericLight;
  45153. }(BABYLON.Light));
  45154. BABYLON.HemisphericLight = HemisphericLight;
  45155. })(BABYLON || (BABYLON = {}));
  45156. //# sourceMappingURL=babylon.hemisphericLight.js.map
  45157. var BABYLON;
  45158. (function (BABYLON) {
  45159. /**
  45160. * Base implementation of @see IShadowLight
  45161. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  45162. */
  45163. var ShadowLight = /** @class */ (function (_super) {
  45164. __extends(ShadowLight, _super);
  45165. function ShadowLight() {
  45166. var _this = _super !== null && _super.apply(this, arguments) || this;
  45167. _this._needProjectionMatrixCompute = true;
  45168. return _this;
  45169. }
  45170. ShadowLight.prototype._setPosition = function (value) {
  45171. this._position = value;
  45172. };
  45173. Object.defineProperty(ShadowLight.prototype, "position", {
  45174. /**
  45175. * Sets the position the shadow will be casted from. Also use as the light position for both
  45176. * point and spot lights.
  45177. */
  45178. get: function () {
  45179. return this._position;
  45180. },
  45181. /**
  45182. * Sets the position the shadow will be casted from. Also use as the light position for both
  45183. * point and spot lights.
  45184. */
  45185. set: function (value) {
  45186. this._setPosition(value);
  45187. },
  45188. enumerable: true,
  45189. configurable: true
  45190. });
  45191. ShadowLight.prototype._setDirection = function (value) {
  45192. this._direction = value;
  45193. };
  45194. Object.defineProperty(ShadowLight.prototype, "direction", {
  45195. /**
  45196. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  45197. * Also use as the light direction on spot and directional lights.
  45198. */
  45199. get: function () {
  45200. return this._direction;
  45201. },
  45202. /**
  45203. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  45204. * Also use as the light direction on spot and directional lights.
  45205. */
  45206. set: function (value) {
  45207. this._setDirection(value);
  45208. },
  45209. enumerable: true,
  45210. configurable: true
  45211. });
  45212. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  45213. /**
  45214. * Gets the shadow projection clipping minimum z value.
  45215. */
  45216. get: function () {
  45217. return this._shadowMinZ;
  45218. },
  45219. /**
  45220. * Sets the shadow projection clipping minimum z value.
  45221. */
  45222. set: function (value) {
  45223. this._shadowMinZ = value;
  45224. this.forceProjectionMatrixCompute();
  45225. },
  45226. enumerable: true,
  45227. configurable: true
  45228. });
  45229. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  45230. /**
  45231. * Sets the shadow projection clipping maximum z value.
  45232. */
  45233. get: function () {
  45234. return this._shadowMaxZ;
  45235. },
  45236. /**
  45237. * Gets the shadow projection clipping maximum z value.
  45238. */
  45239. set: function (value) {
  45240. this._shadowMaxZ = value;
  45241. this.forceProjectionMatrixCompute();
  45242. },
  45243. enumerable: true,
  45244. configurable: true
  45245. });
  45246. /**
  45247. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  45248. * @returns true if the information has been computed, false if it does not need to (no parenting)
  45249. */
  45250. ShadowLight.prototype.computeTransformedInformation = function () {
  45251. if (this.parent && this.parent.getWorldMatrix) {
  45252. if (!this.transformedPosition) {
  45253. this.transformedPosition = BABYLON.Vector3.Zero();
  45254. }
  45255. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  45256. // In case the direction is present.
  45257. if (this.direction) {
  45258. if (!this.transformedDirection) {
  45259. this.transformedDirection = BABYLON.Vector3.Zero();
  45260. }
  45261. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  45262. }
  45263. return true;
  45264. }
  45265. return false;
  45266. };
  45267. /**
  45268. * Return the depth scale used for the shadow map.
  45269. * @returns the depth scale.
  45270. */
  45271. ShadowLight.prototype.getDepthScale = function () {
  45272. return 50.0;
  45273. };
  45274. /**
  45275. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  45276. * @param faceIndex The index of the face we are computed the direction to generate shadow
  45277. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  45278. */
  45279. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  45280. return this.transformedDirection ? this.transformedDirection : this.direction;
  45281. };
  45282. /**
  45283. * Returns the ShadowLight absolute position in the World.
  45284. * @returns the position vector in world space
  45285. */
  45286. ShadowLight.prototype.getAbsolutePosition = function () {
  45287. return this.transformedPosition ? this.transformedPosition : this.position;
  45288. };
  45289. /**
  45290. * Sets the ShadowLight direction toward the passed target.
  45291. * @param target The point tot target in local space
  45292. * @returns the updated ShadowLight direction
  45293. */
  45294. ShadowLight.prototype.setDirectionToTarget = function (target) {
  45295. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  45296. return this.direction;
  45297. };
  45298. /**
  45299. * Returns the light rotation in euler definition.
  45300. * @returns the x y z rotation in local space.
  45301. */
  45302. ShadowLight.prototype.getRotation = function () {
  45303. this.direction.normalize();
  45304. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  45305. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  45306. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  45307. };
  45308. /**
  45309. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  45310. * @returns true if a cube texture needs to be use
  45311. */
  45312. ShadowLight.prototype.needCube = function () {
  45313. return false;
  45314. };
  45315. /**
  45316. * Detects if the projection matrix requires to be recomputed this frame.
  45317. * @returns true if it requires to be recomputed otherwise, false.
  45318. */
  45319. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  45320. return this._needProjectionMatrixCompute;
  45321. };
  45322. /**
  45323. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  45324. */
  45325. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  45326. this._needProjectionMatrixCompute = true;
  45327. };
  45328. /**
  45329. * Get the world matrix of the sahdow lights.
  45330. * @ignore Internal Use Only
  45331. */
  45332. ShadowLight.prototype._getWorldMatrix = function () {
  45333. if (!this._worldMatrix) {
  45334. this._worldMatrix = BABYLON.Matrix.Identity();
  45335. }
  45336. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  45337. return this._worldMatrix;
  45338. };
  45339. /**
  45340. * Gets the minZ used for shadow according to both the scene and the light.
  45341. * @param activeCamera The camera we are returning the min for
  45342. * @returns the depth min z
  45343. */
  45344. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  45345. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  45346. };
  45347. /**
  45348. * Gets the maxZ used for shadow according to both the scene and the light.
  45349. * @param activeCamera The camera we are returning the max for
  45350. * @returns the depth max z
  45351. */
  45352. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  45353. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  45354. };
  45355. /**
  45356. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  45357. * @param matrix The materix to updated with the projection information
  45358. * @param viewMatrix The transform matrix of the light
  45359. * @param renderList The list of mesh to render in the map
  45360. * @returns The current light
  45361. */
  45362. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  45363. if (this.customProjectionMatrixBuilder) {
  45364. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  45365. }
  45366. else {
  45367. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  45368. }
  45369. return this;
  45370. };
  45371. __decorate([
  45372. BABYLON.serializeAsVector3()
  45373. ], ShadowLight.prototype, "position", null);
  45374. __decorate([
  45375. BABYLON.serializeAsVector3()
  45376. ], ShadowLight.prototype, "direction", null);
  45377. __decorate([
  45378. BABYLON.serialize()
  45379. ], ShadowLight.prototype, "shadowMinZ", null);
  45380. __decorate([
  45381. BABYLON.serialize()
  45382. ], ShadowLight.prototype, "shadowMaxZ", null);
  45383. return ShadowLight;
  45384. }(BABYLON.Light));
  45385. BABYLON.ShadowLight = ShadowLight;
  45386. })(BABYLON || (BABYLON = {}));
  45387. //# sourceMappingURL=babylon.shadowLight.js.map
  45388. var BABYLON;
  45389. (function (BABYLON) {
  45390. /**
  45391. * A point light is a light defined by an unique point in world space.
  45392. * The light is emitted in every direction from this point.
  45393. * A good example of a point light is a standard light bulb.
  45394. * Documentation: https://doc.babylonjs.com/babylon101/lights
  45395. */
  45396. var PointLight = /** @class */ (function (_super) {
  45397. __extends(PointLight, _super);
  45398. /**
  45399. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  45400. * A PointLight emits the light in every direction.
  45401. * It can cast shadows.
  45402. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  45403. * ```javascript
  45404. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  45405. * ```
  45406. * Documentation : http://doc.babylonjs.com/tutorials/lights
  45407. * @param name The light friendly name
  45408. * @param position The position of the point light in the scene
  45409. * @param scene The scene the lights belongs to
  45410. */
  45411. function PointLight(name, position, scene) {
  45412. var _this = _super.call(this, name, scene) || this;
  45413. _this._shadowAngle = Math.PI / 2;
  45414. _this.position = position;
  45415. return _this;
  45416. }
  45417. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  45418. /**
  45419. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  45420. * This specifies what angle the shadow will use to be created.
  45421. *
  45422. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  45423. */
  45424. get: function () {
  45425. return this._shadowAngle;
  45426. },
  45427. /**
  45428. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  45429. * This specifies what angle the shadow will use to be created.
  45430. *
  45431. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  45432. */
  45433. set: function (value) {
  45434. this._shadowAngle = value;
  45435. this.forceProjectionMatrixCompute();
  45436. },
  45437. enumerable: true,
  45438. configurable: true
  45439. });
  45440. Object.defineProperty(PointLight.prototype, "direction", {
  45441. /**
  45442. * Gets the direction if it has been set.
  45443. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  45444. */
  45445. get: function () {
  45446. return this._direction;
  45447. },
  45448. /**
  45449. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  45450. */
  45451. set: function (value) {
  45452. var previousNeedCube = this.needCube();
  45453. this._direction = value;
  45454. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  45455. this._shadowGenerator.recreateShadowMap();
  45456. }
  45457. },
  45458. enumerable: true,
  45459. configurable: true
  45460. });
  45461. /**
  45462. * Returns the string "PointLight"
  45463. * @returns the class name
  45464. */
  45465. PointLight.prototype.getClassName = function () {
  45466. return "PointLight";
  45467. };
  45468. /**
  45469. * Returns the integer 0.
  45470. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  45471. */
  45472. PointLight.prototype.getTypeID = function () {
  45473. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  45474. };
  45475. /**
  45476. * Specifies wether or not the shadowmap should be a cube texture.
  45477. * @returns true if the shadowmap needs to be a cube texture.
  45478. */
  45479. PointLight.prototype.needCube = function () {
  45480. return !this.direction;
  45481. };
  45482. /**
  45483. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  45484. * @param faceIndex The index of the face we are computed the direction to generate shadow
  45485. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  45486. */
  45487. PointLight.prototype.getShadowDirection = function (faceIndex) {
  45488. if (this.direction) {
  45489. return _super.prototype.getShadowDirection.call(this, faceIndex);
  45490. }
  45491. else {
  45492. switch (faceIndex) {
  45493. case 0:
  45494. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  45495. case 1:
  45496. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  45497. case 2:
  45498. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  45499. case 3:
  45500. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  45501. case 4:
  45502. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  45503. case 5:
  45504. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  45505. }
  45506. }
  45507. return BABYLON.Vector3.Zero();
  45508. };
  45509. /**
  45510. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  45511. * - fov = PI / 2
  45512. * - aspect ratio : 1.0
  45513. * - z-near and far equal to the active camera minZ and maxZ.
  45514. * Returns the PointLight.
  45515. */
  45516. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  45517. var activeCamera = this.getScene().activeCamera;
  45518. if (!activeCamera) {
  45519. return;
  45520. }
  45521. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  45522. };
  45523. PointLight.prototype._buildUniformLayout = function () {
  45524. this._uniformBuffer.addUniform("vLightData", 4);
  45525. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  45526. this._uniformBuffer.addUniform("vLightSpecular", 3);
  45527. this._uniformBuffer.addUniform("shadowsInfo", 3);
  45528. this._uniformBuffer.addUniform("depthValues", 2);
  45529. this._uniformBuffer.create();
  45530. };
  45531. /**
  45532. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  45533. * @param effect The effect to update
  45534. * @param lightIndex The index of the light in the effect to update
  45535. * @returns The point light
  45536. */
  45537. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  45538. if (this.computeTransformedInformation()) {
  45539. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  45540. return this;
  45541. }
  45542. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  45543. return this;
  45544. };
  45545. __decorate([
  45546. BABYLON.serialize()
  45547. ], PointLight.prototype, "shadowAngle", null);
  45548. return PointLight;
  45549. }(BABYLON.ShadowLight));
  45550. BABYLON.PointLight = PointLight;
  45551. })(BABYLON || (BABYLON = {}));
  45552. //# sourceMappingURL=babylon.pointLight.js.map
  45553. var BABYLON;
  45554. (function (BABYLON) {
  45555. /**
  45556. * A directional light is defined by a direction (what a surprise!).
  45557. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  45558. * An example of a directional light is when a distance planet is lit by the apparently parallel lines of light from its sun. Light in a downward direction will light the top of an object.
  45559. * Documentation: https://doc.babylonjs.com/babylon101/lights
  45560. */
  45561. var DirectionalLight = /** @class */ (function (_super) {
  45562. __extends(DirectionalLight, _super);
  45563. /**
  45564. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  45565. * The directional light is emitted from everywhere in the given direction.
  45566. * It can cast shawdows.
  45567. * Documentation : http://doc.babylonjs.com/tutorials/lights
  45568. * @param name The friendly name of the light
  45569. * @param direction The direction of the light
  45570. * @param scene The scene the light belongs to
  45571. */
  45572. function DirectionalLight(name, direction, scene) {
  45573. var _this = _super.call(this, name, scene) || this;
  45574. _this._shadowFrustumSize = 0;
  45575. _this._shadowOrthoScale = 0.5;
  45576. /**
  45577. * Automatically compute the projection matrix to best fit (including all the casters)
  45578. * on each frame.
  45579. */
  45580. _this.autoUpdateExtends = true;
  45581. // Cache
  45582. _this._orthoLeft = Number.MAX_VALUE;
  45583. _this._orthoRight = Number.MIN_VALUE;
  45584. _this._orthoTop = Number.MIN_VALUE;
  45585. _this._orthoBottom = Number.MAX_VALUE;
  45586. _this.position = direction.scale(-1.0);
  45587. _this.direction = direction;
  45588. return _this;
  45589. }
  45590. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  45591. /**
  45592. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  45593. */
  45594. get: function () {
  45595. return this._shadowFrustumSize;
  45596. },
  45597. /**
  45598. * Specifies a fix frustum size for the shadow generation.
  45599. */
  45600. set: function (value) {
  45601. this._shadowFrustumSize = value;
  45602. this.forceProjectionMatrixCompute();
  45603. },
  45604. enumerable: true,
  45605. configurable: true
  45606. });
  45607. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  45608. /**
  45609. * Gets the shadow projection scale against the optimal computed one.
  45610. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  45611. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  45612. */
  45613. get: function () {
  45614. return this._shadowOrthoScale;
  45615. },
  45616. /**
  45617. * Sets the shadow projection scale against the optimal computed one.
  45618. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  45619. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  45620. */
  45621. set: function (value) {
  45622. this._shadowOrthoScale = value;
  45623. this.forceProjectionMatrixCompute();
  45624. },
  45625. enumerable: true,
  45626. configurable: true
  45627. });
  45628. /**
  45629. * Returns the string "DirectionalLight".
  45630. * @return The class name
  45631. */
  45632. DirectionalLight.prototype.getClassName = function () {
  45633. return "DirectionalLight";
  45634. };
  45635. /**
  45636. * Returns the integer 1.
  45637. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  45638. */
  45639. DirectionalLight.prototype.getTypeID = function () {
  45640. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  45641. };
  45642. /**
  45643. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  45644. * Returns the DirectionalLight Shadow projection matrix.
  45645. */
  45646. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  45647. if (this.shadowFrustumSize > 0) {
  45648. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  45649. }
  45650. else {
  45651. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  45652. }
  45653. };
  45654. /**
  45655. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  45656. * Returns the DirectionalLight Shadow projection matrix.
  45657. */
  45658. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  45659. var activeCamera = this.getScene().activeCamera;
  45660. if (!activeCamera) {
  45661. return;
  45662. }
  45663. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  45664. };
  45665. /**
  45666. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  45667. * Returns the DirectionalLight Shadow projection matrix.
  45668. */
  45669. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  45670. var activeCamera = this.getScene().activeCamera;
  45671. if (!activeCamera) {
  45672. return;
  45673. }
  45674. // Check extends
  45675. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  45676. var tempVector3 = BABYLON.Vector3.Zero();
  45677. this._orthoLeft = Number.MAX_VALUE;
  45678. this._orthoRight = Number.MIN_VALUE;
  45679. this._orthoTop = Number.MIN_VALUE;
  45680. this._orthoBottom = Number.MAX_VALUE;
  45681. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  45682. var mesh = renderList[meshIndex];
  45683. if (!mesh) {
  45684. continue;
  45685. }
  45686. var boundingInfo = mesh.getBoundingInfo();
  45687. var boundingBox = boundingInfo.boundingBox;
  45688. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  45689. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  45690. if (tempVector3.x < this._orthoLeft)
  45691. this._orthoLeft = tempVector3.x;
  45692. if (tempVector3.y < this._orthoBottom)
  45693. this._orthoBottom = tempVector3.y;
  45694. if (tempVector3.x > this._orthoRight)
  45695. this._orthoRight = tempVector3.x;
  45696. if (tempVector3.y > this._orthoTop)
  45697. this._orthoTop = tempVector3.y;
  45698. }
  45699. }
  45700. }
  45701. var xOffset = this._orthoRight - this._orthoLeft;
  45702. var yOffset = this._orthoTop - this._orthoBottom;
  45703. 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);
  45704. };
  45705. DirectionalLight.prototype._buildUniformLayout = function () {
  45706. this._uniformBuffer.addUniform("vLightData", 4);
  45707. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  45708. this._uniformBuffer.addUniform("vLightSpecular", 3);
  45709. this._uniformBuffer.addUniform("shadowsInfo", 3);
  45710. this._uniformBuffer.addUniform("depthValues", 2);
  45711. this._uniformBuffer.create();
  45712. };
  45713. /**
  45714. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  45715. * @param effect The effect to update
  45716. * @param lightIndex The index of the light in the effect to update
  45717. * @returns The directional light
  45718. */
  45719. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  45720. if (this.computeTransformedInformation()) {
  45721. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  45722. return this;
  45723. }
  45724. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  45725. return this;
  45726. };
  45727. /**
  45728. * Gets the minZ used for shadow according to both the scene and the light.
  45729. *
  45730. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  45731. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  45732. * @param activeCamera The camera we are returning the min for
  45733. * @returns the depth min z
  45734. */
  45735. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  45736. return 1;
  45737. };
  45738. /**
  45739. * Gets the maxZ used for shadow according to both the scene and the light.
  45740. *
  45741. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  45742. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  45743. * @param activeCamera The camera we are returning the max for
  45744. * @returns the depth max z
  45745. */
  45746. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  45747. return 1;
  45748. };
  45749. __decorate([
  45750. BABYLON.serialize()
  45751. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  45752. __decorate([
  45753. BABYLON.serialize()
  45754. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  45755. __decorate([
  45756. BABYLON.serialize()
  45757. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  45758. return DirectionalLight;
  45759. }(BABYLON.ShadowLight));
  45760. BABYLON.DirectionalLight = DirectionalLight;
  45761. })(BABYLON || (BABYLON = {}));
  45762. //# sourceMappingURL=babylon.directionalLight.js.map
  45763. var BABYLON;
  45764. (function (BABYLON) {
  45765. /**
  45766. * A spot light is defined by a position, a direction, an angle, and an exponent.
  45767. * These values define a cone of light starting from the position, emitting toward the direction.
  45768. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  45769. * and the exponent defines the speed of the decay of the light with distance (reach).
  45770. * Documentation: https://doc.babylonjs.com/babylon101/lights
  45771. */
  45772. var SpotLight = /** @class */ (function (_super) {
  45773. __extends(SpotLight, _super);
  45774. /**
  45775. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  45776. * It can cast shadows.
  45777. * Documentation : http://doc.babylonjs.com/tutorials/lights
  45778. * @param name The light friendly name
  45779. * @param position The position of the spot light in the scene
  45780. * @param direction The direction of the light in the scene
  45781. * @param angle The cone angle of the light in Radians
  45782. * @param exponent The light decay speed with the distance from the emission spot
  45783. * @param scene The scene the lights belongs to
  45784. */
  45785. function SpotLight(name, position, direction, angle, exponent, scene) {
  45786. var _this = _super.call(this, name, scene) || this;
  45787. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  45788. _this._projectionTextureLightNear = 1e-6;
  45789. _this._projectionTextureLightFar = 1000.0;
  45790. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  45791. _this._projectionTextureViewLightDirty = true;
  45792. _this._projectionTextureProjectionLightDirty = true;
  45793. _this._projectionTextureDirty = true;
  45794. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  45795. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  45796. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  45797. _this._projectionTextureScalingMatrix = BABYLON.Matrix.FromValues(0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.5, 0.5, 0.5, 1.0);
  45798. _this.position = position;
  45799. _this.direction = direction;
  45800. _this.angle = angle;
  45801. _this.exponent = exponent;
  45802. return _this;
  45803. }
  45804. Object.defineProperty(SpotLight.prototype, "angle", {
  45805. /**
  45806. * Gets the cone angle of the spot light in Radians.
  45807. */
  45808. get: function () {
  45809. return this._angle;
  45810. },
  45811. /**
  45812. * Sets the cone angle of the spot light in Radians.
  45813. */
  45814. set: function (value) {
  45815. this._angle = value;
  45816. this._projectionTextureProjectionLightDirty = true;
  45817. this.forceProjectionMatrixCompute();
  45818. },
  45819. enumerable: true,
  45820. configurable: true
  45821. });
  45822. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  45823. /**
  45824. * Allows scaling the angle of the light for shadow generation only.
  45825. */
  45826. get: function () {
  45827. return this._shadowAngleScale;
  45828. },
  45829. /**
  45830. * Allows scaling the angle of the light for shadow generation only.
  45831. */
  45832. set: function (value) {
  45833. this._shadowAngleScale = value;
  45834. this.forceProjectionMatrixCompute();
  45835. },
  45836. enumerable: true,
  45837. configurable: true
  45838. });
  45839. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  45840. /**
  45841. * Allows reading the projecton texture
  45842. */
  45843. get: function () {
  45844. return this._projectionTextureMatrix;
  45845. },
  45846. enumerable: true,
  45847. configurable: true
  45848. });
  45849. ;
  45850. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  45851. /**
  45852. * Gets the near clip of the Spotlight for texture projection.
  45853. */
  45854. get: function () {
  45855. return this._projectionTextureLightNear;
  45856. },
  45857. /**
  45858. * Sets the near clip of the Spotlight for texture projection.
  45859. */
  45860. set: function (value) {
  45861. this._projectionTextureLightNear = value;
  45862. this._projectionTextureProjectionLightDirty = true;
  45863. },
  45864. enumerable: true,
  45865. configurable: true
  45866. });
  45867. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  45868. /**
  45869. * Gets the far clip of the Spotlight for texture projection.
  45870. */
  45871. get: function () {
  45872. return this._projectionTextureLightFar;
  45873. },
  45874. /**
  45875. * Sets the far clip of the Spotlight for texture projection.
  45876. */
  45877. set: function (value) {
  45878. this._projectionTextureLightFar = value;
  45879. this._projectionTextureProjectionLightDirty = true;
  45880. },
  45881. enumerable: true,
  45882. configurable: true
  45883. });
  45884. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  45885. /**
  45886. * Gets the Up vector of the Spotlight for texture projection.
  45887. */
  45888. get: function () {
  45889. return this._projectionTextureUpDirection;
  45890. },
  45891. /**
  45892. * Sets the Up vector of the Spotlight for texture projection.
  45893. */
  45894. set: function (value) {
  45895. this._projectionTextureUpDirection = value;
  45896. this._projectionTextureProjectionLightDirty = true;
  45897. },
  45898. enumerable: true,
  45899. configurable: true
  45900. });
  45901. ;
  45902. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  45903. /**
  45904. * Gets the projection texture of the light.
  45905. */
  45906. get: function () {
  45907. return this._projectionTexture;
  45908. },
  45909. /**
  45910. * Sets the projection texture of the light.
  45911. */
  45912. set: function (value) {
  45913. this._projectionTexture = value;
  45914. this._projectionTextureDirty = true;
  45915. },
  45916. enumerable: true,
  45917. configurable: true
  45918. });
  45919. /**
  45920. * Returns the string "SpotLight".
  45921. * @returns the class name
  45922. */
  45923. SpotLight.prototype.getClassName = function () {
  45924. return "SpotLight";
  45925. };
  45926. /**
  45927. * Returns the integer 2.
  45928. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  45929. */
  45930. SpotLight.prototype.getTypeID = function () {
  45931. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  45932. };
  45933. /**
  45934. * Overrides the direction setter to recompute the projection texture view light Matrix.
  45935. */
  45936. SpotLight.prototype._setDirection = function (value) {
  45937. _super.prototype._setDirection.call(this, value);
  45938. this._projectionTextureViewLightDirty = true;
  45939. };
  45940. /**
  45941. * Overrides the position setter to recompute the projection texture view light Matrix.
  45942. */
  45943. SpotLight.prototype._setPosition = function (value) {
  45944. _super.prototype._setPosition.call(this, value);
  45945. this._projectionTextureViewLightDirty = true;
  45946. };
  45947. /**
  45948. * 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.
  45949. * Returns the SpotLight.
  45950. */
  45951. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  45952. var activeCamera = this.getScene().activeCamera;
  45953. if (!activeCamera) {
  45954. return;
  45955. }
  45956. this._shadowAngleScale = this._shadowAngleScale || 1;
  45957. var angle = this._shadowAngleScale * this._angle;
  45958. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  45959. };
  45960. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  45961. this._projectionTextureViewLightDirty = false;
  45962. this._projectionTextureDirty = true;
  45963. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  45964. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  45965. };
  45966. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  45967. this._projectionTextureProjectionLightDirty = false;
  45968. this._projectionTextureDirty = true;
  45969. var light_far = this.projectionTextureLightFar;
  45970. var light_near = this.projectionTextureLightNear;
  45971. var P = light_far / (light_far - light_near);
  45972. var Q = -P * light_near;
  45973. var S = 1.0 / Math.tan(this._angle / 2.0);
  45974. var A = 1.0;
  45975. BABYLON.Matrix.FromValuesToRef(S / A, 0.0, 0.0, 0.0, 0.0, S, 0.0, 0.0, 0.0, 0.0, P, 1.0, 0.0, 0.0, Q, 0.0, this._projectionTextureProjectionLightMatrix);
  45976. };
  45977. /**
  45978. * Main function for light texture projection matrix computing.
  45979. */
  45980. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  45981. this._projectionTextureDirty = false;
  45982. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  45983. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  45984. };
  45985. SpotLight.prototype._buildUniformLayout = function () {
  45986. this._uniformBuffer.addUniform("vLightData", 4);
  45987. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  45988. this._uniformBuffer.addUniform("vLightSpecular", 3);
  45989. this._uniformBuffer.addUniform("vLightDirection", 3);
  45990. this._uniformBuffer.addUniform("shadowsInfo", 3);
  45991. this._uniformBuffer.addUniform("depthValues", 2);
  45992. this._uniformBuffer.create();
  45993. };
  45994. /**
  45995. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  45996. * @param effect The effect to update
  45997. * @param lightIndex The index of the light in the effect to update
  45998. * @returns The spot light
  45999. */
  46000. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  46001. var normalizeDirection;
  46002. if (this.computeTransformedInformation()) {
  46003. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  46004. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  46005. }
  46006. else {
  46007. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  46008. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  46009. }
  46010. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  46011. if (this.projectionTexture && this.projectionTexture.isReady()) {
  46012. if (this._projectionTextureViewLightDirty) {
  46013. this._computeProjectionTextureViewLightMatrix();
  46014. }
  46015. if (this._projectionTextureProjectionLightDirty) {
  46016. this._computeProjectionTextureProjectionLightMatrix();
  46017. }
  46018. if (this._projectionTextureDirty) {
  46019. this._computeProjectionTextureMatrix();
  46020. }
  46021. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  46022. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  46023. }
  46024. return this;
  46025. };
  46026. /**
  46027. * Disposes the light and the associated resources.
  46028. */
  46029. SpotLight.prototype.dispose = function () {
  46030. _super.prototype.dispose.call(this);
  46031. if (this._projectionTexture) {
  46032. this._projectionTexture.dispose();
  46033. }
  46034. };
  46035. __decorate([
  46036. BABYLON.serialize()
  46037. ], SpotLight.prototype, "angle", null);
  46038. __decorate([
  46039. BABYLON.serialize()
  46040. ], SpotLight.prototype, "shadowAngleScale", null);
  46041. __decorate([
  46042. BABYLON.serialize()
  46043. ], SpotLight.prototype, "exponent", void 0);
  46044. __decorate([
  46045. BABYLON.serialize()
  46046. ], SpotLight.prototype, "projectionTextureLightNear", null);
  46047. __decorate([
  46048. BABYLON.serialize()
  46049. ], SpotLight.prototype, "projectionTextureLightFar", null);
  46050. __decorate([
  46051. BABYLON.serialize()
  46052. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  46053. __decorate([
  46054. BABYLON.serializeAsTexture("projectedLightTexture")
  46055. ], SpotLight.prototype, "_projectionTexture", void 0);
  46056. return SpotLight;
  46057. }(BABYLON.ShadowLight));
  46058. BABYLON.SpotLight = SpotLight;
  46059. })(BABYLON || (BABYLON = {}));
  46060. //# sourceMappingURL=babylon.spotLight.js.map
  46061. var BABYLON;
  46062. (function (BABYLON) {
  46063. var AnimationRange = /** @class */ (function () {
  46064. function AnimationRange(name, from, to) {
  46065. this.name = name;
  46066. this.from = from;
  46067. this.to = to;
  46068. }
  46069. AnimationRange.prototype.clone = function () {
  46070. return new AnimationRange(this.name, this.from, this.to);
  46071. };
  46072. return AnimationRange;
  46073. }());
  46074. BABYLON.AnimationRange = AnimationRange;
  46075. /**
  46076. * Composed of a frame, and an action function
  46077. */
  46078. var AnimationEvent = /** @class */ (function () {
  46079. function AnimationEvent(frame, action, onlyOnce) {
  46080. this.frame = frame;
  46081. this.action = action;
  46082. this.onlyOnce = onlyOnce;
  46083. this.isDone = false;
  46084. }
  46085. return AnimationEvent;
  46086. }());
  46087. BABYLON.AnimationEvent = AnimationEvent;
  46088. var PathCursor = /** @class */ (function () {
  46089. function PathCursor(path) {
  46090. this.path = path;
  46091. this._onchange = new Array();
  46092. this.value = 0;
  46093. this.animations = new Array();
  46094. }
  46095. PathCursor.prototype.getPoint = function () {
  46096. var point = this.path.getPointAtLengthPosition(this.value);
  46097. return new BABYLON.Vector3(point.x, 0, point.y);
  46098. };
  46099. PathCursor.prototype.moveAhead = function (step) {
  46100. if (step === void 0) { step = 0.002; }
  46101. this.move(step);
  46102. return this;
  46103. };
  46104. PathCursor.prototype.moveBack = function (step) {
  46105. if (step === void 0) { step = 0.002; }
  46106. this.move(-step);
  46107. return this;
  46108. };
  46109. PathCursor.prototype.move = function (step) {
  46110. if (Math.abs(step) > 1) {
  46111. throw "step size should be less than 1.";
  46112. }
  46113. this.value += step;
  46114. this.ensureLimits();
  46115. this.raiseOnChange();
  46116. return this;
  46117. };
  46118. PathCursor.prototype.ensureLimits = function () {
  46119. while (this.value > 1) {
  46120. this.value -= 1;
  46121. }
  46122. while (this.value < 0) {
  46123. this.value += 1;
  46124. }
  46125. return this;
  46126. };
  46127. // used by animation engine
  46128. PathCursor.prototype.raiseOnChange = function () {
  46129. var _this = this;
  46130. this._onchange.forEach(function (f) { return f(_this); });
  46131. return this;
  46132. };
  46133. PathCursor.prototype.onchange = function (f) {
  46134. this._onchange.push(f);
  46135. return this;
  46136. };
  46137. return PathCursor;
  46138. }());
  46139. BABYLON.PathCursor = PathCursor;
  46140. var AnimationKeyInterpolation;
  46141. (function (AnimationKeyInterpolation) {
  46142. /**
  46143. * Do not interpolate between keys and use the start key value only. Tangents are ignored.
  46144. */
  46145. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  46146. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  46147. var Animation = /** @class */ (function () {
  46148. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  46149. this.name = name;
  46150. this.targetProperty = targetProperty;
  46151. this.framePerSecond = framePerSecond;
  46152. this.dataType = dataType;
  46153. this.loopMode = loopMode;
  46154. this.enableBlending = enableBlending;
  46155. this._runtimeAnimations = new Array();
  46156. // The set of event that will be linked to this animation
  46157. this._events = new Array();
  46158. this.blendingSpeed = 0.01;
  46159. this._ranges = {};
  46160. this.targetPropertyPath = targetProperty.split(".");
  46161. this.dataType = dataType;
  46162. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  46163. }
  46164. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  46165. var dataType = undefined;
  46166. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  46167. dataType = Animation.ANIMATIONTYPE_FLOAT;
  46168. }
  46169. else if (from instanceof BABYLON.Quaternion) {
  46170. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  46171. }
  46172. else if (from instanceof BABYLON.Vector3) {
  46173. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  46174. }
  46175. else if (from instanceof BABYLON.Vector2) {
  46176. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  46177. }
  46178. else if (from instanceof BABYLON.Color3) {
  46179. dataType = Animation.ANIMATIONTYPE_COLOR3;
  46180. }
  46181. else if (from instanceof BABYLON.Size) {
  46182. dataType = Animation.ANIMATIONTYPE_SIZE;
  46183. }
  46184. if (dataType == undefined) {
  46185. return null;
  46186. }
  46187. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  46188. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  46189. animation.setKeys(keys);
  46190. if (easingFunction !== undefined) {
  46191. animation.setEasingFunction(easingFunction);
  46192. }
  46193. return animation;
  46194. };
  46195. /**
  46196. * Sets up an animation.
  46197. * @param property the property to animate
  46198. * @param animationType the animation type to apply
  46199. * @param easingFunction the easing function used in the animation
  46200. * @returns The created animation
  46201. */
  46202. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  46203. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  46204. animation.setEasingFunction(easingFunction);
  46205. return animation;
  46206. };
  46207. /**
  46208. * Create and start an animation on a node
  46209. * @param {string} name defines the name of the global animation that will be run on all nodes
  46210. * @param {BABYLON.Node} node defines the root node where the animation will take place
  46211. * @param {string} targetProperty defines property to animate
  46212. * @param {number} framePerSecond defines the number of frame per second yo use
  46213. * @param {number} totalFrame defines the number of frames in total
  46214. * @param {any} from defines the initial value
  46215. * @param {any} to defines the final value
  46216. * @param {number} loopMode defines which loop mode you want to use (off by default)
  46217. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  46218. * @param onAnimationEnd defines the callback to call when animation end
  46219. * @returns the animatable created for this animation
  46220. */
  46221. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  46222. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  46223. if (!animation) {
  46224. return null;
  46225. }
  46226. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  46227. };
  46228. /**
  46229. * Create and start an animation on a node and its descendants
  46230. * @param {string} name defines the name of the global animation that will be run on all nodes
  46231. * @param {BABYLON.Node} node defines the root node where the animation will take place
  46232. * @param {boolean} directDescendantsOnly if true only direct descendants will be used, if false direct and also indirect (children of children, an so on in a recursive manner) descendants will be used.
  46233. * @param {string} targetProperty defines property to animate
  46234. * @param {number} framePerSecond defines the number of frame per second yo use
  46235. * @param {number} totalFrame defines the number of frames in total
  46236. * @param {any} from defines the initial value
  46237. * @param {any} to defines the final value
  46238. * @param {number} loopMode defines which loop mode you want to use (off by default)
  46239. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  46240. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  46241. * @returns the list of animatables created for all nodes
  46242. * @example https://www.babylonjs-playground.com/#MH0VLI
  46243. */
  46244. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  46245. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  46246. if (!animation) {
  46247. return null;
  46248. }
  46249. var scene = node.getScene();
  46250. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  46251. };
  46252. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  46253. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  46254. if (!animation) {
  46255. return null;
  46256. }
  46257. node.animations.push(animation);
  46258. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  46259. };
  46260. /**
  46261. * Transition property of the Camera to the target Value.
  46262. * @param property The property to transition
  46263. * @param targetValue The target Value of the property
  46264. * @param host The object where the property to animate belongs
  46265. * @param scene Scene used to run the animation
  46266. * @param frameRate Framerate (in frame/s) to use
  46267. * @param transition The transition type we want to use
  46268. * @param duration The duration of the animation, in milliseconds
  46269. * @param onAnimationEnd Call back trigger at the end of the animation.
  46270. */
  46271. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  46272. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  46273. if (duration <= 0) {
  46274. host[property] = targetValue;
  46275. if (onAnimationEnd) {
  46276. onAnimationEnd();
  46277. }
  46278. return null;
  46279. }
  46280. var endFrame = frameRate * (duration / 1000);
  46281. transition.setKeys([{
  46282. frame: 0,
  46283. value: host[property].clone ? host[property].clone() : host[property]
  46284. },
  46285. {
  46286. frame: endFrame,
  46287. value: targetValue
  46288. }]);
  46289. if (!host.animations) {
  46290. host.animations = [];
  46291. }
  46292. host.animations.push(transition);
  46293. var animation = scene.beginAnimation(host, 0, endFrame, false);
  46294. animation.onAnimationEnd = onAnimationEnd;
  46295. return animation;
  46296. };
  46297. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  46298. /**
  46299. * Return the array of runtime animations currently using this animation
  46300. */
  46301. get: function () {
  46302. return this._runtimeAnimations;
  46303. },
  46304. enumerable: true,
  46305. configurable: true
  46306. });
  46307. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  46308. get: function () {
  46309. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  46310. var runtimeAnimation = _a[_i];
  46311. if (!runtimeAnimation.isStopped) {
  46312. return true;
  46313. }
  46314. }
  46315. return false;
  46316. },
  46317. enumerable: true,
  46318. configurable: true
  46319. });
  46320. // Methods
  46321. /**
  46322. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  46323. */
  46324. Animation.prototype.toString = function (fullDetails) {
  46325. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  46326. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  46327. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  46328. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  46329. if (fullDetails) {
  46330. ret += ", Ranges: {";
  46331. var first = true;
  46332. for (var name in this._ranges) {
  46333. if (first) {
  46334. ret += ", ";
  46335. first = false;
  46336. }
  46337. ret += name;
  46338. }
  46339. ret += "}";
  46340. }
  46341. return ret;
  46342. };
  46343. /**
  46344. * Add an event to this animation.
  46345. */
  46346. Animation.prototype.addEvent = function (event) {
  46347. this._events.push(event);
  46348. };
  46349. /**
  46350. * Remove all events found at the given frame
  46351. * @param frame
  46352. */
  46353. Animation.prototype.removeEvents = function (frame) {
  46354. for (var index = 0; index < this._events.length; index++) {
  46355. if (this._events[index].frame === frame) {
  46356. this._events.splice(index, 1);
  46357. index--;
  46358. }
  46359. }
  46360. };
  46361. Animation.prototype.getEvents = function () {
  46362. return this._events;
  46363. };
  46364. Animation.prototype.createRange = function (name, from, to) {
  46365. // check name not already in use; could happen for bones after serialized
  46366. if (!this._ranges[name]) {
  46367. this._ranges[name] = new AnimationRange(name, from, to);
  46368. }
  46369. };
  46370. Animation.prototype.deleteRange = function (name, deleteFrames) {
  46371. if (deleteFrames === void 0) { deleteFrames = true; }
  46372. var range = this._ranges[name];
  46373. if (!range) {
  46374. return;
  46375. }
  46376. if (deleteFrames) {
  46377. var from = range.from;
  46378. var to = range.to;
  46379. // this loop MUST go high to low for multiple splices to work
  46380. for (var key = this._keys.length - 1; key >= 0; key--) {
  46381. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  46382. this._keys.splice(key, 1);
  46383. }
  46384. }
  46385. }
  46386. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  46387. };
  46388. Animation.prototype.getRange = function (name) {
  46389. return this._ranges[name];
  46390. };
  46391. Animation.prototype.getKeys = function () {
  46392. return this._keys;
  46393. };
  46394. Animation.prototype.getHighestFrame = function () {
  46395. var ret = 0;
  46396. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  46397. if (ret < this._keys[key].frame) {
  46398. ret = this._keys[key].frame;
  46399. }
  46400. }
  46401. return ret;
  46402. };
  46403. Animation.prototype.getEasingFunction = function () {
  46404. return this._easingFunction;
  46405. };
  46406. Animation.prototype.setEasingFunction = function (easingFunction) {
  46407. this._easingFunction = easingFunction;
  46408. };
  46409. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  46410. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  46411. };
  46412. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  46413. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  46414. };
  46415. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  46416. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  46417. };
  46418. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  46419. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  46420. };
  46421. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  46422. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  46423. };
  46424. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  46425. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  46426. };
  46427. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  46428. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  46429. };
  46430. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  46431. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  46432. };
  46433. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  46434. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  46435. };
  46436. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  46437. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  46438. };
  46439. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  46440. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  46441. };
  46442. Animation.prototype.clone = function () {
  46443. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  46444. clone.enableBlending = this.enableBlending;
  46445. clone.blendingSpeed = this.blendingSpeed;
  46446. if (this._keys) {
  46447. clone.setKeys(this._keys);
  46448. }
  46449. if (this._ranges) {
  46450. clone._ranges = {};
  46451. for (var name in this._ranges) {
  46452. var range = this._ranges[name];
  46453. if (!range) {
  46454. continue;
  46455. }
  46456. clone._ranges[name] = range.clone();
  46457. }
  46458. }
  46459. return clone;
  46460. };
  46461. Animation.prototype.setKeys = function (values) {
  46462. this._keys = values.slice(0);
  46463. };
  46464. Animation.prototype.serialize = function () {
  46465. var serializationObject = {};
  46466. serializationObject.name = this.name;
  46467. serializationObject.property = this.targetProperty;
  46468. serializationObject.framePerSecond = this.framePerSecond;
  46469. serializationObject.dataType = this.dataType;
  46470. serializationObject.loopBehavior = this.loopMode;
  46471. serializationObject.enableBlending = this.enableBlending;
  46472. serializationObject.blendingSpeed = this.blendingSpeed;
  46473. var dataType = this.dataType;
  46474. serializationObject.keys = [];
  46475. var keys = this.getKeys();
  46476. for (var index = 0; index < keys.length; index++) {
  46477. var animationKey = keys[index];
  46478. var key = {};
  46479. key.frame = animationKey.frame;
  46480. switch (dataType) {
  46481. case Animation.ANIMATIONTYPE_FLOAT:
  46482. key.values = [animationKey.value];
  46483. break;
  46484. case Animation.ANIMATIONTYPE_QUATERNION:
  46485. case Animation.ANIMATIONTYPE_MATRIX:
  46486. case Animation.ANIMATIONTYPE_VECTOR3:
  46487. case Animation.ANIMATIONTYPE_COLOR3:
  46488. key.values = animationKey.value.asArray();
  46489. break;
  46490. }
  46491. serializationObject.keys.push(key);
  46492. }
  46493. serializationObject.ranges = [];
  46494. for (var name in this._ranges) {
  46495. var source = this._ranges[name];
  46496. if (!source) {
  46497. continue;
  46498. }
  46499. var range = {};
  46500. range.name = name;
  46501. range.from = source.from;
  46502. range.to = source.to;
  46503. serializationObject.ranges.push(range);
  46504. }
  46505. return serializationObject;
  46506. };
  46507. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  46508. get: function () {
  46509. return Animation._ANIMATIONTYPE_FLOAT;
  46510. },
  46511. enumerable: true,
  46512. configurable: true
  46513. });
  46514. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  46515. get: function () {
  46516. return Animation._ANIMATIONTYPE_VECTOR3;
  46517. },
  46518. enumerable: true,
  46519. configurable: true
  46520. });
  46521. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  46522. get: function () {
  46523. return Animation._ANIMATIONTYPE_VECTOR2;
  46524. },
  46525. enumerable: true,
  46526. configurable: true
  46527. });
  46528. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  46529. get: function () {
  46530. return Animation._ANIMATIONTYPE_SIZE;
  46531. },
  46532. enumerable: true,
  46533. configurable: true
  46534. });
  46535. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  46536. get: function () {
  46537. return Animation._ANIMATIONTYPE_QUATERNION;
  46538. },
  46539. enumerable: true,
  46540. configurable: true
  46541. });
  46542. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  46543. get: function () {
  46544. return Animation._ANIMATIONTYPE_MATRIX;
  46545. },
  46546. enumerable: true,
  46547. configurable: true
  46548. });
  46549. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  46550. get: function () {
  46551. return Animation._ANIMATIONTYPE_COLOR3;
  46552. },
  46553. enumerable: true,
  46554. configurable: true
  46555. });
  46556. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  46557. get: function () {
  46558. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  46559. },
  46560. enumerable: true,
  46561. configurable: true
  46562. });
  46563. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  46564. get: function () {
  46565. return Animation._ANIMATIONLOOPMODE_CYCLE;
  46566. },
  46567. enumerable: true,
  46568. configurable: true
  46569. });
  46570. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  46571. get: function () {
  46572. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  46573. },
  46574. enumerable: true,
  46575. configurable: true
  46576. });
  46577. Animation.Parse = function (parsedAnimation) {
  46578. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  46579. var dataType = parsedAnimation.dataType;
  46580. var keys = [];
  46581. var data;
  46582. var index;
  46583. if (parsedAnimation.enableBlending) {
  46584. animation.enableBlending = parsedAnimation.enableBlending;
  46585. }
  46586. if (parsedAnimation.blendingSpeed) {
  46587. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  46588. }
  46589. for (index = 0; index < parsedAnimation.keys.length; index++) {
  46590. var key = parsedAnimation.keys[index];
  46591. var inTangent;
  46592. var outTangent;
  46593. switch (dataType) {
  46594. case Animation.ANIMATIONTYPE_FLOAT:
  46595. data = key.values[0];
  46596. if (key.values.length >= 1) {
  46597. inTangent = key.values[1];
  46598. }
  46599. if (key.values.length >= 2) {
  46600. outTangent = key.values[2];
  46601. }
  46602. break;
  46603. case Animation.ANIMATIONTYPE_QUATERNION:
  46604. data = BABYLON.Quaternion.FromArray(key.values);
  46605. if (key.values.length >= 8) {
  46606. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  46607. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  46608. inTangent = _inTangent;
  46609. }
  46610. }
  46611. if (key.values.length >= 12) {
  46612. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  46613. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  46614. outTangent = _outTangent;
  46615. }
  46616. }
  46617. break;
  46618. case Animation.ANIMATIONTYPE_MATRIX:
  46619. data = BABYLON.Matrix.FromArray(key.values);
  46620. break;
  46621. case Animation.ANIMATIONTYPE_COLOR3:
  46622. data = BABYLON.Color3.FromArray(key.values);
  46623. break;
  46624. case Animation.ANIMATIONTYPE_VECTOR3:
  46625. default:
  46626. data = BABYLON.Vector3.FromArray(key.values);
  46627. break;
  46628. }
  46629. var keyData = {};
  46630. keyData.frame = key.frame;
  46631. keyData.value = data;
  46632. if (inTangent != undefined) {
  46633. keyData.inTangent = inTangent;
  46634. }
  46635. if (outTangent != undefined) {
  46636. keyData.outTangent = outTangent;
  46637. }
  46638. keys.push(keyData);
  46639. }
  46640. animation.setKeys(keys);
  46641. if (parsedAnimation.ranges) {
  46642. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  46643. data = parsedAnimation.ranges[index];
  46644. animation.createRange(data.name, data.from, data.to);
  46645. }
  46646. }
  46647. return animation;
  46648. };
  46649. Animation.AppendSerializedAnimations = function (source, destination) {
  46650. if (source.animations) {
  46651. destination.animations = [];
  46652. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  46653. var animation = source.animations[animationIndex];
  46654. destination.animations.push(animation.serialize());
  46655. }
  46656. }
  46657. };
  46658. Animation.AllowMatricesInterpolation = false;
  46659. // Statics
  46660. Animation._ANIMATIONTYPE_FLOAT = 0;
  46661. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  46662. Animation._ANIMATIONTYPE_QUATERNION = 2;
  46663. Animation._ANIMATIONTYPE_MATRIX = 3;
  46664. Animation._ANIMATIONTYPE_COLOR3 = 4;
  46665. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  46666. Animation._ANIMATIONTYPE_SIZE = 6;
  46667. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  46668. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  46669. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  46670. return Animation;
  46671. }());
  46672. BABYLON.Animation = Animation;
  46673. })(BABYLON || (BABYLON = {}));
  46674. //# sourceMappingURL=babylon.animation.js.map
  46675. var BABYLON;
  46676. (function (BABYLON) {
  46677. /**
  46678. * This class defines the direct association between an animation and a target
  46679. */
  46680. var TargetedAnimation = /** @class */ (function () {
  46681. function TargetedAnimation() {
  46682. }
  46683. return TargetedAnimation;
  46684. }());
  46685. BABYLON.TargetedAnimation = TargetedAnimation;
  46686. /**
  46687. * Use this class to create coordinated animations on multiple targets
  46688. */
  46689. var AnimationGroup = /** @class */ (function () {
  46690. function AnimationGroup(name, scene) {
  46691. if (scene === void 0) { scene = null; }
  46692. this.name = name;
  46693. this._targetedAnimations = new Array();
  46694. this._animatables = new Array();
  46695. this._from = Number.MAX_VALUE;
  46696. this._to = -Number.MAX_VALUE;
  46697. this._speedRatio = 1;
  46698. this.onAnimationEndObservable = new BABYLON.Observable();
  46699. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  46700. this._scene.animationGroups.push(this);
  46701. }
  46702. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  46703. /**
  46704. * Define if the animations are started
  46705. */
  46706. get: function () {
  46707. return this._isStarted;
  46708. },
  46709. enumerable: true,
  46710. configurable: true
  46711. });
  46712. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  46713. /**
  46714. * Gets or sets the speed ratio to use for all animations
  46715. */
  46716. get: function () {
  46717. return this._speedRatio;
  46718. },
  46719. /**
  46720. * Gets or sets the speed ratio to use for all animations
  46721. */
  46722. set: function (value) {
  46723. if (this._speedRatio === value) {
  46724. return;
  46725. }
  46726. this._speedRatio = value;
  46727. for (var index = 0; index < this._animatables.length; index++) {
  46728. var animatable = this._animatables[index];
  46729. animatable.speedRatio = this._speedRatio;
  46730. }
  46731. },
  46732. enumerable: true,
  46733. configurable: true
  46734. });
  46735. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  46736. /**
  46737. * Gets the targeted animations for this animation group
  46738. */
  46739. get: function () {
  46740. return this._targetedAnimations;
  46741. },
  46742. enumerable: true,
  46743. configurable: true
  46744. });
  46745. /**
  46746. * Add an animation (with its target) in the group
  46747. * @param animation defines the animation we want to add
  46748. * @param target defines the target of the animation
  46749. * @returns the {BABYLON.TargetedAnimation} object
  46750. */
  46751. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  46752. var targetedAnimation = {
  46753. animation: animation,
  46754. target: target
  46755. };
  46756. var keys = animation.getKeys();
  46757. if (this._from > keys[0].frame) {
  46758. this._from = keys[0].frame;
  46759. }
  46760. if (this._to < keys[keys.length - 1].frame) {
  46761. this._to = keys[keys.length - 1].frame;
  46762. }
  46763. this._targetedAnimations.push(targetedAnimation);
  46764. return targetedAnimation;
  46765. };
  46766. /**
  46767. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  46768. * It can add constant keys at begin or end
  46769. * @param beginFrame defines the new begin frame for all animations. It can't be bigger than the smallest begin frame of all animations
  46770. * @param endFrame defines the new end frame for all animations. It can't be smaller than the largest end frame of all animations
  46771. */
  46772. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  46773. if (beginFrame === void 0) { beginFrame = -Number.MAX_VALUE; }
  46774. if (endFrame === void 0) { endFrame = Number.MAX_VALUE; }
  46775. beginFrame = Math.max(beginFrame, this._from);
  46776. endFrame = Math.min(endFrame, this._to);
  46777. for (var index = 0; index < this._targetedAnimations.length; index++) {
  46778. var targetedAnimation = this._targetedAnimations[index];
  46779. var keys = targetedAnimation.animation.getKeys();
  46780. var startKey = keys[0];
  46781. var endKey = keys[keys.length - 1];
  46782. if (startKey.frame > beginFrame) {
  46783. var newKey = {
  46784. frame: beginFrame,
  46785. value: startKey.value,
  46786. inTangent: startKey.inTangent,
  46787. outTangent: startKey.outTangent,
  46788. interpolation: startKey.interpolation
  46789. };
  46790. keys.splice(0, 0, newKey);
  46791. }
  46792. if (endKey.frame < endFrame) {
  46793. var newKey = {
  46794. frame: endFrame,
  46795. value: endKey.value,
  46796. inTangent: endKey.outTangent,
  46797. outTangent: endKey.outTangent,
  46798. interpolation: endKey.interpolation
  46799. };
  46800. keys.push(newKey);
  46801. }
  46802. }
  46803. return this;
  46804. };
  46805. /**
  46806. * Start all animations on given targets
  46807. * @param loop defines if animations must loop
  46808. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  46809. */
  46810. AnimationGroup.prototype.start = function (loop, speedRatio) {
  46811. var _this = this;
  46812. if (loop === void 0) { loop = false; }
  46813. if (speedRatio === void 0) { speedRatio = 1; }
  46814. if (this._isStarted || this._targetedAnimations.length === 0) {
  46815. return this;
  46816. }
  46817. var _loop_1 = function () {
  46818. var targetedAnimation = this_1._targetedAnimations[index];
  46819. this_1._animatables.push(this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], this_1._from, this_1._to, loop, speedRatio, function () {
  46820. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  46821. }));
  46822. };
  46823. var this_1 = this;
  46824. for (var index = 0; index < this._targetedAnimations.length; index++) {
  46825. _loop_1();
  46826. }
  46827. this._speedRatio = speedRatio;
  46828. this._isStarted = true;
  46829. return this;
  46830. };
  46831. /**
  46832. * Pause all animations
  46833. */
  46834. AnimationGroup.prototype.pause = function () {
  46835. if (!this._isStarted) {
  46836. return this;
  46837. }
  46838. for (var index = 0; index < this._animatables.length; index++) {
  46839. var animatable = this._animatables[index];
  46840. animatable.pause();
  46841. }
  46842. return this;
  46843. };
  46844. /**
  46845. * Play all animations to initial state
  46846. * This function will start() the animations if they were not started or will restart() them if they were paused
  46847. * @param loop defines if animations must loop
  46848. */
  46849. AnimationGroup.prototype.play = function (loop) {
  46850. if (this.isStarted) {
  46851. if (loop !== undefined) {
  46852. for (var index = 0; index < this._animatables.length; index++) {
  46853. var animatable = this._animatables[index];
  46854. animatable.loopAnimation = loop;
  46855. }
  46856. }
  46857. this.restart();
  46858. }
  46859. else {
  46860. this.start(loop, this._speedRatio);
  46861. }
  46862. return this;
  46863. };
  46864. /**
  46865. * Reset all animations to initial state
  46866. */
  46867. AnimationGroup.prototype.reset = function () {
  46868. if (!this._isStarted) {
  46869. return this;
  46870. }
  46871. for (var index = 0; index < this._animatables.length; index++) {
  46872. var animatable = this._animatables[index];
  46873. animatable.reset();
  46874. }
  46875. return this;
  46876. };
  46877. /**
  46878. * Restart animations from key 0
  46879. */
  46880. AnimationGroup.prototype.restart = function () {
  46881. if (!this._isStarted) {
  46882. return this;
  46883. }
  46884. for (var index = 0; index < this._animatables.length; index++) {
  46885. var animatable = this._animatables[index];
  46886. animatable.restart();
  46887. }
  46888. return this;
  46889. };
  46890. /**
  46891. * Stop all animations
  46892. */
  46893. AnimationGroup.prototype.stop = function () {
  46894. if (!this._isStarted) {
  46895. return this;
  46896. }
  46897. for (var index = 0; index < this._animatables.length; index++) {
  46898. var animatable = this._animatables[index];
  46899. animatable.stop();
  46900. }
  46901. this._isStarted = false;
  46902. return this;
  46903. };
  46904. /**
  46905. * Dispose all associated resources
  46906. */
  46907. AnimationGroup.prototype.dispose = function () {
  46908. this._targetedAnimations = [];
  46909. this._animatables = [];
  46910. var index = this._scene.animationGroups.indexOf(this);
  46911. if (index > -1) {
  46912. this._scene.animationGroups.splice(index, 1);
  46913. }
  46914. };
  46915. return AnimationGroup;
  46916. }());
  46917. BABYLON.AnimationGroup = AnimationGroup;
  46918. })(BABYLON || (BABYLON = {}));
  46919. //# sourceMappingURL=babylon.animationGroup.js.map
  46920. var BABYLON;
  46921. (function (BABYLON) {
  46922. var RuntimeAnimation = /** @class */ (function () {
  46923. function RuntimeAnimation(target, animation) {
  46924. this._offsetsCache = {};
  46925. this._highLimitsCache = {};
  46926. this._stopped = false;
  46927. this._blendingFactor = 0;
  46928. this._ratioOffset = 0;
  46929. this._animation = animation;
  46930. this._target = target;
  46931. animation._runtimeAnimations.push(this);
  46932. }
  46933. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  46934. get: function () {
  46935. return this._animation;
  46936. },
  46937. enumerable: true,
  46938. configurable: true
  46939. });
  46940. RuntimeAnimation.prototype.reset = function () {
  46941. this._offsetsCache = {};
  46942. this._highLimitsCache = {};
  46943. this.currentFrame = 0;
  46944. this._blendingFactor = 0;
  46945. this._originalBlendValue = null;
  46946. };
  46947. RuntimeAnimation.prototype.isStopped = function () {
  46948. return this._stopped;
  46949. };
  46950. RuntimeAnimation.prototype.dispose = function () {
  46951. var index = this._animation.runtimeAnimations.indexOf(this);
  46952. if (index > -1) {
  46953. this._animation.runtimeAnimations.splice(index, 1);
  46954. }
  46955. };
  46956. RuntimeAnimation.prototype._getKeyValue = function (value) {
  46957. if (typeof value === "function") {
  46958. return value();
  46959. }
  46960. return value;
  46961. };
  46962. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  46963. if (loopMode === BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  46964. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  46965. }
  46966. this.currentFrame = currentFrame;
  46967. var keys = this._animation.getKeys();
  46968. // Try to get a hash to find the right key
  46969. 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));
  46970. if (keys[startKeyIndex].frame >= currentFrame) {
  46971. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  46972. startKeyIndex--;
  46973. }
  46974. }
  46975. for (var key = startKeyIndex; key < keys.length; key++) {
  46976. var endKey = keys[key + 1];
  46977. if (endKey.frame >= currentFrame) {
  46978. var startKey = keys[key];
  46979. var startValue = this._getKeyValue(startKey.value);
  46980. if (startKey.interpolation === BABYLON.AnimationKeyInterpolation.STEP) {
  46981. return startValue;
  46982. }
  46983. var endValue = this._getKeyValue(endKey.value);
  46984. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  46985. var frameDelta = endKey.frame - startKey.frame;
  46986. // gradient : percent of currentFrame between the frame inf and the frame sup
  46987. var gradient = (currentFrame - startKey.frame) / frameDelta;
  46988. // check for easingFunction and correction of gradient
  46989. var easingFunction = this._animation.getEasingFunction();
  46990. if (easingFunction != null) {
  46991. gradient = easingFunction.ease(gradient);
  46992. }
  46993. switch (this._animation.dataType) {
  46994. // Float
  46995. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  46996. var floatValue = useTangent ? this._animation.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this._animation.floatInterpolateFunction(startValue, endValue, gradient);
  46997. switch (loopMode) {
  46998. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  46999. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47000. return floatValue;
  47001. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47002. return offsetValue * repeatCount + floatValue;
  47003. }
  47004. break;
  47005. // Quaternion
  47006. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  47007. var quatValue = useTangent ? this._animation.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.quaternionInterpolateFunction(startValue, endValue, gradient);
  47008. switch (loopMode) {
  47009. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47010. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47011. return quatValue;
  47012. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47013. return quatValue.add(offsetValue.scale(repeatCount));
  47014. }
  47015. return quatValue;
  47016. // Vector3
  47017. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  47018. var vec3Value = useTangent ? this._animation.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector3InterpolateFunction(startValue, endValue, gradient);
  47019. switch (loopMode) {
  47020. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47021. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47022. return vec3Value;
  47023. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47024. return vec3Value.add(offsetValue.scale(repeatCount));
  47025. }
  47026. // Vector2
  47027. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  47028. var vec2Value = useTangent ? this._animation.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector2InterpolateFunction(startValue, endValue, gradient);
  47029. switch (loopMode) {
  47030. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47031. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47032. return vec2Value;
  47033. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47034. return vec2Value.add(offsetValue.scale(repeatCount));
  47035. }
  47036. // Size
  47037. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  47038. switch (loopMode) {
  47039. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47040. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47041. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient);
  47042. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47043. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  47044. }
  47045. // Color3
  47046. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  47047. switch (loopMode) {
  47048. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47049. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47050. return this._animation.color3InterpolateFunction(startValue, endValue, gradient);
  47051. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47052. return this._animation.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  47053. }
  47054. // Matrix
  47055. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  47056. switch (loopMode) {
  47057. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47058. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47059. if (BABYLON.Animation.AllowMatricesInterpolation) {
  47060. return this._animation.matrixInterpolateFunction(startValue, endValue, gradient);
  47061. }
  47062. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47063. return startValue;
  47064. }
  47065. default:
  47066. break;
  47067. }
  47068. break;
  47069. }
  47070. }
  47071. return this._getKeyValue(keys[keys.length - 1].value);
  47072. };
  47073. RuntimeAnimation.prototype.setValue = function (currentValue, blend) {
  47074. if (blend === void 0) { blend = false; }
  47075. // Set value
  47076. var path;
  47077. var destination;
  47078. var targetPropertyPath = this._animation.targetPropertyPath;
  47079. if (targetPropertyPath.length > 1) {
  47080. var property = this._target[targetPropertyPath[0]];
  47081. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  47082. property = property[targetPropertyPath[index]];
  47083. }
  47084. path = targetPropertyPath[targetPropertyPath.length - 1];
  47085. destination = property;
  47086. }
  47087. else {
  47088. path = targetPropertyPath[0];
  47089. destination = this._target;
  47090. }
  47091. // Blending
  47092. if (this._animation.enableBlending && this._blendingFactor <= 1.0) {
  47093. if (!this._originalBlendValue) {
  47094. if (destination[path].clone) {
  47095. this._originalBlendValue = destination[path].clone();
  47096. }
  47097. else {
  47098. this._originalBlendValue = destination[path];
  47099. }
  47100. }
  47101. if (this._originalBlendValue.prototype) {
  47102. if (this._originalBlendValue.prototype.Lerp) {
  47103. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  47104. }
  47105. else {
  47106. destination[path] = currentValue;
  47107. }
  47108. }
  47109. else if (this._originalBlendValue.m) {
  47110. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  47111. }
  47112. else {
  47113. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  47114. }
  47115. this._blendingFactor += this._animation.blendingSpeed;
  47116. }
  47117. else {
  47118. destination[path] = currentValue;
  47119. }
  47120. if (this._target.markAsDirty) {
  47121. this._target.markAsDirty(this._animation.targetProperty);
  47122. }
  47123. };
  47124. RuntimeAnimation.prototype.goToFrame = function (frame) {
  47125. var keys = this._animation.getKeys();
  47126. if (frame < keys[0].frame) {
  47127. frame = keys[0].frame;
  47128. }
  47129. else if (frame > keys[keys.length - 1].frame) {
  47130. frame = keys[keys.length - 1].frame;
  47131. }
  47132. var currentValue = this._interpolate(frame, 0, this._animation.loopMode);
  47133. this.setValue(currentValue);
  47134. };
  47135. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  47136. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  47137. this._ratioOffset = this._previousRatio - newRatio;
  47138. };
  47139. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  47140. if (blend === void 0) { blend = false; }
  47141. var targetPropertyPath = this._animation.targetPropertyPath;
  47142. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  47143. this._stopped = true;
  47144. return false;
  47145. }
  47146. var returnValue = true;
  47147. var keys = this._animation.getKeys();
  47148. // Adding a start key at frame 0 if missing
  47149. if (keys[0].frame !== 0) {
  47150. var newKey = { frame: 0, value: keys[0].value };
  47151. keys.splice(0, 0, newKey);
  47152. }
  47153. // Check limits
  47154. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  47155. from = keys[0].frame;
  47156. }
  47157. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  47158. to = keys[keys.length - 1].frame;
  47159. }
  47160. //to and from cannot be the same key
  47161. if (from === to) {
  47162. if (from > keys[0].frame) {
  47163. from--;
  47164. }
  47165. else if (to < keys[keys.length - 1].frame) {
  47166. to++;
  47167. }
  47168. }
  47169. // Compute ratio
  47170. var range = to - from;
  47171. var offsetValue;
  47172. // ratio represents the frame delta between from and to
  47173. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  47174. var highLimitValue = 0;
  47175. this._previousDelay = delay;
  47176. this._previousRatio = ratio;
  47177. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  47178. returnValue = false;
  47179. highLimitValue = this._getKeyValue(keys[keys.length - 1].value);
  47180. }
  47181. else {
  47182. // Get max value if required
  47183. if (this._animation.loopMode !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  47184. var keyOffset = to.toString() + from.toString();
  47185. if (!this._offsetsCache[keyOffset]) {
  47186. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  47187. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  47188. switch (this._animation.dataType) {
  47189. // Float
  47190. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  47191. this._offsetsCache[keyOffset] = toValue - fromValue;
  47192. break;
  47193. // Quaternion
  47194. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  47195. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  47196. break;
  47197. // Vector3
  47198. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  47199. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  47200. // Vector2
  47201. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  47202. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  47203. // Size
  47204. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  47205. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  47206. // Color3
  47207. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  47208. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  47209. default:
  47210. break;
  47211. }
  47212. this._highLimitsCache[keyOffset] = toValue;
  47213. }
  47214. highLimitValue = this._highLimitsCache[keyOffset];
  47215. offsetValue = this._offsetsCache[keyOffset];
  47216. }
  47217. }
  47218. if (offsetValue === undefined) {
  47219. switch (this._animation.dataType) {
  47220. // Float
  47221. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  47222. offsetValue = 0;
  47223. break;
  47224. // Quaternion
  47225. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  47226. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  47227. break;
  47228. // Vector3
  47229. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  47230. offsetValue = BABYLON.Vector3.Zero();
  47231. break;
  47232. // Vector2
  47233. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  47234. offsetValue = BABYLON.Vector2.Zero();
  47235. break;
  47236. // Size
  47237. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  47238. offsetValue = BABYLON.Size.Zero();
  47239. break;
  47240. // Color3
  47241. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  47242. offsetValue = BABYLON.Color3.Black();
  47243. }
  47244. }
  47245. // Compute value
  47246. var repeatCount = (ratio / range) >> 0;
  47247. var currentFrame = returnValue ? from + ratio % range : to;
  47248. var currentValue = this._interpolate(currentFrame, repeatCount, this._animation.loopMode, offsetValue, highLimitValue);
  47249. // Set value
  47250. this.setValue(currentValue);
  47251. // Check events
  47252. var events = this._animation.getEvents();
  47253. for (var index = 0; index < events.length; index++) {
  47254. // Make sure current frame has passed event frame and that event frame is within the current range
  47255. // Also, handle both forward and reverse animations
  47256. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  47257. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  47258. var event = events[index];
  47259. if (!event.isDone) {
  47260. // If event should be done only once, remove it.
  47261. if (event.onlyOnce) {
  47262. events.splice(index, 1);
  47263. index--;
  47264. }
  47265. event.isDone = true;
  47266. event.action();
  47267. } // Don't do anything if the event has already be done.
  47268. }
  47269. else if (events[index].isDone && !events[index].onlyOnce) {
  47270. // reset event, the animation is looping
  47271. events[index].isDone = false;
  47272. }
  47273. }
  47274. if (!returnValue) {
  47275. this._stopped = true;
  47276. }
  47277. return returnValue;
  47278. };
  47279. return RuntimeAnimation;
  47280. }());
  47281. BABYLON.RuntimeAnimation = RuntimeAnimation;
  47282. })(BABYLON || (BABYLON = {}));
  47283. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  47284. var BABYLON;
  47285. (function (BABYLON) {
  47286. var Animatable = /** @class */ (function () {
  47287. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  47288. if (fromFrame === void 0) { fromFrame = 0; }
  47289. if (toFrame === void 0) { toFrame = 100; }
  47290. if (loopAnimation === void 0) { loopAnimation = false; }
  47291. if (speedRatio === void 0) { speedRatio = 1.0; }
  47292. this.target = target;
  47293. this.fromFrame = fromFrame;
  47294. this.toFrame = toFrame;
  47295. this.loopAnimation = loopAnimation;
  47296. this.onAnimationEnd = onAnimationEnd;
  47297. this._localDelayOffset = null;
  47298. this._pausedDelay = null;
  47299. this._runtimeAnimations = new Array();
  47300. this._paused = false;
  47301. this._speedRatio = 1;
  47302. this.animationStarted = false;
  47303. if (animations) {
  47304. this.appendAnimations(target, animations);
  47305. }
  47306. this._speedRatio = speedRatio;
  47307. this._scene = scene;
  47308. scene._activeAnimatables.push(this);
  47309. }
  47310. Object.defineProperty(Animatable.prototype, "speedRatio", {
  47311. get: function () {
  47312. return this._speedRatio;
  47313. },
  47314. set: function (value) {
  47315. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  47316. var animation = this._runtimeAnimations[index];
  47317. animation._prepareForSpeedRatioChange(value);
  47318. }
  47319. this._speedRatio = value;
  47320. },
  47321. enumerable: true,
  47322. configurable: true
  47323. });
  47324. // Methods
  47325. Animatable.prototype.getAnimations = function () {
  47326. return this._runtimeAnimations;
  47327. };
  47328. Animatable.prototype.appendAnimations = function (target, animations) {
  47329. for (var index = 0; index < animations.length; index++) {
  47330. var animation = animations[index];
  47331. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation));
  47332. }
  47333. };
  47334. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  47335. var runtimeAnimations = this._runtimeAnimations;
  47336. for (var index = 0; index < runtimeAnimations.length; index++) {
  47337. if (runtimeAnimations[index].animation.targetProperty === property) {
  47338. return runtimeAnimations[index].animation;
  47339. }
  47340. }
  47341. return null;
  47342. };
  47343. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  47344. var runtimeAnimations = this._runtimeAnimations;
  47345. for (var index = 0; index < runtimeAnimations.length; index++) {
  47346. if (runtimeAnimations[index].animation.targetProperty === property) {
  47347. return runtimeAnimations[index];
  47348. }
  47349. }
  47350. return null;
  47351. };
  47352. Animatable.prototype.reset = function () {
  47353. var runtimeAnimations = this._runtimeAnimations;
  47354. for (var index = 0; index < runtimeAnimations.length; index++) {
  47355. runtimeAnimations[index].reset();
  47356. }
  47357. // Reset to original value
  47358. for (index = 0; index < runtimeAnimations.length; index++) {
  47359. var animation = runtimeAnimations[index];
  47360. animation.animate(0, this.fromFrame, this.toFrame, false, this._speedRatio);
  47361. }
  47362. this._localDelayOffset = null;
  47363. this._pausedDelay = null;
  47364. };
  47365. Animatable.prototype.enableBlending = function (blendingSpeed) {
  47366. var runtimeAnimations = this._runtimeAnimations;
  47367. for (var index = 0; index < runtimeAnimations.length; index++) {
  47368. runtimeAnimations[index].animation.enableBlending = true;
  47369. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  47370. }
  47371. };
  47372. Animatable.prototype.disableBlending = function () {
  47373. var runtimeAnimations = this._runtimeAnimations;
  47374. for (var index = 0; index < runtimeAnimations.length; index++) {
  47375. runtimeAnimations[index].animation.enableBlending = false;
  47376. }
  47377. };
  47378. Animatable.prototype.goToFrame = function (frame) {
  47379. var runtimeAnimations = this._runtimeAnimations;
  47380. if (runtimeAnimations[0]) {
  47381. var fps = runtimeAnimations[0].animation.framePerSecond;
  47382. var currentFrame = runtimeAnimations[0].currentFrame;
  47383. var adjustTime = frame - currentFrame;
  47384. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  47385. if (this._localDelayOffset === null) {
  47386. this._localDelayOffset = 0;
  47387. }
  47388. this._localDelayOffset -= delay;
  47389. }
  47390. for (var index = 0; index < runtimeAnimations.length; index++) {
  47391. runtimeAnimations[index].goToFrame(frame);
  47392. }
  47393. };
  47394. Animatable.prototype.pause = function () {
  47395. if (this._paused) {
  47396. return;
  47397. }
  47398. this._paused = true;
  47399. };
  47400. Animatable.prototype.restart = function () {
  47401. this._paused = false;
  47402. };
  47403. Animatable.prototype.stop = function (animationName) {
  47404. if (animationName) {
  47405. var idx = this._scene._activeAnimatables.indexOf(this);
  47406. if (idx > -1) {
  47407. var runtimeAnimations = this._runtimeAnimations;
  47408. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  47409. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  47410. continue;
  47411. }
  47412. runtimeAnimations[index].dispose();
  47413. runtimeAnimations.splice(index, 1);
  47414. }
  47415. if (runtimeAnimations.length == 0) {
  47416. this._scene._activeAnimatables.splice(idx, 1);
  47417. if (this.onAnimationEnd) {
  47418. this.onAnimationEnd();
  47419. }
  47420. }
  47421. }
  47422. }
  47423. else {
  47424. var index = this._scene._activeAnimatables.indexOf(this);
  47425. if (index > -1) {
  47426. this._scene._activeAnimatables.splice(index, 1);
  47427. var runtimeAnimations = this._runtimeAnimations;
  47428. for (var index = 0; index < runtimeAnimations.length; index++) {
  47429. runtimeAnimations[index].dispose();
  47430. }
  47431. if (this.onAnimationEnd) {
  47432. this.onAnimationEnd();
  47433. }
  47434. }
  47435. }
  47436. };
  47437. Animatable.prototype._animate = function (delay) {
  47438. if (this._paused) {
  47439. this.animationStarted = false;
  47440. if (this._pausedDelay === null) {
  47441. this._pausedDelay = delay;
  47442. }
  47443. return true;
  47444. }
  47445. if (this._localDelayOffset === null) {
  47446. this._localDelayOffset = delay;
  47447. this._pausedDelay = null;
  47448. }
  47449. else if (this._pausedDelay !== null) {
  47450. this._localDelayOffset += delay - this._pausedDelay;
  47451. this._pausedDelay = null;
  47452. }
  47453. // Animating
  47454. var running = false;
  47455. var runtimeAnimations = this._runtimeAnimations;
  47456. var index;
  47457. for (index = 0; index < runtimeAnimations.length; index++) {
  47458. var animation = runtimeAnimations[index];
  47459. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio);
  47460. running = running || isRunning;
  47461. }
  47462. this.animationStarted = running;
  47463. if (!running) {
  47464. // Remove from active animatables
  47465. index = this._scene._activeAnimatables.indexOf(this);
  47466. this._scene._activeAnimatables.splice(index, 1);
  47467. // Dispose all runtime animations
  47468. for (index = 0; index < runtimeAnimations.length; index++) {
  47469. runtimeAnimations[index].dispose();
  47470. }
  47471. }
  47472. if (!running && this.onAnimationEnd) {
  47473. this.onAnimationEnd();
  47474. this.onAnimationEnd = null;
  47475. }
  47476. return running;
  47477. };
  47478. return Animatable;
  47479. }());
  47480. BABYLON.Animatable = Animatable;
  47481. })(BABYLON || (BABYLON = {}));
  47482. //# sourceMappingURL=babylon.animatable.js.map
  47483. var BABYLON;
  47484. (function (BABYLON) {
  47485. var EasingFunction = /** @class */ (function () {
  47486. function EasingFunction() {
  47487. // Properties
  47488. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  47489. }
  47490. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  47491. get: function () {
  47492. return EasingFunction._EASINGMODE_EASEIN;
  47493. },
  47494. enumerable: true,
  47495. configurable: true
  47496. });
  47497. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  47498. get: function () {
  47499. return EasingFunction._EASINGMODE_EASEOUT;
  47500. },
  47501. enumerable: true,
  47502. configurable: true
  47503. });
  47504. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  47505. get: function () {
  47506. return EasingFunction._EASINGMODE_EASEINOUT;
  47507. },
  47508. enumerable: true,
  47509. configurable: true
  47510. });
  47511. EasingFunction.prototype.setEasingMode = function (easingMode) {
  47512. var n = Math.min(Math.max(easingMode, 0), 2);
  47513. this._easingMode = n;
  47514. };
  47515. EasingFunction.prototype.getEasingMode = function () {
  47516. return this._easingMode;
  47517. };
  47518. EasingFunction.prototype.easeInCore = function (gradient) {
  47519. throw new Error('You must implement this method');
  47520. };
  47521. EasingFunction.prototype.ease = function (gradient) {
  47522. switch (this._easingMode) {
  47523. case EasingFunction.EASINGMODE_EASEIN:
  47524. return this.easeInCore(gradient);
  47525. case EasingFunction.EASINGMODE_EASEOUT:
  47526. return (1 - this.easeInCore(1 - gradient));
  47527. }
  47528. if (gradient >= 0.5) {
  47529. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  47530. }
  47531. return (this.easeInCore(gradient * 2) * 0.5);
  47532. };
  47533. //Statics
  47534. EasingFunction._EASINGMODE_EASEIN = 0;
  47535. EasingFunction._EASINGMODE_EASEOUT = 1;
  47536. EasingFunction._EASINGMODE_EASEINOUT = 2;
  47537. return EasingFunction;
  47538. }());
  47539. BABYLON.EasingFunction = EasingFunction;
  47540. var CircleEase = /** @class */ (function (_super) {
  47541. __extends(CircleEase, _super);
  47542. function CircleEase() {
  47543. return _super !== null && _super.apply(this, arguments) || this;
  47544. }
  47545. CircleEase.prototype.easeInCore = function (gradient) {
  47546. gradient = Math.max(0, Math.min(1, gradient));
  47547. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  47548. };
  47549. return CircleEase;
  47550. }(EasingFunction));
  47551. BABYLON.CircleEase = CircleEase;
  47552. var BackEase = /** @class */ (function (_super) {
  47553. __extends(BackEase, _super);
  47554. function BackEase(amplitude) {
  47555. if (amplitude === void 0) { amplitude = 1; }
  47556. var _this = _super.call(this) || this;
  47557. _this.amplitude = amplitude;
  47558. return _this;
  47559. }
  47560. BackEase.prototype.easeInCore = function (gradient) {
  47561. var num = Math.max(0, this.amplitude);
  47562. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  47563. };
  47564. return BackEase;
  47565. }(EasingFunction));
  47566. BABYLON.BackEase = BackEase;
  47567. var BounceEase = /** @class */ (function (_super) {
  47568. __extends(BounceEase, _super);
  47569. function BounceEase(bounces, bounciness) {
  47570. if (bounces === void 0) { bounces = 3; }
  47571. if (bounciness === void 0) { bounciness = 2; }
  47572. var _this = _super.call(this) || this;
  47573. _this.bounces = bounces;
  47574. _this.bounciness = bounciness;
  47575. return _this;
  47576. }
  47577. BounceEase.prototype.easeInCore = function (gradient) {
  47578. var y = Math.max(0.0, this.bounces);
  47579. var bounciness = this.bounciness;
  47580. if (bounciness <= 1.0) {
  47581. bounciness = 1.001;
  47582. }
  47583. var num9 = Math.pow(bounciness, y);
  47584. var num5 = 1.0 - bounciness;
  47585. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  47586. var num15 = gradient * num4;
  47587. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  47588. var num3 = Math.floor(num65);
  47589. var num13 = num3 + 1.0;
  47590. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  47591. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  47592. var num7 = (num8 + num12) * 0.5;
  47593. var num6 = gradient - num7;
  47594. var num2 = num7 - num8;
  47595. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  47596. };
  47597. return BounceEase;
  47598. }(EasingFunction));
  47599. BABYLON.BounceEase = BounceEase;
  47600. var CubicEase = /** @class */ (function (_super) {
  47601. __extends(CubicEase, _super);
  47602. function CubicEase() {
  47603. return _super !== null && _super.apply(this, arguments) || this;
  47604. }
  47605. CubicEase.prototype.easeInCore = function (gradient) {
  47606. return (gradient * gradient * gradient);
  47607. };
  47608. return CubicEase;
  47609. }(EasingFunction));
  47610. BABYLON.CubicEase = CubicEase;
  47611. var ElasticEase = /** @class */ (function (_super) {
  47612. __extends(ElasticEase, _super);
  47613. function ElasticEase(oscillations, springiness) {
  47614. if (oscillations === void 0) { oscillations = 3; }
  47615. if (springiness === void 0) { springiness = 3; }
  47616. var _this = _super.call(this) || this;
  47617. _this.oscillations = oscillations;
  47618. _this.springiness = springiness;
  47619. return _this;
  47620. }
  47621. ElasticEase.prototype.easeInCore = function (gradient) {
  47622. var num2;
  47623. var num3 = Math.max(0.0, this.oscillations);
  47624. var num = Math.max(0.0, this.springiness);
  47625. if (num == 0) {
  47626. num2 = gradient;
  47627. }
  47628. else {
  47629. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  47630. }
  47631. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  47632. };
  47633. return ElasticEase;
  47634. }(EasingFunction));
  47635. BABYLON.ElasticEase = ElasticEase;
  47636. var ExponentialEase = /** @class */ (function (_super) {
  47637. __extends(ExponentialEase, _super);
  47638. function ExponentialEase(exponent) {
  47639. if (exponent === void 0) { exponent = 2; }
  47640. var _this = _super.call(this) || this;
  47641. _this.exponent = exponent;
  47642. return _this;
  47643. }
  47644. ExponentialEase.prototype.easeInCore = function (gradient) {
  47645. if (this.exponent <= 0) {
  47646. return gradient;
  47647. }
  47648. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  47649. };
  47650. return ExponentialEase;
  47651. }(EasingFunction));
  47652. BABYLON.ExponentialEase = ExponentialEase;
  47653. var PowerEase = /** @class */ (function (_super) {
  47654. __extends(PowerEase, _super);
  47655. function PowerEase(power) {
  47656. if (power === void 0) { power = 2; }
  47657. var _this = _super.call(this) || this;
  47658. _this.power = power;
  47659. return _this;
  47660. }
  47661. PowerEase.prototype.easeInCore = function (gradient) {
  47662. var y = Math.max(0.0, this.power);
  47663. return Math.pow(gradient, y);
  47664. };
  47665. return PowerEase;
  47666. }(EasingFunction));
  47667. BABYLON.PowerEase = PowerEase;
  47668. var QuadraticEase = /** @class */ (function (_super) {
  47669. __extends(QuadraticEase, _super);
  47670. function QuadraticEase() {
  47671. return _super !== null && _super.apply(this, arguments) || this;
  47672. }
  47673. QuadraticEase.prototype.easeInCore = function (gradient) {
  47674. return (gradient * gradient);
  47675. };
  47676. return QuadraticEase;
  47677. }(EasingFunction));
  47678. BABYLON.QuadraticEase = QuadraticEase;
  47679. var QuarticEase = /** @class */ (function (_super) {
  47680. __extends(QuarticEase, _super);
  47681. function QuarticEase() {
  47682. return _super !== null && _super.apply(this, arguments) || this;
  47683. }
  47684. QuarticEase.prototype.easeInCore = function (gradient) {
  47685. return (gradient * gradient * gradient * gradient);
  47686. };
  47687. return QuarticEase;
  47688. }(EasingFunction));
  47689. BABYLON.QuarticEase = QuarticEase;
  47690. var QuinticEase = /** @class */ (function (_super) {
  47691. __extends(QuinticEase, _super);
  47692. function QuinticEase() {
  47693. return _super !== null && _super.apply(this, arguments) || this;
  47694. }
  47695. QuinticEase.prototype.easeInCore = function (gradient) {
  47696. return (gradient * gradient * gradient * gradient * gradient);
  47697. };
  47698. return QuinticEase;
  47699. }(EasingFunction));
  47700. BABYLON.QuinticEase = QuinticEase;
  47701. var SineEase = /** @class */ (function (_super) {
  47702. __extends(SineEase, _super);
  47703. function SineEase() {
  47704. return _super !== null && _super.apply(this, arguments) || this;
  47705. }
  47706. SineEase.prototype.easeInCore = function (gradient) {
  47707. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  47708. };
  47709. return SineEase;
  47710. }(EasingFunction));
  47711. BABYLON.SineEase = SineEase;
  47712. var BezierCurveEase = /** @class */ (function (_super) {
  47713. __extends(BezierCurveEase, _super);
  47714. function BezierCurveEase(x1, y1, x2, y2) {
  47715. if (x1 === void 0) { x1 = 0; }
  47716. if (y1 === void 0) { y1 = 0; }
  47717. if (x2 === void 0) { x2 = 1; }
  47718. if (y2 === void 0) { y2 = 1; }
  47719. var _this = _super.call(this) || this;
  47720. _this.x1 = x1;
  47721. _this.y1 = y1;
  47722. _this.x2 = x2;
  47723. _this.y2 = y2;
  47724. return _this;
  47725. }
  47726. BezierCurveEase.prototype.easeInCore = function (gradient) {
  47727. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  47728. };
  47729. return BezierCurveEase;
  47730. }(EasingFunction));
  47731. BABYLON.BezierCurveEase = BezierCurveEase;
  47732. })(BABYLON || (BABYLON = {}));
  47733. //# sourceMappingURL=babylon.easing.js.map
  47734. var BABYLON;
  47735. (function (BABYLON) {
  47736. var Condition = /** @class */ (function () {
  47737. function Condition(actionManager) {
  47738. this._actionManager = actionManager;
  47739. }
  47740. Condition.prototype.isValid = function () {
  47741. return true;
  47742. };
  47743. Condition.prototype._getProperty = function (propertyPath) {
  47744. return this._actionManager._getProperty(propertyPath);
  47745. };
  47746. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  47747. return this._actionManager._getEffectiveTarget(target, propertyPath);
  47748. };
  47749. Condition.prototype.serialize = function () {
  47750. };
  47751. Condition.prototype._serialize = function (serializedCondition) {
  47752. return {
  47753. type: 2,
  47754. children: [],
  47755. name: serializedCondition.name,
  47756. properties: serializedCondition.properties
  47757. };
  47758. };
  47759. return Condition;
  47760. }());
  47761. BABYLON.Condition = Condition;
  47762. var ValueCondition = /** @class */ (function (_super) {
  47763. __extends(ValueCondition, _super);
  47764. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  47765. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  47766. var _this = _super.call(this, actionManager) || this;
  47767. _this.propertyPath = propertyPath;
  47768. _this.value = value;
  47769. _this.operator = operator;
  47770. _this._target = target;
  47771. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  47772. _this._property = _this._getProperty(_this.propertyPath);
  47773. return _this;
  47774. }
  47775. Object.defineProperty(ValueCondition, "IsEqual", {
  47776. get: function () {
  47777. return ValueCondition._IsEqual;
  47778. },
  47779. enumerable: true,
  47780. configurable: true
  47781. });
  47782. Object.defineProperty(ValueCondition, "IsDifferent", {
  47783. get: function () {
  47784. return ValueCondition._IsDifferent;
  47785. },
  47786. enumerable: true,
  47787. configurable: true
  47788. });
  47789. Object.defineProperty(ValueCondition, "IsGreater", {
  47790. get: function () {
  47791. return ValueCondition._IsGreater;
  47792. },
  47793. enumerable: true,
  47794. configurable: true
  47795. });
  47796. Object.defineProperty(ValueCondition, "IsLesser", {
  47797. get: function () {
  47798. return ValueCondition._IsLesser;
  47799. },
  47800. enumerable: true,
  47801. configurable: true
  47802. });
  47803. // Methods
  47804. ValueCondition.prototype.isValid = function () {
  47805. switch (this.operator) {
  47806. case ValueCondition.IsGreater:
  47807. return this._effectiveTarget[this._property] > this.value;
  47808. case ValueCondition.IsLesser:
  47809. return this._effectiveTarget[this._property] < this.value;
  47810. case ValueCondition.IsEqual:
  47811. case ValueCondition.IsDifferent:
  47812. var check;
  47813. if (this.value.equals) {
  47814. check = this.value.equals(this._effectiveTarget[this._property]);
  47815. }
  47816. else {
  47817. check = this.value === this._effectiveTarget[this._property];
  47818. }
  47819. return this.operator === ValueCondition.IsEqual ? check : !check;
  47820. }
  47821. return false;
  47822. };
  47823. ValueCondition.prototype.serialize = function () {
  47824. return this._serialize({
  47825. name: "ValueCondition",
  47826. properties: [
  47827. BABYLON.Action._GetTargetProperty(this._target),
  47828. { name: "propertyPath", value: this.propertyPath },
  47829. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  47830. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  47831. ]
  47832. });
  47833. };
  47834. ValueCondition.GetOperatorName = function (operator) {
  47835. switch (operator) {
  47836. case ValueCondition._IsEqual: return "IsEqual";
  47837. case ValueCondition._IsDifferent: return "IsDifferent";
  47838. case ValueCondition._IsGreater: return "IsGreater";
  47839. case ValueCondition._IsLesser: return "IsLesser";
  47840. default: return "";
  47841. }
  47842. };
  47843. // Statics
  47844. ValueCondition._IsEqual = 0;
  47845. ValueCondition._IsDifferent = 1;
  47846. ValueCondition._IsGreater = 2;
  47847. ValueCondition._IsLesser = 3;
  47848. return ValueCondition;
  47849. }(Condition));
  47850. BABYLON.ValueCondition = ValueCondition;
  47851. var PredicateCondition = /** @class */ (function (_super) {
  47852. __extends(PredicateCondition, _super);
  47853. function PredicateCondition(actionManager, predicate) {
  47854. var _this = _super.call(this, actionManager) || this;
  47855. _this.predicate = predicate;
  47856. return _this;
  47857. }
  47858. PredicateCondition.prototype.isValid = function () {
  47859. return this.predicate();
  47860. };
  47861. return PredicateCondition;
  47862. }(Condition));
  47863. BABYLON.PredicateCondition = PredicateCondition;
  47864. var StateCondition = /** @class */ (function (_super) {
  47865. __extends(StateCondition, _super);
  47866. function StateCondition(actionManager, target, value) {
  47867. var _this = _super.call(this, actionManager) || this;
  47868. _this.value = value;
  47869. _this._target = target;
  47870. return _this;
  47871. }
  47872. // Methods
  47873. StateCondition.prototype.isValid = function () {
  47874. return this._target.state === this.value;
  47875. };
  47876. StateCondition.prototype.serialize = function () {
  47877. return this._serialize({
  47878. name: "StateCondition",
  47879. properties: [
  47880. BABYLON.Action._GetTargetProperty(this._target),
  47881. { name: "value", value: this.value }
  47882. ]
  47883. });
  47884. };
  47885. return StateCondition;
  47886. }(Condition));
  47887. BABYLON.StateCondition = StateCondition;
  47888. })(BABYLON || (BABYLON = {}));
  47889. //# sourceMappingURL=babylon.condition.js.map
  47890. var BABYLON;
  47891. (function (BABYLON) {
  47892. var Action = /** @class */ (function () {
  47893. function Action(triggerOptions, condition) {
  47894. this.triggerOptions = triggerOptions;
  47895. this.onBeforeExecuteObservable = new BABYLON.Observable();
  47896. if (triggerOptions.parameter) {
  47897. this.trigger = triggerOptions.trigger;
  47898. this._triggerParameter = triggerOptions.parameter;
  47899. }
  47900. else {
  47901. this.trigger = triggerOptions;
  47902. }
  47903. this._nextActiveAction = this;
  47904. this._condition = condition;
  47905. }
  47906. // Methods
  47907. Action.prototype._prepare = function () {
  47908. };
  47909. Action.prototype.getTriggerParameter = function () {
  47910. return this._triggerParameter;
  47911. };
  47912. Action.prototype._executeCurrent = function (evt) {
  47913. if (this._nextActiveAction._condition) {
  47914. var condition = this._nextActiveAction._condition;
  47915. var currentRenderId = this._actionManager.getScene().getRenderId();
  47916. // We cache the current evaluation for the current frame
  47917. if (condition._evaluationId === currentRenderId) {
  47918. if (!condition._currentResult) {
  47919. return;
  47920. }
  47921. }
  47922. else {
  47923. condition._evaluationId = currentRenderId;
  47924. if (!condition.isValid()) {
  47925. condition._currentResult = false;
  47926. return;
  47927. }
  47928. condition._currentResult = true;
  47929. }
  47930. }
  47931. this.onBeforeExecuteObservable.notifyObservers(this);
  47932. this._nextActiveAction.execute(evt);
  47933. this.skipToNextActiveAction();
  47934. };
  47935. Action.prototype.execute = function (evt) {
  47936. };
  47937. Action.prototype.skipToNextActiveAction = function () {
  47938. if (this._nextActiveAction._child) {
  47939. if (!this._nextActiveAction._child._actionManager) {
  47940. this._nextActiveAction._child._actionManager = this._actionManager;
  47941. }
  47942. this._nextActiveAction = this._nextActiveAction._child;
  47943. }
  47944. else {
  47945. this._nextActiveAction = this;
  47946. }
  47947. };
  47948. Action.prototype.then = function (action) {
  47949. this._child = action;
  47950. action._actionManager = this._actionManager;
  47951. action._prepare();
  47952. return action;
  47953. };
  47954. Action.prototype._getProperty = function (propertyPath) {
  47955. return this._actionManager._getProperty(propertyPath);
  47956. };
  47957. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  47958. return this._actionManager._getEffectiveTarget(target, propertyPath);
  47959. };
  47960. Action.prototype.serialize = function (parent) {
  47961. };
  47962. // Called by BABYLON.Action objects in serialize(...). Internal use
  47963. Action.prototype._serialize = function (serializedAction, parent) {
  47964. var serializationObject = {
  47965. type: 1,
  47966. children: [],
  47967. name: serializedAction.name,
  47968. properties: serializedAction.properties || []
  47969. };
  47970. // Serialize child
  47971. if (this._child) {
  47972. this._child.serialize(serializationObject);
  47973. }
  47974. // Check if "this" has a condition
  47975. if (this._condition) {
  47976. var serializedCondition = this._condition.serialize();
  47977. serializedCondition.children.push(serializationObject);
  47978. if (parent) {
  47979. parent.children.push(serializedCondition);
  47980. }
  47981. return serializedCondition;
  47982. }
  47983. if (parent) {
  47984. parent.children.push(serializationObject);
  47985. }
  47986. return serializationObject;
  47987. };
  47988. Action._SerializeValueAsString = function (value) {
  47989. if (typeof value === "number") {
  47990. return value.toString();
  47991. }
  47992. if (typeof value === "boolean") {
  47993. return value ? "true" : "false";
  47994. }
  47995. if (value instanceof BABYLON.Vector2) {
  47996. return value.x + ", " + value.y;
  47997. }
  47998. if (value instanceof BABYLON.Vector3) {
  47999. return value.x + ", " + value.y + ", " + value.z;
  48000. }
  48001. if (value instanceof BABYLON.Color3) {
  48002. return value.r + ", " + value.g + ", " + value.b;
  48003. }
  48004. if (value instanceof BABYLON.Color4) {
  48005. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  48006. }
  48007. return value; // string
  48008. };
  48009. Action._GetTargetProperty = function (target) {
  48010. return {
  48011. name: "target",
  48012. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  48013. : target instanceof BABYLON.Light ? "LightProperties"
  48014. : target instanceof BABYLON.Camera ? "CameraProperties"
  48015. : "SceneProperties",
  48016. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  48017. };
  48018. };
  48019. return Action;
  48020. }());
  48021. BABYLON.Action = Action;
  48022. })(BABYLON || (BABYLON = {}));
  48023. //# sourceMappingURL=babylon.action.js.map
  48024. var BABYLON;
  48025. (function (BABYLON) {
  48026. /**
  48027. * ActionEvent is the event beint sent when an action is triggered.
  48028. */
  48029. var ActionEvent = /** @class */ (function () {
  48030. /**
  48031. * @param source The mesh or sprite that triggered the action.
  48032. * @param pointerX The X mouse cursor position at the time of the event
  48033. * @param pointerY The Y mouse cursor position at the time of the event
  48034. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  48035. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  48036. */
  48037. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  48038. this.source = source;
  48039. this.pointerX = pointerX;
  48040. this.pointerY = pointerY;
  48041. this.meshUnderPointer = meshUnderPointer;
  48042. this.sourceEvent = sourceEvent;
  48043. this.additionalData = additionalData;
  48044. }
  48045. /**
  48046. * Helper function to auto-create an ActionEvent from a source mesh.
  48047. * @param source The source mesh that triggered the event
  48048. * @param evt {Event} The original (browser) event
  48049. */
  48050. ActionEvent.CreateNew = function (source, evt, additionalData) {
  48051. var scene = source.getScene();
  48052. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  48053. };
  48054. /**
  48055. * Helper function to auto-create an ActionEvent from a source mesh.
  48056. * @param source The source sprite that triggered the event
  48057. * @param scene Scene associated with the sprite
  48058. * @param evt {Event} The original (browser) event
  48059. */
  48060. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  48061. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  48062. };
  48063. /**
  48064. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  48065. * @param scene the scene where the event occurred
  48066. * @param evt {Event} The original (browser) event
  48067. */
  48068. ActionEvent.CreateNewFromScene = function (scene, evt) {
  48069. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  48070. };
  48071. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  48072. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  48073. };
  48074. return ActionEvent;
  48075. }());
  48076. BABYLON.ActionEvent = ActionEvent;
  48077. /**
  48078. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  48079. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  48080. */
  48081. var ActionManager = /** @class */ (function () {
  48082. function ActionManager(scene) {
  48083. // Members
  48084. this.actions = new Array();
  48085. this.hoverCursor = '';
  48086. this._scene = scene;
  48087. scene._actionManagers.push(this);
  48088. }
  48089. Object.defineProperty(ActionManager, "NothingTrigger", {
  48090. get: function () {
  48091. return ActionManager._NothingTrigger;
  48092. },
  48093. enumerable: true,
  48094. configurable: true
  48095. });
  48096. Object.defineProperty(ActionManager, "OnPickTrigger", {
  48097. get: function () {
  48098. return ActionManager._OnPickTrigger;
  48099. },
  48100. enumerable: true,
  48101. configurable: true
  48102. });
  48103. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  48104. get: function () {
  48105. return ActionManager._OnLeftPickTrigger;
  48106. },
  48107. enumerable: true,
  48108. configurable: true
  48109. });
  48110. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  48111. get: function () {
  48112. return ActionManager._OnRightPickTrigger;
  48113. },
  48114. enumerable: true,
  48115. configurable: true
  48116. });
  48117. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  48118. get: function () {
  48119. return ActionManager._OnCenterPickTrigger;
  48120. },
  48121. enumerable: true,
  48122. configurable: true
  48123. });
  48124. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  48125. get: function () {
  48126. return ActionManager._OnPickDownTrigger;
  48127. },
  48128. enumerable: true,
  48129. configurable: true
  48130. });
  48131. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  48132. get: function () {
  48133. return ActionManager._OnDoublePickTrigger;
  48134. },
  48135. enumerable: true,
  48136. configurable: true
  48137. });
  48138. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  48139. get: function () {
  48140. return ActionManager._OnPickUpTrigger;
  48141. },
  48142. enumerable: true,
  48143. configurable: true
  48144. });
  48145. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  48146. /// This trigger will only be raised if you also declared a OnPickDown
  48147. get: function () {
  48148. return ActionManager._OnPickOutTrigger;
  48149. },
  48150. enumerable: true,
  48151. configurable: true
  48152. });
  48153. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  48154. get: function () {
  48155. return ActionManager._OnLongPressTrigger;
  48156. },
  48157. enumerable: true,
  48158. configurable: true
  48159. });
  48160. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  48161. get: function () {
  48162. return ActionManager._OnPointerOverTrigger;
  48163. },
  48164. enumerable: true,
  48165. configurable: true
  48166. });
  48167. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  48168. get: function () {
  48169. return ActionManager._OnPointerOutTrigger;
  48170. },
  48171. enumerable: true,
  48172. configurable: true
  48173. });
  48174. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  48175. get: function () {
  48176. return ActionManager._OnEveryFrameTrigger;
  48177. },
  48178. enumerable: true,
  48179. configurable: true
  48180. });
  48181. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  48182. get: function () {
  48183. return ActionManager._OnIntersectionEnterTrigger;
  48184. },
  48185. enumerable: true,
  48186. configurable: true
  48187. });
  48188. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  48189. get: function () {
  48190. return ActionManager._OnIntersectionExitTrigger;
  48191. },
  48192. enumerable: true,
  48193. configurable: true
  48194. });
  48195. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  48196. get: function () {
  48197. return ActionManager._OnKeyDownTrigger;
  48198. },
  48199. enumerable: true,
  48200. configurable: true
  48201. });
  48202. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  48203. get: function () {
  48204. return ActionManager._OnKeyUpTrigger;
  48205. },
  48206. enumerable: true,
  48207. configurable: true
  48208. });
  48209. // Methods
  48210. ActionManager.prototype.dispose = function () {
  48211. var index = this._scene._actionManagers.indexOf(this);
  48212. for (var i = 0; i < this.actions.length; i++) {
  48213. var action = this.actions[i];
  48214. ActionManager.Triggers[action.trigger]--;
  48215. if (ActionManager.Triggers[action.trigger] === 0) {
  48216. delete ActionManager.Triggers[action.trigger];
  48217. }
  48218. }
  48219. if (index > -1) {
  48220. this._scene._actionManagers.splice(index, 1);
  48221. }
  48222. };
  48223. ActionManager.prototype.getScene = function () {
  48224. return this._scene;
  48225. };
  48226. /**
  48227. * Does this action manager handles actions of any of the given triggers
  48228. * @param {number[]} triggers - the triggers to be tested
  48229. * @return {boolean} whether one (or more) of the triggers is handeled
  48230. */
  48231. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  48232. for (var index = 0; index < this.actions.length; index++) {
  48233. var action = this.actions[index];
  48234. if (triggers.indexOf(action.trigger) > -1) {
  48235. return true;
  48236. }
  48237. }
  48238. return false;
  48239. };
  48240. /**
  48241. * Does this action manager handles actions of a given trigger
  48242. * @param {number} trigger - the trigger to be tested
  48243. * @return {boolean} whether the trigger is handeled
  48244. */
  48245. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  48246. for (var index = 0; index < this.actions.length; index++) {
  48247. var action = this.actions[index];
  48248. if (action.trigger === trigger) {
  48249. return true;
  48250. }
  48251. }
  48252. return false;
  48253. };
  48254. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  48255. /**
  48256. * Does this action manager has pointer triggers
  48257. * @return {boolean} whether or not it has pointer triggers
  48258. */
  48259. get: function () {
  48260. for (var index = 0; index < this.actions.length; index++) {
  48261. var action = this.actions[index];
  48262. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  48263. return true;
  48264. }
  48265. }
  48266. return false;
  48267. },
  48268. enumerable: true,
  48269. configurable: true
  48270. });
  48271. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  48272. /**
  48273. * Does this action manager has pick triggers
  48274. * @return {boolean} whether or not it has pick triggers
  48275. */
  48276. get: function () {
  48277. for (var index = 0; index < this.actions.length; index++) {
  48278. var action = this.actions[index];
  48279. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  48280. return true;
  48281. }
  48282. }
  48283. return false;
  48284. },
  48285. enumerable: true,
  48286. configurable: true
  48287. });
  48288. Object.defineProperty(ActionManager, "HasTriggers", {
  48289. /**
  48290. * Does exist one action manager with at least one trigger
  48291. * @return {boolean} whether or not it exists one action manager with one trigger
  48292. **/
  48293. get: function () {
  48294. for (var t in ActionManager.Triggers) {
  48295. if (ActionManager.Triggers.hasOwnProperty(t)) {
  48296. return true;
  48297. }
  48298. }
  48299. return false;
  48300. },
  48301. enumerable: true,
  48302. configurable: true
  48303. });
  48304. Object.defineProperty(ActionManager, "HasPickTriggers", {
  48305. /**
  48306. * Does exist one action manager with at least one pick trigger
  48307. * @return {boolean} whether or not it exists one action manager with one pick trigger
  48308. **/
  48309. get: function () {
  48310. for (var t in ActionManager.Triggers) {
  48311. if (ActionManager.Triggers.hasOwnProperty(t)) {
  48312. var t_int = parseInt(t);
  48313. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  48314. return true;
  48315. }
  48316. }
  48317. }
  48318. return false;
  48319. },
  48320. enumerable: true,
  48321. configurable: true
  48322. });
  48323. /**
  48324. * Does exist one action manager that handles actions of a given trigger
  48325. * @param {number} trigger - the trigger to be tested
  48326. * @return {boolean} whether the trigger is handeled by at least one action manager
  48327. **/
  48328. ActionManager.HasSpecificTrigger = function (trigger) {
  48329. for (var t in ActionManager.Triggers) {
  48330. if (ActionManager.Triggers.hasOwnProperty(t)) {
  48331. var t_int = parseInt(t);
  48332. if (t_int === trigger) {
  48333. return true;
  48334. }
  48335. }
  48336. }
  48337. return false;
  48338. };
  48339. /**
  48340. * Registers an action to this action manager
  48341. * @param {BABYLON.Action} action - the action to be registered
  48342. * @return {BABYLON.Action} the action amended (prepared) after registration
  48343. */
  48344. ActionManager.prototype.registerAction = function (action) {
  48345. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  48346. if (this.getScene().actionManager !== this) {
  48347. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  48348. return null;
  48349. }
  48350. }
  48351. this.actions.push(action);
  48352. if (ActionManager.Triggers[action.trigger]) {
  48353. ActionManager.Triggers[action.trigger]++;
  48354. }
  48355. else {
  48356. ActionManager.Triggers[action.trigger] = 1;
  48357. }
  48358. action._actionManager = this;
  48359. action._prepare();
  48360. return action;
  48361. };
  48362. /**
  48363. * Unregisters an action to this action manager
  48364. * @param action The action to be unregistered
  48365. * @return whether the action has been unregistered
  48366. */
  48367. ActionManager.prototype.unregisterAction = function (action) {
  48368. var index = this.actions.indexOf(action);
  48369. if (index !== -1) {
  48370. this.actions.splice(index, 1);
  48371. ActionManager.Triggers[action.trigger] -= 1;
  48372. if (ActionManager.Triggers[action.trigger] === 0) {
  48373. delete ActionManager.Triggers[action.trigger];
  48374. }
  48375. delete action._actionManager;
  48376. return true;
  48377. }
  48378. return false;
  48379. };
  48380. /**
  48381. * Process a specific trigger
  48382. * @param {number} trigger - the trigger to process
  48383. * @param evt {BABYLON.ActionEvent} the event details to be processed
  48384. */
  48385. ActionManager.prototype.processTrigger = function (trigger, evt) {
  48386. for (var index = 0; index < this.actions.length; index++) {
  48387. var action = this.actions[index];
  48388. if (action.trigger === trigger) {
  48389. if (evt) {
  48390. if (trigger === ActionManager.OnKeyUpTrigger
  48391. || trigger === ActionManager.OnKeyDownTrigger) {
  48392. var parameter = action.getTriggerParameter();
  48393. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  48394. if (!parameter.toLowerCase) {
  48395. continue;
  48396. }
  48397. var lowerCase = parameter.toLowerCase();
  48398. if (lowerCase !== evt.sourceEvent.key) {
  48399. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  48400. var actualkey = String.fromCharCode(unicode).toLowerCase();
  48401. if (actualkey !== lowerCase) {
  48402. continue;
  48403. }
  48404. }
  48405. }
  48406. }
  48407. }
  48408. action._executeCurrent(evt);
  48409. }
  48410. }
  48411. };
  48412. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  48413. var properties = propertyPath.split(".");
  48414. for (var index = 0; index < properties.length - 1; index++) {
  48415. target = target[properties[index]];
  48416. }
  48417. return target;
  48418. };
  48419. ActionManager.prototype._getProperty = function (propertyPath) {
  48420. var properties = propertyPath.split(".");
  48421. return properties[properties.length - 1];
  48422. };
  48423. ActionManager.prototype.serialize = function (name) {
  48424. var root = {
  48425. children: new Array(),
  48426. name: name,
  48427. type: 3,
  48428. properties: new Array() // Empty for root but required
  48429. };
  48430. for (var i = 0; i < this.actions.length; i++) {
  48431. var triggerObject = {
  48432. type: 0,
  48433. children: new Array(),
  48434. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  48435. properties: new Array()
  48436. };
  48437. var triggerOptions = this.actions[i].triggerOptions;
  48438. if (triggerOptions && typeof triggerOptions !== "number") {
  48439. if (triggerOptions.parameter instanceof BABYLON.Node) {
  48440. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  48441. }
  48442. else {
  48443. var parameter = {};
  48444. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  48445. if (triggerOptions.parameter.mesh) {
  48446. parameter._meshId = triggerOptions.parameter.mesh.id;
  48447. }
  48448. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  48449. }
  48450. }
  48451. // Serialize child action, recursively
  48452. this.actions[i].serialize(triggerObject);
  48453. // Add serialized trigger
  48454. root.children.push(triggerObject);
  48455. }
  48456. return root;
  48457. };
  48458. ActionManager.Parse = function (parsedActions, object, scene) {
  48459. var actionManager = new ActionManager(scene);
  48460. if (object === null)
  48461. scene.actionManager = actionManager;
  48462. else
  48463. object.actionManager = actionManager;
  48464. // instanciate a new object
  48465. var instanciate = function (name, params) {
  48466. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  48467. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  48468. newInstance.constructor.apply(newInstance, params);
  48469. return newInstance;
  48470. };
  48471. var parseParameter = function (name, value, target, propertyPath) {
  48472. if (propertyPath === null) {
  48473. // String, boolean or float
  48474. var floatValue = parseFloat(value);
  48475. if (value === "true" || value === "false")
  48476. return value === "true";
  48477. else
  48478. return isNaN(floatValue) ? value : floatValue;
  48479. }
  48480. var effectiveTarget = propertyPath.split(".");
  48481. var values = value.split(",");
  48482. // Get effective Target
  48483. for (var i = 0; i < effectiveTarget.length; i++) {
  48484. target = target[effectiveTarget[i]];
  48485. }
  48486. // Return appropriate value with its type
  48487. if (typeof (target) === "boolean")
  48488. return values[0] === "true";
  48489. if (typeof (target) === "string")
  48490. return values[0];
  48491. // Parameters with multiple values such as Vector3 etc.
  48492. var split = new Array();
  48493. for (var i = 0; i < values.length; i++)
  48494. split.push(parseFloat(values[i]));
  48495. if (target instanceof BABYLON.Vector3)
  48496. return BABYLON.Vector3.FromArray(split);
  48497. if (target instanceof BABYLON.Vector4)
  48498. return BABYLON.Vector4.FromArray(split);
  48499. if (target instanceof BABYLON.Color3)
  48500. return BABYLON.Color3.FromArray(split);
  48501. if (target instanceof BABYLON.Color4)
  48502. return BABYLON.Color4.FromArray(split);
  48503. return parseFloat(values[0]);
  48504. };
  48505. // traverse graph per trigger
  48506. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  48507. if (combineArray === void 0) { combineArray = null; }
  48508. if (parsedAction.detached)
  48509. return;
  48510. var parameters = new Array();
  48511. var target = null;
  48512. var propertyPath = null;
  48513. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  48514. // Parameters
  48515. if (parsedAction.type === 2)
  48516. parameters.push(actionManager);
  48517. else
  48518. parameters.push(trigger);
  48519. if (combine) {
  48520. var actions = new Array();
  48521. for (var j = 0; j < parsedAction.combine.length; j++) {
  48522. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  48523. }
  48524. parameters.push(actions);
  48525. }
  48526. else {
  48527. for (var i = 0; i < parsedAction.properties.length; i++) {
  48528. var value = parsedAction.properties[i].value;
  48529. var name = parsedAction.properties[i].name;
  48530. var targetType = parsedAction.properties[i].targetType;
  48531. if (name === "target")
  48532. if (targetType !== null && targetType === "SceneProperties")
  48533. value = target = scene;
  48534. else
  48535. value = target = scene.getNodeByName(value);
  48536. else if (name === "parent")
  48537. value = scene.getNodeByName(value);
  48538. else if (name === "sound")
  48539. value = scene.getSoundByName(value);
  48540. else if (name !== "propertyPath") {
  48541. if (parsedAction.type === 2 && name === "operator")
  48542. value = BABYLON.ValueCondition[value];
  48543. else
  48544. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  48545. }
  48546. else {
  48547. propertyPath = value;
  48548. }
  48549. parameters.push(value);
  48550. }
  48551. }
  48552. if (combineArray === null) {
  48553. parameters.push(condition);
  48554. }
  48555. else {
  48556. parameters.push(null);
  48557. }
  48558. // If interpolate value action
  48559. if (parsedAction.name === "InterpolateValueAction") {
  48560. var param = parameters[parameters.length - 2];
  48561. parameters[parameters.length - 1] = param;
  48562. parameters[parameters.length - 2] = condition;
  48563. }
  48564. // Action or condition(s) and not CombineAction
  48565. var newAction = instanciate(parsedAction.name, parameters);
  48566. if (newAction instanceof BABYLON.Condition && condition !== null) {
  48567. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  48568. if (action)
  48569. action.then(nothing);
  48570. else
  48571. actionManager.registerAction(nothing);
  48572. action = nothing;
  48573. }
  48574. if (combineArray === null) {
  48575. if (newAction instanceof BABYLON.Condition) {
  48576. condition = newAction;
  48577. newAction = action;
  48578. }
  48579. else {
  48580. condition = null;
  48581. if (action)
  48582. action.then(newAction);
  48583. else
  48584. actionManager.registerAction(newAction);
  48585. }
  48586. }
  48587. else {
  48588. combineArray.push(newAction);
  48589. }
  48590. for (var i = 0; i < parsedAction.children.length; i++)
  48591. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  48592. };
  48593. // triggers
  48594. for (var i = 0; i < parsedActions.children.length; i++) {
  48595. var triggerParams;
  48596. var trigger = parsedActions.children[i];
  48597. if (trigger.properties.length > 0) {
  48598. var param = trigger.properties[0].value;
  48599. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  48600. if (value._meshId) {
  48601. value.mesh = scene.getMeshByID(value._meshId);
  48602. }
  48603. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  48604. }
  48605. else
  48606. triggerParams = ActionManager[trigger.name];
  48607. for (var j = 0; j < trigger.children.length; j++) {
  48608. if (!trigger.detached)
  48609. traverse(trigger.children[j], triggerParams, null, null);
  48610. }
  48611. }
  48612. };
  48613. ActionManager.GetTriggerName = function (trigger) {
  48614. switch (trigger) {
  48615. case 0: return "NothingTrigger";
  48616. case 1: return "OnPickTrigger";
  48617. case 2: return "OnLeftPickTrigger";
  48618. case 3: return "OnRightPickTrigger";
  48619. case 4: return "OnCenterPickTrigger";
  48620. case 5: return "OnPickDownTrigger";
  48621. case 6: return "OnPickUpTrigger";
  48622. case 7: return "OnLongPressTrigger";
  48623. case 8: return "OnPointerOverTrigger";
  48624. case 9: return "OnPointerOutTrigger";
  48625. case 10: return "OnEveryFrameTrigger";
  48626. case 11: return "OnIntersectionEnterTrigger";
  48627. case 12: return "OnIntersectionExitTrigger";
  48628. case 13: return "OnKeyDownTrigger";
  48629. case 14: return "OnKeyUpTrigger";
  48630. case 15: return "OnPickOutTrigger";
  48631. default: return "";
  48632. }
  48633. };
  48634. // Statics
  48635. ActionManager._NothingTrigger = 0;
  48636. ActionManager._OnPickTrigger = 1;
  48637. ActionManager._OnLeftPickTrigger = 2;
  48638. ActionManager._OnRightPickTrigger = 3;
  48639. ActionManager._OnCenterPickTrigger = 4;
  48640. ActionManager._OnPickDownTrigger = 5;
  48641. ActionManager._OnDoublePickTrigger = 6;
  48642. ActionManager._OnPickUpTrigger = 7;
  48643. ActionManager._OnLongPressTrigger = 8;
  48644. ActionManager._OnPointerOverTrigger = 9;
  48645. ActionManager._OnPointerOutTrigger = 10;
  48646. ActionManager._OnEveryFrameTrigger = 11;
  48647. ActionManager._OnIntersectionEnterTrigger = 12;
  48648. ActionManager._OnIntersectionExitTrigger = 13;
  48649. ActionManager._OnKeyDownTrigger = 14;
  48650. ActionManager._OnKeyUpTrigger = 15;
  48651. ActionManager._OnPickOutTrigger = 16;
  48652. ActionManager.Triggers = {};
  48653. return ActionManager;
  48654. }());
  48655. BABYLON.ActionManager = ActionManager;
  48656. })(BABYLON || (BABYLON = {}));
  48657. //# sourceMappingURL=babylon.actionManager.js.map
  48658. var BABYLON;
  48659. (function (BABYLON) {
  48660. var InterpolateValueAction = /** @class */ (function (_super) {
  48661. __extends(InterpolateValueAction, _super);
  48662. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  48663. if (duration === void 0) { duration = 1000; }
  48664. var _this = _super.call(this, triggerOptions, condition) || this;
  48665. _this.propertyPath = propertyPath;
  48666. _this.value = value;
  48667. _this.duration = duration;
  48668. _this.stopOtherAnimations = stopOtherAnimations;
  48669. _this.onInterpolationDone = onInterpolationDone;
  48670. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  48671. _this._target = _this._effectiveTarget = target;
  48672. return _this;
  48673. }
  48674. InterpolateValueAction.prototype._prepare = function () {
  48675. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  48676. this._property = this._getProperty(this.propertyPath);
  48677. };
  48678. InterpolateValueAction.prototype.execute = function () {
  48679. var _this = this;
  48680. var scene = this._actionManager.getScene();
  48681. var keys = [
  48682. {
  48683. frame: 0,
  48684. value: this._effectiveTarget[this._property]
  48685. }, {
  48686. frame: 100,
  48687. value: this.value
  48688. }
  48689. ];
  48690. var dataType;
  48691. if (typeof this.value === "number") {
  48692. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  48693. }
  48694. else if (this.value instanceof BABYLON.Color3) {
  48695. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  48696. }
  48697. else if (this.value instanceof BABYLON.Vector3) {
  48698. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  48699. }
  48700. else if (this.value instanceof BABYLON.Matrix) {
  48701. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  48702. }
  48703. else if (this.value instanceof BABYLON.Quaternion) {
  48704. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  48705. }
  48706. else {
  48707. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  48708. return;
  48709. }
  48710. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  48711. animation.setKeys(keys);
  48712. if (this.stopOtherAnimations) {
  48713. scene.stopAnimation(this._effectiveTarget);
  48714. }
  48715. var wrapper = function () {
  48716. _this.onInterpolationDoneObservable.notifyObservers(_this);
  48717. if (_this.onInterpolationDone) {
  48718. _this.onInterpolationDone();
  48719. }
  48720. };
  48721. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  48722. };
  48723. InterpolateValueAction.prototype.serialize = function (parent) {
  48724. return _super.prototype._serialize.call(this, {
  48725. name: "InterpolateValueAction",
  48726. properties: [
  48727. BABYLON.Action._GetTargetProperty(this._target),
  48728. { name: "propertyPath", value: this.propertyPath },
  48729. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  48730. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  48731. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  48732. ]
  48733. }, parent);
  48734. };
  48735. return InterpolateValueAction;
  48736. }(BABYLON.Action));
  48737. BABYLON.InterpolateValueAction = InterpolateValueAction;
  48738. })(BABYLON || (BABYLON = {}));
  48739. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  48740. var BABYLON;
  48741. (function (BABYLON) {
  48742. var SwitchBooleanAction = /** @class */ (function (_super) {
  48743. __extends(SwitchBooleanAction, _super);
  48744. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  48745. var _this = _super.call(this, triggerOptions, condition) || this;
  48746. _this.propertyPath = propertyPath;
  48747. _this._target = _this._effectiveTarget = target;
  48748. return _this;
  48749. }
  48750. SwitchBooleanAction.prototype._prepare = function () {
  48751. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  48752. this._property = this._getProperty(this.propertyPath);
  48753. };
  48754. SwitchBooleanAction.prototype.execute = function () {
  48755. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  48756. };
  48757. SwitchBooleanAction.prototype.serialize = function (parent) {
  48758. return _super.prototype._serialize.call(this, {
  48759. name: "SwitchBooleanAction",
  48760. properties: [
  48761. BABYLON.Action._GetTargetProperty(this._target),
  48762. { name: "propertyPath", value: this.propertyPath }
  48763. ]
  48764. }, parent);
  48765. };
  48766. return SwitchBooleanAction;
  48767. }(BABYLON.Action));
  48768. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  48769. var SetStateAction = /** @class */ (function (_super) {
  48770. __extends(SetStateAction, _super);
  48771. function SetStateAction(triggerOptions, target, value, condition) {
  48772. var _this = _super.call(this, triggerOptions, condition) || this;
  48773. _this.value = value;
  48774. _this._target = target;
  48775. return _this;
  48776. }
  48777. SetStateAction.prototype.execute = function () {
  48778. this._target.state = this.value;
  48779. };
  48780. SetStateAction.prototype.serialize = function (parent) {
  48781. return _super.prototype._serialize.call(this, {
  48782. name: "SetStateAction",
  48783. properties: [
  48784. BABYLON.Action._GetTargetProperty(this._target),
  48785. { name: "value", value: this.value }
  48786. ]
  48787. }, parent);
  48788. };
  48789. return SetStateAction;
  48790. }(BABYLON.Action));
  48791. BABYLON.SetStateAction = SetStateAction;
  48792. var SetValueAction = /** @class */ (function (_super) {
  48793. __extends(SetValueAction, _super);
  48794. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  48795. var _this = _super.call(this, triggerOptions, condition) || this;
  48796. _this.propertyPath = propertyPath;
  48797. _this.value = value;
  48798. _this._target = _this._effectiveTarget = target;
  48799. return _this;
  48800. }
  48801. SetValueAction.prototype._prepare = function () {
  48802. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  48803. this._property = this._getProperty(this.propertyPath);
  48804. };
  48805. SetValueAction.prototype.execute = function () {
  48806. this._effectiveTarget[this._property] = this.value;
  48807. if (this._target.markAsDirty) {
  48808. this._target.markAsDirty(this._property);
  48809. }
  48810. };
  48811. SetValueAction.prototype.serialize = function (parent) {
  48812. return _super.prototype._serialize.call(this, {
  48813. name: "SetValueAction",
  48814. properties: [
  48815. BABYLON.Action._GetTargetProperty(this._target),
  48816. { name: "propertyPath", value: this.propertyPath },
  48817. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  48818. ]
  48819. }, parent);
  48820. };
  48821. return SetValueAction;
  48822. }(BABYLON.Action));
  48823. BABYLON.SetValueAction = SetValueAction;
  48824. var IncrementValueAction = /** @class */ (function (_super) {
  48825. __extends(IncrementValueAction, _super);
  48826. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  48827. var _this = _super.call(this, triggerOptions, condition) || this;
  48828. _this.propertyPath = propertyPath;
  48829. _this.value = value;
  48830. _this._target = _this._effectiveTarget = target;
  48831. return _this;
  48832. }
  48833. IncrementValueAction.prototype._prepare = function () {
  48834. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  48835. this._property = this._getProperty(this.propertyPath);
  48836. if (typeof this._effectiveTarget[this._property] !== "number") {
  48837. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  48838. }
  48839. };
  48840. IncrementValueAction.prototype.execute = function () {
  48841. this._effectiveTarget[this._property] += this.value;
  48842. if (this._target.markAsDirty) {
  48843. this._target.markAsDirty(this._property);
  48844. }
  48845. };
  48846. IncrementValueAction.prototype.serialize = function (parent) {
  48847. return _super.prototype._serialize.call(this, {
  48848. name: "IncrementValueAction",
  48849. properties: [
  48850. BABYLON.Action._GetTargetProperty(this._target),
  48851. { name: "propertyPath", value: this.propertyPath },
  48852. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  48853. ]
  48854. }, parent);
  48855. };
  48856. return IncrementValueAction;
  48857. }(BABYLON.Action));
  48858. BABYLON.IncrementValueAction = IncrementValueAction;
  48859. var PlayAnimationAction = /** @class */ (function (_super) {
  48860. __extends(PlayAnimationAction, _super);
  48861. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  48862. var _this = _super.call(this, triggerOptions, condition) || this;
  48863. _this.from = from;
  48864. _this.to = to;
  48865. _this.loop = loop;
  48866. _this._target = target;
  48867. return _this;
  48868. }
  48869. PlayAnimationAction.prototype._prepare = function () {
  48870. };
  48871. PlayAnimationAction.prototype.execute = function () {
  48872. var scene = this._actionManager.getScene();
  48873. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  48874. };
  48875. PlayAnimationAction.prototype.serialize = function (parent) {
  48876. return _super.prototype._serialize.call(this, {
  48877. name: "PlayAnimationAction",
  48878. properties: [
  48879. BABYLON.Action._GetTargetProperty(this._target),
  48880. { name: "from", value: String(this.from) },
  48881. { name: "to", value: String(this.to) },
  48882. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  48883. ]
  48884. }, parent);
  48885. };
  48886. return PlayAnimationAction;
  48887. }(BABYLON.Action));
  48888. BABYLON.PlayAnimationAction = PlayAnimationAction;
  48889. var StopAnimationAction = /** @class */ (function (_super) {
  48890. __extends(StopAnimationAction, _super);
  48891. function StopAnimationAction(triggerOptions, target, condition) {
  48892. var _this = _super.call(this, triggerOptions, condition) || this;
  48893. _this._target = target;
  48894. return _this;
  48895. }
  48896. StopAnimationAction.prototype._prepare = function () {
  48897. };
  48898. StopAnimationAction.prototype.execute = function () {
  48899. var scene = this._actionManager.getScene();
  48900. scene.stopAnimation(this._target);
  48901. };
  48902. StopAnimationAction.prototype.serialize = function (parent) {
  48903. return _super.prototype._serialize.call(this, {
  48904. name: "StopAnimationAction",
  48905. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  48906. }, parent);
  48907. };
  48908. return StopAnimationAction;
  48909. }(BABYLON.Action));
  48910. BABYLON.StopAnimationAction = StopAnimationAction;
  48911. var DoNothingAction = /** @class */ (function (_super) {
  48912. __extends(DoNothingAction, _super);
  48913. function DoNothingAction(triggerOptions, condition) {
  48914. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  48915. return _super.call(this, triggerOptions, condition) || this;
  48916. }
  48917. DoNothingAction.prototype.execute = function () {
  48918. };
  48919. DoNothingAction.prototype.serialize = function (parent) {
  48920. return _super.prototype._serialize.call(this, {
  48921. name: "DoNothingAction",
  48922. properties: []
  48923. }, parent);
  48924. };
  48925. return DoNothingAction;
  48926. }(BABYLON.Action));
  48927. BABYLON.DoNothingAction = DoNothingAction;
  48928. var CombineAction = /** @class */ (function (_super) {
  48929. __extends(CombineAction, _super);
  48930. function CombineAction(triggerOptions, children, condition) {
  48931. var _this = _super.call(this, triggerOptions, condition) || this;
  48932. _this.children = children;
  48933. return _this;
  48934. }
  48935. CombineAction.prototype._prepare = function () {
  48936. for (var index = 0; index < this.children.length; index++) {
  48937. this.children[index]._actionManager = this._actionManager;
  48938. this.children[index]._prepare();
  48939. }
  48940. };
  48941. CombineAction.prototype.execute = function (evt) {
  48942. for (var index = 0; index < this.children.length; index++) {
  48943. this.children[index].execute(evt);
  48944. }
  48945. };
  48946. CombineAction.prototype.serialize = function (parent) {
  48947. var serializationObject = _super.prototype._serialize.call(this, {
  48948. name: "CombineAction",
  48949. properties: [],
  48950. combine: []
  48951. }, parent);
  48952. for (var i = 0; i < this.children.length; i++) {
  48953. serializationObject.combine.push(this.children[i].serialize(null));
  48954. }
  48955. return serializationObject;
  48956. };
  48957. return CombineAction;
  48958. }(BABYLON.Action));
  48959. BABYLON.CombineAction = CombineAction;
  48960. var ExecuteCodeAction = /** @class */ (function (_super) {
  48961. __extends(ExecuteCodeAction, _super);
  48962. function ExecuteCodeAction(triggerOptions, func, condition) {
  48963. var _this = _super.call(this, triggerOptions, condition) || this;
  48964. _this.func = func;
  48965. return _this;
  48966. }
  48967. ExecuteCodeAction.prototype.execute = function (evt) {
  48968. this.func(evt);
  48969. };
  48970. return ExecuteCodeAction;
  48971. }(BABYLON.Action));
  48972. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  48973. var SetParentAction = /** @class */ (function (_super) {
  48974. __extends(SetParentAction, _super);
  48975. function SetParentAction(triggerOptions, target, parent, condition) {
  48976. var _this = _super.call(this, triggerOptions, condition) || this;
  48977. _this._target = target;
  48978. _this._parent = parent;
  48979. return _this;
  48980. }
  48981. SetParentAction.prototype._prepare = function () {
  48982. };
  48983. SetParentAction.prototype.execute = function () {
  48984. if (this._target.parent === this._parent) {
  48985. return;
  48986. }
  48987. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  48988. invertParentWorldMatrix.invert();
  48989. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  48990. this._target.parent = this._parent;
  48991. };
  48992. SetParentAction.prototype.serialize = function (parent) {
  48993. return _super.prototype._serialize.call(this, {
  48994. name: "SetParentAction",
  48995. properties: [
  48996. BABYLON.Action._GetTargetProperty(this._target),
  48997. BABYLON.Action._GetTargetProperty(this._parent),
  48998. ]
  48999. }, parent);
  49000. };
  49001. return SetParentAction;
  49002. }(BABYLON.Action));
  49003. BABYLON.SetParentAction = SetParentAction;
  49004. var PlaySoundAction = /** @class */ (function (_super) {
  49005. __extends(PlaySoundAction, _super);
  49006. function PlaySoundAction(triggerOptions, sound, condition) {
  49007. var _this = _super.call(this, triggerOptions, condition) || this;
  49008. _this._sound = sound;
  49009. return _this;
  49010. }
  49011. PlaySoundAction.prototype._prepare = function () {
  49012. };
  49013. PlaySoundAction.prototype.execute = function () {
  49014. if (this._sound !== undefined)
  49015. this._sound.play();
  49016. };
  49017. PlaySoundAction.prototype.serialize = function (parent) {
  49018. return _super.prototype._serialize.call(this, {
  49019. name: "PlaySoundAction",
  49020. properties: [{ name: "sound", value: this._sound.name }]
  49021. }, parent);
  49022. };
  49023. return PlaySoundAction;
  49024. }(BABYLON.Action));
  49025. BABYLON.PlaySoundAction = PlaySoundAction;
  49026. var StopSoundAction = /** @class */ (function (_super) {
  49027. __extends(StopSoundAction, _super);
  49028. function StopSoundAction(triggerOptions, sound, condition) {
  49029. var _this = _super.call(this, triggerOptions, condition) || this;
  49030. _this._sound = sound;
  49031. return _this;
  49032. }
  49033. StopSoundAction.prototype._prepare = function () {
  49034. };
  49035. StopSoundAction.prototype.execute = function () {
  49036. if (this._sound !== undefined)
  49037. this._sound.stop();
  49038. };
  49039. StopSoundAction.prototype.serialize = function (parent) {
  49040. return _super.prototype._serialize.call(this, {
  49041. name: "StopSoundAction",
  49042. properties: [{ name: "sound", value: this._sound.name }]
  49043. }, parent);
  49044. };
  49045. return StopSoundAction;
  49046. }(BABYLON.Action));
  49047. BABYLON.StopSoundAction = StopSoundAction;
  49048. })(BABYLON || (BABYLON = {}));
  49049. //# sourceMappingURL=babylon.directActions.js.map
  49050. var BABYLON;
  49051. (function (BABYLON) {
  49052. var SpriteManager = /** @class */ (function () {
  49053. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  49054. if (epsilon === void 0) { epsilon = 0.01; }
  49055. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  49056. this.name = name;
  49057. this.sprites = new Array();
  49058. this.renderingGroupId = 0;
  49059. this.layerMask = 0x0FFFFFFF;
  49060. this.fogEnabled = true;
  49061. this.isPickable = false;
  49062. /**
  49063. * An event triggered when the manager is disposed.
  49064. * @type {BABYLON.Observable}
  49065. */
  49066. this.onDisposeObservable = new BABYLON.Observable();
  49067. this._vertexBuffers = {};
  49068. this._capacity = capacity;
  49069. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  49070. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  49071. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  49072. if (cellSize.width && cellSize.height) {
  49073. this.cellWidth = cellSize.width;
  49074. this.cellHeight = cellSize.height;
  49075. }
  49076. else if (cellSize !== undefined) {
  49077. this.cellWidth = cellSize;
  49078. this.cellHeight = cellSize;
  49079. }
  49080. else {
  49081. return;
  49082. }
  49083. this._epsilon = epsilon;
  49084. this._scene = scene;
  49085. this._scene.spriteManagers.push(this);
  49086. var indices = [];
  49087. var index = 0;
  49088. for (var count = 0; count < capacity; count++) {
  49089. indices.push(index);
  49090. indices.push(index + 1);
  49091. indices.push(index + 2);
  49092. indices.push(index);
  49093. indices.push(index + 2);
  49094. indices.push(index + 3);
  49095. index += 4;
  49096. }
  49097. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  49098. // VBO
  49099. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  49100. this._vertexData = new Float32Array(capacity * 16 * 4);
  49101. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  49102. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  49103. var options = this._buffer.createVertexBuffer("options", 4, 4);
  49104. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  49105. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  49106. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  49107. this._vertexBuffers["options"] = options;
  49108. this._vertexBuffers["cellInfo"] = cellInfo;
  49109. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  49110. // Effects
  49111. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  49112. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  49113. }
  49114. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  49115. set: function (callback) {
  49116. if (this._onDisposeObserver) {
  49117. this.onDisposeObservable.remove(this._onDisposeObserver);
  49118. }
  49119. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  49120. },
  49121. enumerable: true,
  49122. configurable: true
  49123. });
  49124. Object.defineProperty(SpriteManager.prototype, "texture", {
  49125. get: function () {
  49126. return this._spriteTexture;
  49127. },
  49128. set: function (value) {
  49129. this._spriteTexture = value;
  49130. },
  49131. enumerable: true,
  49132. configurable: true
  49133. });
  49134. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  49135. var arrayOffset = index * 16;
  49136. if (offsetX === 0)
  49137. offsetX = this._epsilon;
  49138. else if (offsetX === 1)
  49139. offsetX = 1 - this._epsilon;
  49140. if (offsetY === 0)
  49141. offsetY = this._epsilon;
  49142. else if (offsetY === 1)
  49143. offsetY = 1 - this._epsilon;
  49144. this._vertexData[arrayOffset] = sprite.position.x;
  49145. this._vertexData[arrayOffset + 1] = sprite.position.y;
  49146. this._vertexData[arrayOffset + 2] = sprite.position.z;
  49147. this._vertexData[arrayOffset + 3] = sprite.angle;
  49148. this._vertexData[arrayOffset + 4] = sprite.width;
  49149. this._vertexData[arrayOffset + 5] = sprite.height;
  49150. this._vertexData[arrayOffset + 6] = offsetX;
  49151. this._vertexData[arrayOffset + 7] = offsetY;
  49152. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  49153. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  49154. var offset = (sprite.cellIndex / rowSize) >> 0;
  49155. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  49156. this._vertexData[arrayOffset + 11] = offset;
  49157. // Color
  49158. this._vertexData[arrayOffset + 12] = sprite.color.r;
  49159. this._vertexData[arrayOffset + 13] = sprite.color.g;
  49160. this._vertexData[arrayOffset + 14] = sprite.color.b;
  49161. this._vertexData[arrayOffset + 15] = sprite.color.a;
  49162. };
  49163. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  49164. var count = Math.min(this._capacity, this.sprites.length);
  49165. var min = BABYLON.Vector3.Zero();
  49166. var max = BABYLON.Vector3.Zero();
  49167. var distance = Number.MAX_VALUE;
  49168. var currentSprite = null;
  49169. var cameraSpacePosition = BABYLON.Vector3.Zero();
  49170. var cameraView = camera.getViewMatrix();
  49171. for (var index = 0; index < count; index++) {
  49172. var sprite = this.sprites[index];
  49173. if (!sprite) {
  49174. continue;
  49175. }
  49176. if (predicate) {
  49177. if (!predicate(sprite)) {
  49178. continue;
  49179. }
  49180. }
  49181. else if (!sprite.isPickable) {
  49182. continue;
  49183. }
  49184. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  49185. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  49186. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  49187. if (ray.intersectsBoxMinMax(min, max)) {
  49188. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  49189. if (distance > currentDistance) {
  49190. distance = currentDistance;
  49191. currentSprite = sprite;
  49192. if (fastCheck) {
  49193. break;
  49194. }
  49195. }
  49196. }
  49197. }
  49198. if (currentSprite) {
  49199. var result = new BABYLON.PickingInfo();
  49200. result.hit = true;
  49201. result.pickedSprite = currentSprite;
  49202. result.distance = distance;
  49203. return result;
  49204. }
  49205. return null;
  49206. };
  49207. SpriteManager.prototype.render = function () {
  49208. // Check
  49209. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  49210. return;
  49211. var engine = this._scene.getEngine();
  49212. var baseSize = this._spriteTexture.getBaseSize();
  49213. // Sprites
  49214. var deltaTime = engine.getDeltaTime();
  49215. var max = Math.min(this._capacity, this.sprites.length);
  49216. var rowSize = baseSize.width / this.cellWidth;
  49217. var offset = 0;
  49218. for (var index = 0; index < max; index++) {
  49219. var sprite = this.sprites[index];
  49220. if (!sprite) {
  49221. continue;
  49222. }
  49223. sprite._animate(deltaTime);
  49224. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  49225. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  49226. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  49227. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  49228. }
  49229. this._buffer.update(this._vertexData);
  49230. // Render
  49231. var effect = this._effectBase;
  49232. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  49233. effect = this._effectFog;
  49234. }
  49235. engine.enableEffect(effect);
  49236. var viewMatrix = this._scene.getViewMatrix();
  49237. effect.setTexture("diffuseSampler", this._spriteTexture);
  49238. effect.setMatrix("view", viewMatrix);
  49239. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  49240. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  49241. // Fog
  49242. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  49243. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  49244. effect.setColor3("vFogColor", this._scene.fogColor);
  49245. }
  49246. // VBOs
  49247. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  49248. // Draw order
  49249. engine.setDepthFunctionToLessOrEqual();
  49250. effect.setBool("alphaTest", true);
  49251. engine.setColorWrite(false);
  49252. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  49253. engine.setColorWrite(true);
  49254. effect.setBool("alphaTest", false);
  49255. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  49256. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  49257. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  49258. };
  49259. SpriteManager.prototype.dispose = function () {
  49260. if (this._buffer) {
  49261. this._buffer.dispose();
  49262. this._buffer = null;
  49263. }
  49264. if (this._indexBuffer) {
  49265. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  49266. this._indexBuffer = null;
  49267. }
  49268. if (this._spriteTexture) {
  49269. this._spriteTexture.dispose();
  49270. this._spriteTexture = null;
  49271. }
  49272. // Remove from scene
  49273. var index = this._scene.spriteManagers.indexOf(this);
  49274. this._scene.spriteManagers.splice(index, 1);
  49275. // Callback
  49276. this.onDisposeObservable.notifyObservers(this);
  49277. this.onDisposeObservable.clear();
  49278. };
  49279. return SpriteManager;
  49280. }());
  49281. BABYLON.SpriteManager = SpriteManager;
  49282. })(BABYLON || (BABYLON = {}));
  49283. //# sourceMappingURL=babylon.spriteManager.js.map
  49284. var BABYLON;
  49285. (function (BABYLON) {
  49286. var Sprite = /** @class */ (function () {
  49287. function Sprite(name, manager) {
  49288. this.name = name;
  49289. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  49290. this.width = 1.0;
  49291. this.height = 1.0;
  49292. this.angle = 0;
  49293. this.cellIndex = 0;
  49294. this.invertU = 0;
  49295. this.invertV = 0;
  49296. this.animations = new Array();
  49297. this.isPickable = false;
  49298. this._animationStarted = false;
  49299. this._loopAnimation = false;
  49300. this._fromIndex = 0;
  49301. this._toIndex = 0;
  49302. this._delay = 0;
  49303. this._direction = 1;
  49304. this._time = 0;
  49305. this._manager = manager;
  49306. this._manager.sprites.push(this);
  49307. this.position = BABYLON.Vector3.Zero();
  49308. }
  49309. Object.defineProperty(Sprite.prototype, "size", {
  49310. get: function () {
  49311. return this.width;
  49312. },
  49313. set: function (value) {
  49314. this.width = value;
  49315. this.height = value;
  49316. },
  49317. enumerable: true,
  49318. configurable: true
  49319. });
  49320. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  49321. this._fromIndex = from;
  49322. this._toIndex = to;
  49323. this._loopAnimation = loop;
  49324. this._delay = delay;
  49325. this._animationStarted = true;
  49326. this._direction = from < to ? 1 : -1;
  49327. this.cellIndex = from;
  49328. this._time = 0;
  49329. this._onAnimationEnd = onAnimationEnd;
  49330. };
  49331. Sprite.prototype.stopAnimation = function () {
  49332. this._animationStarted = false;
  49333. };
  49334. Sprite.prototype._animate = function (deltaTime) {
  49335. if (!this._animationStarted)
  49336. return;
  49337. this._time += deltaTime;
  49338. if (this._time > this._delay) {
  49339. this._time = this._time % this._delay;
  49340. this.cellIndex += this._direction;
  49341. if (this.cellIndex > this._toIndex) {
  49342. if (this._loopAnimation) {
  49343. this.cellIndex = this._fromIndex;
  49344. }
  49345. else {
  49346. this.cellIndex = this._toIndex;
  49347. this._animationStarted = false;
  49348. if (this._onAnimationEnd) {
  49349. this._onAnimationEnd();
  49350. }
  49351. if (this.disposeWhenFinishedAnimating) {
  49352. this.dispose();
  49353. }
  49354. }
  49355. }
  49356. }
  49357. };
  49358. Sprite.prototype.dispose = function () {
  49359. for (var i = 0; i < this._manager.sprites.length; i++) {
  49360. if (this._manager.sprites[i] == this) {
  49361. this._manager.sprites.splice(i, 1);
  49362. }
  49363. }
  49364. };
  49365. return Sprite;
  49366. }());
  49367. BABYLON.Sprite = Sprite;
  49368. })(BABYLON || (BABYLON = {}));
  49369. //# sourceMappingURL=babylon.sprite.js.map
  49370. var BABYLON;
  49371. (function (BABYLON) {
  49372. var IntersectionInfo = /** @class */ (function () {
  49373. function IntersectionInfo(bu, bv, distance) {
  49374. this.bu = bu;
  49375. this.bv = bv;
  49376. this.distance = distance;
  49377. this.faceId = 0;
  49378. this.subMeshId = 0;
  49379. }
  49380. return IntersectionInfo;
  49381. }());
  49382. BABYLON.IntersectionInfo = IntersectionInfo;
  49383. var PickingInfo = /** @class */ (function () {
  49384. function PickingInfo() {
  49385. this.hit = false;
  49386. this.distance = 0;
  49387. this.pickedPoint = null;
  49388. this.pickedMesh = null;
  49389. this.bu = 0;
  49390. this.bv = 0;
  49391. this.faceId = -1;
  49392. this.subMeshId = 0;
  49393. this.pickedSprite = null;
  49394. }
  49395. // Methods
  49396. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  49397. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  49398. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  49399. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  49400. return null;
  49401. }
  49402. var indices = this.pickedMesh.getIndices();
  49403. if (!indices) {
  49404. return null;
  49405. }
  49406. var result;
  49407. if (useVerticesNormals) {
  49408. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  49409. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  49410. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  49411. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  49412. normal0 = normal0.scale(this.bu);
  49413. normal1 = normal1.scale(this.bv);
  49414. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  49415. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  49416. }
  49417. else {
  49418. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  49419. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  49420. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  49421. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  49422. var p1p2 = vertex1.subtract(vertex2);
  49423. var p3p2 = vertex3.subtract(vertex2);
  49424. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  49425. }
  49426. if (useWorldCoordinates) {
  49427. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  49428. }
  49429. return BABYLON.Vector3.Normalize(result);
  49430. };
  49431. PickingInfo.prototype.getTextureCoordinates = function () {
  49432. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  49433. return null;
  49434. }
  49435. var indices = this.pickedMesh.getIndices();
  49436. if (!indices) {
  49437. return null;
  49438. }
  49439. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  49440. if (!uvs) {
  49441. return null;
  49442. }
  49443. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  49444. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  49445. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  49446. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  49447. uv1 = uv1.scale(this.bu);
  49448. uv2 = uv2.scale(this.bv);
  49449. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  49450. };
  49451. return PickingInfo;
  49452. }());
  49453. BABYLON.PickingInfo = PickingInfo;
  49454. })(BABYLON || (BABYLON = {}));
  49455. //# sourceMappingURL=babylon.pickingInfo.js.map
  49456. var BABYLON;
  49457. (function (BABYLON) {
  49458. var Ray = /** @class */ (function () {
  49459. function Ray(origin, direction, length) {
  49460. if (length === void 0) { length = Number.MAX_VALUE; }
  49461. this.origin = origin;
  49462. this.direction = direction;
  49463. this.length = length;
  49464. }
  49465. // Methods
  49466. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  49467. var d = 0.0;
  49468. var maxValue = Number.MAX_VALUE;
  49469. var inv;
  49470. var min;
  49471. var max;
  49472. var temp;
  49473. if (Math.abs(this.direction.x) < 0.0000001) {
  49474. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  49475. return false;
  49476. }
  49477. }
  49478. else {
  49479. inv = 1.0 / this.direction.x;
  49480. min = (minimum.x - this.origin.x) * inv;
  49481. max = (maximum.x - this.origin.x) * inv;
  49482. if (max === -Infinity) {
  49483. max = Infinity;
  49484. }
  49485. if (min > max) {
  49486. temp = min;
  49487. min = max;
  49488. max = temp;
  49489. }
  49490. d = Math.max(min, d);
  49491. maxValue = Math.min(max, maxValue);
  49492. if (d > maxValue) {
  49493. return false;
  49494. }
  49495. }
  49496. if (Math.abs(this.direction.y) < 0.0000001) {
  49497. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  49498. return false;
  49499. }
  49500. }
  49501. else {
  49502. inv = 1.0 / this.direction.y;
  49503. min = (minimum.y - this.origin.y) * inv;
  49504. max = (maximum.y - this.origin.y) * inv;
  49505. if (max === -Infinity) {
  49506. max = Infinity;
  49507. }
  49508. if (min > max) {
  49509. temp = min;
  49510. min = max;
  49511. max = temp;
  49512. }
  49513. d = Math.max(min, d);
  49514. maxValue = Math.min(max, maxValue);
  49515. if (d > maxValue) {
  49516. return false;
  49517. }
  49518. }
  49519. if (Math.abs(this.direction.z) < 0.0000001) {
  49520. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  49521. return false;
  49522. }
  49523. }
  49524. else {
  49525. inv = 1.0 / this.direction.z;
  49526. min = (minimum.z - this.origin.z) * inv;
  49527. max = (maximum.z - this.origin.z) * inv;
  49528. if (max === -Infinity) {
  49529. max = Infinity;
  49530. }
  49531. if (min > max) {
  49532. temp = min;
  49533. min = max;
  49534. max = temp;
  49535. }
  49536. d = Math.max(min, d);
  49537. maxValue = Math.min(max, maxValue);
  49538. if (d > maxValue) {
  49539. return false;
  49540. }
  49541. }
  49542. return true;
  49543. };
  49544. Ray.prototype.intersectsBox = function (box) {
  49545. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  49546. };
  49547. Ray.prototype.intersectsSphere = function (sphere) {
  49548. var x = sphere.center.x - this.origin.x;
  49549. var y = sphere.center.y - this.origin.y;
  49550. var z = sphere.center.z - this.origin.z;
  49551. var pyth = (x * x) + (y * y) + (z * z);
  49552. var rr = sphere.radius * sphere.radius;
  49553. if (pyth <= rr) {
  49554. return true;
  49555. }
  49556. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  49557. if (dot < 0.0) {
  49558. return false;
  49559. }
  49560. var temp = pyth - (dot * dot);
  49561. return temp <= rr;
  49562. };
  49563. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  49564. if (!this._edge1) {
  49565. this._edge1 = BABYLON.Vector3.Zero();
  49566. this._edge2 = BABYLON.Vector3.Zero();
  49567. this._pvec = BABYLON.Vector3.Zero();
  49568. this._tvec = BABYLON.Vector3.Zero();
  49569. this._qvec = BABYLON.Vector3.Zero();
  49570. }
  49571. vertex1.subtractToRef(vertex0, this._edge1);
  49572. vertex2.subtractToRef(vertex0, this._edge2);
  49573. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  49574. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  49575. if (det === 0) {
  49576. return null;
  49577. }
  49578. var invdet = 1 / det;
  49579. this.origin.subtractToRef(vertex0, this._tvec);
  49580. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  49581. if (bu < 0 || bu > 1.0) {
  49582. return null;
  49583. }
  49584. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  49585. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  49586. if (bv < 0 || bu + bv > 1.0) {
  49587. return null;
  49588. }
  49589. //check if the distance is longer than the predefined length.
  49590. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  49591. if (distance > this.length) {
  49592. return null;
  49593. }
  49594. return new BABYLON.IntersectionInfo(bu, bv, distance);
  49595. };
  49596. Ray.prototype.intersectsPlane = function (plane) {
  49597. var distance;
  49598. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  49599. if (Math.abs(result1) < 9.99999997475243E-07) {
  49600. return null;
  49601. }
  49602. else {
  49603. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  49604. distance = (-plane.d - result2) / result1;
  49605. if (distance < 0.0) {
  49606. if (distance < -9.99999997475243E-07) {
  49607. return null;
  49608. }
  49609. else {
  49610. return 0;
  49611. }
  49612. }
  49613. return distance;
  49614. }
  49615. };
  49616. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  49617. var tm = BABYLON.Tmp.Matrix[0];
  49618. mesh.getWorldMatrix().invertToRef(tm);
  49619. if (this._tmpRay) {
  49620. Ray.TransformToRef(this, tm, this._tmpRay);
  49621. }
  49622. else {
  49623. this._tmpRay = Ray.Transform(this, tm);
  49624. }
  49625. return mesh.intersects(this._tmpRay, fastCheck);
  49626. };
  49627. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  49628. if (results) {
  49629. results.length = 0;
  49630. }
  49631. else {
  49632. results = [];
  49633. }
  49634. for (var i = 0; i < meshes.length; i++) {
  49635. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  49636. if (pickInfo.hit) {
  49637. results.push(pickInfo);
  49638. }
  49639. }
  49640. results.sort(this._comparePickingInfo);
  49641. return results;
  49642. };
  49643. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  49644. if (pickingInfoA.distance < pickingInfoB.distance) {
  49645. return -1;
  49646. }
  49647. else if (pickingInfoA.distance > pickingInfoB.distance) {
  49648. return 1;
  49649. }
  49650. else {
  49651. return 0;
  49652. }
  49653. };
  49654. /**
  49655. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  49656. * @param sega the first point of the segment to test the intersection against
  49657. * @param segb the second point of the segment to test the intersection against
  49658. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  49659. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  49660. */
  49661. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  49662. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  49663. var u = segb.subtract(sega);
  49664. var v = rsegb.subtract(this.origin);
  49665. var w = sega.subtract(this.origin);
  49666. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  49667. var b = BABYLON.Vector3.Dot(u, v);
  49668. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  49669. var d = BABYLON.Vector3.Dot(u, w);
  49670. var e = BABYLON.Vector3.Dot(v, w);
  49671. var D = a * c - b * b; // always >= 0
  49672. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  49673. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  49674. // compute the line parameters of the two closest points
  49675. if (D < Ray.smallnum) {
  49676. sN = 0.0; // force using point P0 on segment S1
  49677. sD = 1.0; // to prevent possible division by 0.0 later
  49678. tN = e;
  49679. tD = c;
  49680. }
  49681. else {
  49682. sN = (b * e - c * d);
  49683. tN = (a * e - b * d);
  49684. if (sN < 0.0) {
  49685. sN = 0.0;
  49686. tN = e;
  49687. tD = c;
  49688. }
  49689. else if (sN > sD) {
  49690. sN = sD;
  49691. tN = e + b;
  49692. tD = c;
  49693. }
  49694. }
  49695. if (tN < 0.0) {
  49696. tN = 0.0;
  49697. // recompute sc for this edge
  49698. if (-d < 0.0) {
  49699. sN = 0.0;
  49700. }
  49701. else if (-d > a)
  49702. sN = sD;
  49703. else {
  49704. sN = -d;
  49705. sD = a;
  49706. }
  49707. }
  49708. else if (tN > tD) {
  49709. tN = tD;
  49710. // recompute sc for this edge
  49711. if ((-d + b) < 0.0) {
  49712. sN = 0;
  49713. }
  49714. else if ((-d + b) > a) {
  49715. sN = sD;
  49716. }
  49717. else {
  49718. sN = (-d + b);
  49719. sD = a;
  49720. }
  49721. }
  49722. // finally do the division to get sc and tc
  49723. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  49724. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  49725. // get the difference of the two closest points
  49726. var qtc = v.multiplyByFloats(tc, tc, tc);
  49727. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  49728. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  49729. if (isIntersected) {
  49730. return qtc.length();
  49731. }
  49732. return -1;
  49733. };
  49734. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  49735. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  49736. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  49737. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  49738. this.direction.normalize();
  49739. return this;
  49740. };
  49741. // Statics
  49742. Ray.Zero = function () {
  49743. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  49744. };
  49745. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  49746. var result = Ray.Zero();
  49747. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  49748. };
  49749. /**
  49750. * 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
  49751. * transformed to the given world matrix.
  49752. * @param origin The origin point
  49753. * @param end The end point
  49754. * @param world a matrix to transform the ray to. Default is the identity matrix.
  49755. */
  49756. Ray.CreateNewFromTo = function (origin, end, world) {
  49757. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  49758. var direction = end.subtract(origin);
  49759. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  49760. direction.normalize();
  49761. return Ray.Transform(new Ray(origin, direction, length), world);
  49762. };
  49763. Ray.Transform = function (ray, matrix) {
  49764. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  49765. Ray.TransformToRef(ray, matrix, result);
  49766. return result;
  49767. };
  49768. Ray.TransformToRef = function (ray, matrix, result) {
  49769. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  49770. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  49771. result.length = ray.length;
  49772. var dir = result.direction;
  49773. var len = dir.length();
  49774. if (!(len === 0 || len === 1)) {
  49775. var num = 1.0 / len;
  49776. dir.x *= num;
  49777. dir.y *= num;
  49778. dir.z *= num;
  49779. result.length *= len;
  49780. }
  49781. };
  49782. Ray.smallnum = 0.00000001;
  49783. Ray.rayl = 10e8;
  49784. return Ray;
  49785. }());
  49786. BABYLON.Ray = Ray;
  49787. })(BABYLON || (BABYLON = {}));
  49788. //# sourceMappingURL=babylon.ray.js.map
  49789. var BABYLON;
  49790. (function (BABYLON) {
  49791. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  49792. if (boxMin.x > sphereCenter.x + sphereRadius)
  49793. return false;
  49794. if (sphereCenter.x - sphereRadius > boxMax.x)
  49795. return false;
  49796. if (boxMin.y > sphereCenter.y + sphereRadius)
  49797. return false;
  49798. if (sphereCenter.y - sphereRadius > boxMax.y)
  49799. return false;
  49800. if (boxMin.z > sphereCenter.z + sphereRadius)
  49801. return false;
  49802. if (sphereCenter.z - sphereRadius > boxMax.z)
  49803. return false;
  49804. return true;
  49805. };
  49806. var getLowestRoot = (function () {
  49807. var result = { root: 0, found: false };
  49808. return function (a, b, c, maxR) {
  49809. result.root = 0;
  49810. result.found = false;
  49811. var determinant = b * b - 4.0 * a * c;
  49812. if (determinant < 0)
  49813. return result;
  49814. var sqrtD = Math.sqrt(determinant);
  49815. var r1 = (-b - sqrtD) / (2.0 * a);
  49816. var r2 = (-b + sqrtD) / (2.0 * a);
  49817. if (r1 > r2) {
  49818. var temp = r2;
  49819. r2 = r1;
  49820. r1 = temp;
  49821. }
  49822. if (r1 > 0 && r1 < maxR) {
  49823. result.root = r1;
  49824. result.found = true;
  49825. return result;
  49826. }
  49827. if (r2 > 0 && r2 < maxR) {
  49828. result.root = r2;
  49829. result.found = true;
  49830. return result;
  49831. }
  49832. return result;
  49833. };
  49834. })();
  49835. var Collider = /** @class */ (function () {
  49836. function Collider() {
  49837. this._collisionPoint = BABYLON.Vector3.Zero();
  49838. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  49839. this._tempVector = BABYLON.Vector3.Zero();
  49840. this._tempVector2 = BABYLON.Vector3.Zero();
  49841. this._tempVector3 = BABYLON.Vector3.Zero();
  49842. this._tempVector4 = BABYLON.Vector3.Zero();
  49843. this._edge = BABYLON.Vector3.Zero();
  49844. this._baseToVertex = BABYLON.Vector3.Zero();
  49845. this._destinationPoint = BABYLON.Vector3.Zero();
  49846. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  49847. this._displacementVector = BABYLON.Vector3.Zero();
  49848. this._radius = BABYLON.Vector3.One();
  49849. this._retry = 0;
  49850. this._basePointWorld = BABYLON.Vector3.Zero();
  49851. this._velocityWorld = BABYLON.Vector3.Zero();
  49852. this._normalizedVelocity = BABYLON.Vector3.Zero();
  49853. this._collisionMask = -1;
  49854. }
  49855. Object.defineProperty(Collider.prototype, "collisionMask", {
  49856. get: function () {
  49857. return this._collisionMask;
  49858. },
  49859. set: function (mask) {
  49860. this._collisionMask = !isNaN(mask) ? mask : -1;
  49861. },
  49862. enumerable: true,
  49863. configurable: true
  49864. });
  49865. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  49866. /**
  49867. * Gets the plane normal used to compute the sliding response (in local space)
  49868. */
  49869. get: function () {
  49870. return this._slidePlaneNormal;
  49871. },
  49872. enumerable: true,
  49873. configurable: true
  49874. });
  49875. // Methods
  49876. Collider.prototype._initialize = function (source, dir, e) {
  49877. this._velocity = dir;
  49878. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  49879. this._basePoint = source;
  49880. source.multiplyToRef(this._radius, this._basePointWorld);
  49881. dir.multiplyToRef(this._radius, this._velocityWorld);
  49882. this._velocityWorldLength = this._velocityWorld.length();
  49883. this._epsilon = e;
  49884. this.collisionFound = false;
  49885. };
  49886. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  49887. pa.subtractToRef(point, this._tempVector);
  49888. pb.subtractToRef(point, this._tempVector2);
  49889. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  49890. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  49891. if (d < 0)
  49892. return false;
  49893. pc.subtractToRef(point, this._tempVector3);
  49894. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  49895. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  49896. if (d < 0)
  49897. return false;
  49898. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  49899. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  49900. return d >= 0;
  49901. };
  49902. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  49903. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  49904. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  49905. if (distance > this._velocityWorldLength + max + sphereRadius) {
  49906. return false;
  49907. }
  49908. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  49909. return false;
  49910. return true;
  49911. };
  49912. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  49913. var t0;
  49914. var embeddedInPlane = false;
  49915. //defensive programming, actually not needed.
  49916. if (!trianglePlaneArray) {
  49917. trianglePlaneArray = [];
  49918. }
  49919. if (!trianglePlaneArray[faceIndex]) {
  49920. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  49921. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  49922. }
  49923. var trianglePlane = trianglePlaneArray[faceIndex];
  49924. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  49925. return;
  49926. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  49927. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  49928. if (normalDotVelocity == 0) {
  49929. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  49930. return;
  49931. embeddedInPlane = true;
  49932. t0 = 0;
  49933. }
  49934. else {
  49935. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  49936. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  49937. if (t0 > t1) {
  49938. var temp = t1;
  49939. t1 = t0;
  49940. t0 = temp;
  49941. }
  49942. if (t0 > 1.0 || t1 < 0.0)
  49943. return;
  49944. if (t0 < 0)
  49945. t0 = 0;
  49946. if (t0 > 1.0)
  49947. t0 = 1.0;
  49948. }
  49949. this._collisionPoint.copyFromFloats(0, 0, 0);
  49950. var found = false;
  49951. var t = 1.0;
  49952. if (!embeddedInPlane) {
  49953. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  49954. this._velocity.scaleToRef(t0, this._tempVector);
  49955. this._planeIntersectionPoint.addInPlace(this._tempVector);
  49956. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  49957. found = true;
  49958. t = t0;
  49959. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  49960. }
  49961. }
  49962. if (!found) {
  49963. var velocitySquaredLength = this._velocity.lengthSquared();
  49964. var a = velocitySquaredLength;
  49965. this._basePoint.subtractToRef(p1, this._tempVector);
  49966. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  49967. var c = this._tempVector.lengthSquared() - 1.0;
  49968. var lowestRoot = getLowestRoot(a, b, c, t);
  49969. if (lowestRoot.found) {
  49970. t = lowestRoot.root;
  49971. found = true;
  49972. this._collisionPoint.copyFrom(p1);
  49973. }
  49974. this._basePoint.subtractToRef(p2, this._tempVector);
  49975. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  49976. c = this._tempVector.lengthSquared() - 1.0;
  49977. lowestRoot = getLowestRoot(a, b, c, t);
  49978. if (lowestRoot.found) {
  49979. t = lowestRoot.root;
  49980. found = true;
  49981. this._collisionPoint.copyFrom(p2);
  49982. }
  49983. this._basePoint.subtractToRef(p3, this._tempVector);
  49984. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  49985. c = this._tempVector.lengthSquared() - 1.0;
  49986. lowestRoot = getLowestRoot(a, b, c, t);
  49987. if (lowestRoot.found) {
  49988. t = lowestRoot.root;
  49989. found = true;
  49990. this._collisionPoint.copyFrom(p3);
  49991. }
  49992. p2.subtractToRef(p1, this._edge);
  49993. p1.subtractToRef(this._basePoint, this._baseToVertex);
  49994. var edgeSquaredLength = this._edge.lengthSquared();
  49995. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  49996. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  49997. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  49998. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  49999. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  50000. lowestRoot = getLowestRoot(a, b, c, t);
  50001. if (lowestRoot.found) {
  50002. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  50003. if (f >= 0.0 && f <= 1.0) {
  50004. t = lowestRoot.root;
  50005. found = true;
  50006. this._edge.scaleInPlace(f);
  50007. p1.addToRef(this._edge, this._collisionPoint);
  50008. }
  50009. }
  50010. p3.subtractToRef(p2, this._edge);
  50011. p2.subtractToRef(this._basePoint, this._baseToVertex);
  50012. edgeSquaredLength = this._edge.lengthSquared();
  50013. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  50014. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  50015. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  50016. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  50017. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  50018. lowestRoot = getLowestRoot(a, b, c, t);
  50019. if (lowestRoot.found) {
  50020. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  50021. if (f >= 0.0 && f <= 1.0) {
  50022. t = lowestRoot.root;
  50023. found = true;
  50024. this._edge.scaleInPlace(f);
  50025. p2.addToRef(this._edge, this._collisionPoint);
  50026. }
  50027. }
  50028. p1.subtractToRef(p3, this._edge);
  50029. p3.subtractToRef(this._basePoint, this._baseToVertex);
  50030. edgeSquaredLength = this._edge.lengthSquared();
  50031. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  50032. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  50033. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  50034. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  50035. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  50036. lowestRoot = getLowestRoot(a, b, c, t);
  50037. if (lowestRoot.found) {
  50038. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  50039. if (f >= 0.0 && f <= 1.0) {
  50040. t = lowestRoot.root;
  50041. found = true;
  50042. this._edge.scaleInPlace(f);
  50043. p3.addToRef(this._edge, this._collisionPoint);
  50044. }
  50045. }
  50046. }
  50047. if (found) {
  50048. var distToCollision = t * this._velocity.length();
  50049. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  50050. if (!this.intersectionPoint) {
  50051. this.intersectionPoint = this._collisionPoint.clone();
  50052. }
  50053. else {
  50054. this.intersectionPoint.copyFrom(this._collisionPoint);
  50055. }
  50056. this._nearestDistance = distToCollision;
  50057. this.collisionFound = true;
  50058. }
  50059. }
  50060. };
  50061. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  50062. for (var i = indexStart; i < indexEnd; i += 3) {
  50063. var p1 = pts[indices[i] - decal];
  50064. var p2 = pts[indices[i + 1] - decal];
  50065. var p3 = pts[indices[i + 2] - decal];
  50066. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  50067. }
  50068. };
  50069. Collider.prototype._getResponse = function (pos, vel) {
  50070. pos.addToRef(vel, this._destinationPoint);
  50071. vel.scaleInPlace((this._nearestDistance / vel.length()));
  50072. this._basePoint.addToRef(vel, pos);
  50073. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  50074. this._slidePlaneNormal.normalize();
  50075. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  50076. pos.addInPlace(this._displacementVector);
  50077. this.intersectionPoint.addInPlace(this._displacementVector);
  50078. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  50079. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  50080. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  50081. };
  50082. return Collider;
  50083. }());
  50084. BABYLON.Collider = Collider;
  50085. })(BABYLON || (BABYLON = {}));
  50086. //# sourceMappingURL=babylon.collider.js.map
  50087. var BABYLON;
  50088. (function (BABYLON) {
  50089. //WebWorker code will be inserted to this variable.
  50090. BABYLON.CollisionWorker = "";
  50091. var WorkerTaskType;
  50092. (function (WorkerTaskType) {
  50093. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  50094. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  50095. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  50096. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  50097. var WorkerReplyType;
  50098. (function (WorkerReplyType) {
  50099. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  50100. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  50101. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  50102. var CollisionCoordinatorWorker = /** @class */ (function () {
  50103. function CollisionCoordinatorWorker() {
  50104. var _this = this;
  50105. this._scaledPosition = BABYLON.Vector3.Zero();
  50106. this._scaledVelocity = BABYLON.Vector3.Zero();
  50107. this.onMeshUpdated = function (transformNode) {
  50108. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  50109. };
  50110. this.onGeometryUpdated = function (geometry) {
  50111. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  50112. };
  50113. this._afterRender = function () {
  50114. if (!_this._init)
  50115. return;
  50116. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  50117. return;
  50118. }
  50119. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  50120. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  50121. if (_this._runningUpdated > 4) {
  50122. return;
  50123. }
  50124. ++_this._runningUpdated;
  50125. var payload = {
  50126. updatedMeshes: _this._addUpdateMeshesList,
  50127. updatedGeometries: _this._addUpdateGeometriesList,
  50128. removedGeometries: _this._toRemoveGeometryArray,
  50129. removedMeshes: _this._toRemoveMeshesArray
  50130. };
  50131. var message = {
  50132. payload: payload,
  50133. taskType: WorkerTaskType.UPDATE
  50134. };
  50135. var serializable = [];
  50136. for (var id in payload.updatedGeometries) {
  50137. if (payload.updatedGeometries.hasOwnProperty(id)) {
  50138. //prepare transferables
  50139. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  50140. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  50141. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  50142. }
  50143. }
  50144. _this._worker.postMessage(message, serializable);
  50145. _this._addUpdateMeshesList = {};
  50146. _this._addUpdateGeometriesList = {};
  50147. _this._toRemoveGeometryArray = [];
  50148. _this._toRemoveMeshesArray = [];
  50149. };
  50150. this._onMessageFromWorker = function (e) {
  50151. var returnData = e.data;
  50152. if (returnData.error != WorkerReplyType.SUCCESS) {
  50153. //TODO what errors can be returned from the worker?
  50154. BABYLON.Tools.Warn("error returned from worker!");
  50155. return;
  50156. }
  50157. switch (returnData.taskType) {
  50158. case WorkerTaskType.INIT:
  50159. _this._init = true;
  50160. //Update the worked with ALL of the scene's current state
  50161. _this._scene.meshes.forEach(function (mesh) {
  50162. _this.onMeshAdded(mesh);
  50163. });
  50164. _this._scene.getGeometries().forEach(function (geometry) {
  50165. _this.onGeometryAdded(geometry);
  50166. });
  50167. break;
  50168. case WorkerTaskType.UPDATE:
  50169. _this._runningUpdated--;
  50170. break;
  50171. case WorkerTaskType.COLLIDE:
  50172. var returnPayload = returnData.payload;
  50173. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  50174. return;
  50175. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  50176. if (callback) {
  50177. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  50178. if (mesh) {
  50179. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  50180. }
  50181. }
  50182. //cleanup
  50183. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  50184. break;
  50185. }
  50186. };
  50187. this._collisionsCallbackArray = [];
  50188. this._init = false;
  50189. this._runningUpdated = 0;
  50190. this._addUpdateMeshesList = {};
  50191. this._addUpdateGeometriesList = {};
  50192. this._toRemoveGeometryArray = [];
  50193. this._toRemoveMeshesArray = [];
  50194. }
  50195. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  50196. if (!this._init)
  50197. return;
  50198. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  50199. return;
  50200. position.divideToRef(collider._radius, this._scaledPosition);
  50201. displacement.divideToRef(collider._radius, this._scaledVelocity);
  50202. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  50203. var payload = {
  50204. collider: {
  50205. position: this._scaledPosition.asArray(),
  50206. velocity: this._scaledVelocity.asArray(),
  50207. radius: collider._radius.asArray()
  50208. },
  50209. collisionId: collisionIndex,
  50210. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  50211. maximumRetry: maximumRetry
  50212. };
  50213. var message = {
  50214. payload: payload,
  50215. taskType: WorkerTaskType.COLLIDE
  50216. };
  50217. this._worker.postMessage(message);
  50218. };
  50219. CollisionCoordinatorWorker.prototype.init = function (scene) {
  50220. this._scene = scene;
  50221. this._scene.registerAfterRender(this._afterRender);
  50222. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  50223. this._worker = new Worker(workerUrl);
  50224. this._worker.onmessage = this._onMessageFromWorker;
  50225. var message = {
  50226. payload: {},
  50227. taskType: WorkerTaskType.INIT
  50228. };
  50229. this._worker.postMessage(message);
  50230. };
  50231. CollisionCoordinatorWorker.prototype.destroy = function () {
  50232. this._scene.unregisterAfterRender(this._afterRender);
  50233. this._worker.terminate();
  50234. };
  50235. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  50236. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  50237. this.onMeshUpdated(mesh);
  50238. };
  50239. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  50240. this._toRemoveMeshesArray.push(mesh.uniqueId);
  50241. };
  50242. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  50243. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  50244. geometry.onGeometryUpdated = this.onGeometryUpdated;
  50245. this.onGeometryUpdated(geometry);
  50246. };
  50247. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  50248. this._toRemoveGeometryArray.push(geometry.id);
  50249. };
  50250. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  50251. var submeshes = [];
  50252. if (mesh.subMeshes) {
  50253. submeshes = mesh.subMeshes.map(function (sm, idx) {
  50254. var boundingInfo = sm.getBoundingInfo();
  50255. return {
  50256. position: idx,
  50257. verticesStart: sm.verticesStart,
  50258. verticesCount: sm.verticesCount,
  50259. indexStart: sm.indexStart,
  50260. indexCount: sm.indexCount,
  50261. hasMaterial: !!sm.getMaterial(),
  50262. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  50263. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  50264. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  50265. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  50266. };
  50267. });
  50268. }
  50269. var geometryId = null;
  50270. if (mesh instanceof BABYLON.Mesh) {
  50271. var geometry = mesh.geometry;
  50272. geometryId = geometry ? geometry.id : null;
  50273. }
  50274. else if (mesh instanceof BABYLON.InstancedMesh) {
  50275. var geometry = mesh.sourceMesh.geometry;
  50276. geometryId = geometry ? geometry.id : null;
  50277. }
  50278. var boundingInfo = mesh.getBoundingInfo();
  50279. return {
  50280. uniqueId: mesh.uniqueId,
  50281. id: mesh.id,
  50282. name: mesh.name,
  50283. geometryId: geometryId,
  50284. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  50285. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  50286. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  50287. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  50288. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  50289. subMeshes: submeshes,
  50290. checkCollisions: mesh.checkCollisions
  50291. };
  50292. };
  50293. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  50294. return {
  50295. id: geometry.id,
  50296. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  50297. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  50298. indices: new Uint32Array(geometry.getIndices() || []),
  50299. };
  50300. };
  50301. return CollisionCoordinatorWorker;
  50302. }());
  50303. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  50304. var CollisionCoordinatorLegacy = /** @class */ (function () {
  50305. function CollisionCoordinatorLegacy() {
  50306. this._scaledPosition = BABYLON.Vector3.Zero();
  50307. this._scaledVelocity = BABYLON.Vector3.Zero();
  50308. this._finalPosition = BABYLON.Vector3.Zero();
  50309. }
  50310. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  50311. position.divideToRef(collider._radius, this._scaledPosition);
  50312. displacement.divideToRef(collider._radius, this._scaledVelocity);
  50313. collider.collidedMesh = null;
  50314. collider._retry = 0;
  50315. collider._initialVelocity = this._scaledVelocity;
  50316. collider._initialPosition = this._scaledPosition;
  50317. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  50318. this._finalPosition.multiplyInPlace(collider._radius);
  50319. //run the callback
  50320. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  50321. };
  50322. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  50323. this._scene = scene;
  50324. };
  50325. CollisionCoordinatorLegacy.prototype.destroy = function () {
  50326. //Legacy need no destruction method.
  50327. };
  50328. //No update in legacy mode
  50329. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  50330. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  50331. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  50332. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  50333. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  50334. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  50335. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  50336. if (excludedMesh === void 0) { excludedMesh = null; }
  50337. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  50338. if (collider._retry >= maximumRetry) {
  50339. finalPosition.copyFrom(position);
  50340. return;
  50341. }
  50342. // Check if this is a mesh else camera or -1
  50343. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  50344. collider._initialize(position, velocity, closeDistance);
  50345. // Check all meshes
  50346. for (var index = 0; index < this._scene.meshes.length; index++) {
  50347. var mesh = this._scene.meshes[index];
  50348. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  50349. mesh._checkCollision(collider);
  50350. }
  50351. }
  50352. if (!collider.collisionFound) {
  50353. position.addToRef(velocity, finalPosition);
  50354. return;
  50355. }
  50356. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  50357. collider._getResponse(position, velocity);
  50358. }
  50359. if (velocity.length() <= closeDistance) {
  50360. finalPosition.copyFrom(position);
  50361. return;
  50362. }
  50363. collider._retry++;
  50364. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  50365. };
  50366. return CollisionCoordinatorLegacy;
  50367. }());
  50368. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  50369. })(BABYLON || (BABYLON = {}));
  50370. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  50371. var BABYLON;
  50372. (function (BABYLON) {
  50373. /**
  50374. * A particle represents one of the element emitted by a particle system.
  50375. * This is mainly define by its coordinates, direction, velocity and age.
  50376. */
  50377. var Particle = /** @class */ (function () {
  50378. /**
  50379. * Creates a new instance of @see Particle
  50380. * @param particleSystem the particle system the particle belongs to
  50381. */
  50382. function Particle(particleSystem) {
  50383. this.particleSystem = particleSystem;
  50384. /**
  50385. * The world position of the particle in the scene.
  50386. */
  50387. this.position = BABYLON.Vector3.Zero();
  50388. /**
  50389. * The world direction of the particle in the scene.
  50390. */
  50391. this.direction = BABYLON.Vector3.Zero();
  50392. /**
  50393. * The color of the particle.
  50394. */
  50395. this.color = new BABYLON.Color4(0, 0, 0, 0);
  50396. /**
  50397. * The color change of the particle per step.
  50398. */
  50399. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  50400. /**
  50401. * Defines how long will the life of the particle be.
  50402. */
  50403. this.lifeTime = 1.0;
  50404. /**
  50405. * The current age of the particle.
  50406. */
  50407. this.age = 0;
  50408. /**
  50409. * The current size of the particle.
  50410. */
  50411. this.size = 0;
  50412. /**
  50413. * The current angle of the particle.
  50414. */
  50415. this.angle = 0;
  50416. /**
  50417. * Defines how fast is the angle changing.
  50418. */
  50419. this.angularSpeed = 0;
  50420. /**
  50421. * Defines the cell index used by the particle to be rendered from a sprite.
  50422. */
  50423. this.cellIndex = 0;
  50424. this._currentFrameCounter = 0;
  50425. if (!this.particleSystem.isAnimationSheetEnabled) {
  50426. return;
  50427. }
  50428. this.cellIndex = this.particleSystem.startSpriteCellID;
  50429. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  50430. this.updateCellIndex = this.updateCellIndexWithSpeedCalculated;
  50431. }
  50432. else {
  50433. this.updateCellIndex = this.updateCellIndexWithCustomSpeed;
  50434. }
  50435. }
  50436. Particle.prototype.updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  50437. // (ageOffset / scaledUpdateSpeed) / available cells
  50438. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  50439. this._currentFrameCounter += scaledUpdateSpeed;
  50440. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  50441. this._currentFrameCounter = 0;
  50442. this.cellIndex++;
  50443. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  50444. this.cellIndex = this.particleSystem.endSpriteCellID;
  50445. }
  50446. }
  50447. };
  50448. Particle.prototype.updateCellIndexWithCustomSpeed = function () {
  50449. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  50450. this.cellIndex++;
  50451. this._currentFrameCounter = 0;
  50452. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  50453. if (this.particleSystem.spriteCellLoop) {
  50454. this.cellIndex = this.particleSystem.startSpriteCellID;
  50455. }
  50456. else {
  50457. this.cellIndex = this.particleSystem.endSpriteCellID;
  50458. }
  50459. }
  50460. }
  50461. else {
  50462. this._currentFrameCounter++;
  50463. }
  50464. };
  50465. /**
  50466. * Copy the properties of particle to another one.
  50467. * @param other the particle to copy the information to.
  50468. */
  50469. Particle.prototype.copyTo = function (other) {
  50470. other.position.copyFrom(this.position);
  50471. other.direction.copyFrom(this.direction);
  50472. other.color.copyFrom(this.color);
  50473. other.colorStep.copyFrom(this.colorStep);
  50474. other.lifeTime = this.lifeTime;
  50475. other.age = this.age;
  50476. other.size = this.size;
  50477. other.angle = this.angle;
  50478. other.angularSpeed = this.angularSpeed;
  50479. other.particleSystem = this.particleSystem;
  50480. other.cellIndex = this.cellIndex;
  50481. };
  50482. return Particle;
  50483. }());
  50484. BABYLON.Particle = Particle;
  50485. })(BABYLON || (BABYLON = {}));
  50486. //# sourceMappingURL=babylon.particle.js.map
  50487. var BABYLON;
  50488. (function (BABYLON) {
  50489. /**
  50490. * This represents a particle system in Babylon.
  50491. * Particles are often small sprites used to simulate hard-to-reproduce phenomena like fire, smoke, water, or abstract visual effects like magic glitter and faery dust.
  50492. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  50493. * @example https://doc.babylonjs.com/babylon101/particles
  50494. */
  50495. var ParticleSystem = /** @class */ (function () {
  50496. /**
  50497. * Instantiates a particle system.
  50498. * Particles are often small sprites used to simulate hard-to-reproduce phenomena like fire, smoke, water, or abstract visual effects like magic glitter and faery dust.
  50499. * @param name The name of the particle system
  50500. * @param capacity The max number of particles alive at the same time
  50501. * @param scene The scene the particle system belongs to
  50502. * @param customEffect a custom effect used to change the way particles are rendered by default
  50503. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  50504. * @param epsilon Offset used to render the particles
  50505. */
  50506. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  50507. if (customEffect === void 0) { customEffect = null; }
  50508. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  50509. if (epsilon === void 0) { epsilon = 0.01; }
  50510. var _this = this;
  50511. /**
  50512. * List of animations used by the particle system.
  50513. */
  50514. this.animations = [];
  50515. /**
  50516. * The rendering group used by the Particle system to chose when to render.
  50517. */
  50518. this.renderingGroupId = 0;
  50519. /**
  50520. * The emitter represents the Mesh or position we are attaching the particle system to.
  50521. */
  50522. this.emitter = null;
  50523. /**
  50524. * The maximum number of particles to emit per frame
  50525. */
  50526. this.emitRate = 10;
  50527. /**
  50528. * If you want to launch only a few particles at once, that can be done, as well.
  50529. */
  50530. this.manualEmitCount = -1;
  50531. /**
  50532. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  50533. */
  50534. this.updateSpeed = 0.01;
  50535. /**
  50536. * The amount of time the particle system is running (depends of the overall update speed).
  50537. */
  50538. this.targetStopDuration = 0;
  50539. /**
  50540. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  50541. */
  50542. this.disposeOnStop = false;
  50543. /**
  50544. * Minimum power of emitting particles.
  50545. */
  50546. this.minEmitPower = 1;
  50547. /**
  50548. * Maximum power of emitting particles.
  50549. */
  50550. this.maxEmitPower = 1;
  50551. /**
  50552. * Minimum life time of emitting particles.
  50553. */
  50554. this.minLifeTime = 1;
  50555. /**
  50556. * Maximum life time of emitting particles.
  50557. */
  50558. this.maxLifeTime = 1;
  50559. /**
  50560. * Minimum Size of emitting particles.
  50561. */
  50562. this.minSize = 1;
  50563. /**
  50564. * Maximum Size of emitting particles.
  50565. */
  50566. this.maxSize = 1;
  50567. /**
  50568. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  50569. */
  50570. this.minAngularSpeed = 0;
  50571. /**
  50572. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  50573. */
  50574. this.maxAngularSpeed = 0;
  50575. /**
  50576. * The layer mask we are rendering the particles through.
  50577. */
  50578. this.layerMask = 0x0FFFFFFF;
  50579. /**
  50580. * This can help using your own shader to render the particle system.
  50581. * The according effect will be created
  50582. */
  50583. this.customShader = null;
  50584. /**
  50585. * By default particle system starts as soon as they are created. This prevents the
  50586. * automatic start to happen and let you decide when to start emitting particles.
  50587. */
  50588. this.preventAutoStart = false;
  50589. /**
  50590. * Callback triggered when the particle animation is ending.
  50591. */
  50592. this.onAnimationEnd = null;
  50593. /**
  50594. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  50595. */
  50596. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  50597. /**
  50598. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  50599. * to override the particles.
  50600. */
  50601. this.forceDepthWrite = false;
  50602. /**
  50603. * You can use gravity if you want to give an orientation to your particles.
  50604. */
  50605. this.gravity = BABYLON.Vector3.Zero();
  50606. /**
  50607. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  50608. */
  50609. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  50610. /**
  50611. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  50612. */
  50613. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  50614. /**
  50615. * Color the particle will have at the end of its lifetime.
  50616. */
  50617. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  50618. /**
  50619. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel.
  50620. */
  50621. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  50622. /**
  50623. * If using a spritesheet (isAnimationSheetEnabled), defines if the sprite animation should loop between startSpriteCellID and endSpriteCellID or not.
  50624. */
  50625. this.spriteCellLoop = true;
  50626. /**
  50627. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the speed of the sprite loop.
  50628. */
  50629. this.spriteCellChangeSpeed = 0;
  50630. /**
  50631. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the first sprite cell to display.
  50632. */
  50633. this.startSpriteCellID = 0;
  50634. /**
  50635. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the last sprite cell to display.
  50636. */
  50637. this.endSpriteCellID = 0;
  50638. /**
  50639. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use.
  50640. */
  50641. this.spriteCellWidth = 0;
  50642. /**
  50643. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use.
  50644. */
  50645. this.spriteCellHeight = 0;
  50646. /**
  50647. * An event triggered when the system is disposed.
  50648. */
  50649. this.onDisposeObservable = new BABYLON.Observable();
  50650. this._particles = new Array();
  50651. this._stockParticles = new Array();
  50652. this._newPartsExcess = 0;
  50653. this._vertexBuffers = {};
  50654. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  50655. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  50656. this._scaledDirection = BABYLON.Vector3.Zero();
  50657. this._scaledGravity = BABYLON.Vector3.Zero();
  50658. this._currentRenderId = -1;
  50659. this._started = false;
  50660. this._stopped = false;
  50661. this._actualFrame = 0;
  50662. this._vertexBufferSize = 11;
  50663. this._appendParticleVertexes = null;
  50664. this.id = name;
  50665. this.name = name;
  50666. this._capacity = capacity;
  50667. this._epsilon = epsilon;
  50668. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  50669. if (isAnimationSheetEnabled) {
  50670. this._vertexBufferSize = 12;
  50671. }
  50672. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  50673. this._customEffect = customEffect;
  50674. scene.particleSystems.push(this);
  50675. this._createIndexBuffer();
  50676. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  50677. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  50678. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  50679. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  50680. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  50681. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  50682. if (this._isAnimationSheetEnabled) {
  50683. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  50684. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  50685. }
  50686. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  50687. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  50688. this._vertexBuffers["options"] = options;
  50689. // Default emitter type
  50690. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  50691. this.updateFunction = function (particles) {
  50692. for (var index = 0; index < particles.length; index++) {
  50693. var particle = particles[index];
  50694. particle.age += _this._scaledUpdateSpeed;
  50695. if (particle.age >= particle.lifeTime) {
  50696. _this.recycleParticle(particle);
  50697. index--;
  50698. continue;
  50699. }
  50700. else {
  50701. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  50702. particle.color.addInPlace(_this._scaledColorStep);
  50703. if (particle.color.a < 0)
  50704. particle.color.a = 0;
  50705. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  50706. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  50707. particle.position.addInPlace(_this._scaledDirection);
  50708. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  50709. particle.direction.addInPlace(_this._scaledGravity);
  50710. if (_this._isAnimationSheetEnabled) {
  50711. particle.updateCellIndex(_this._scaledUpdateSpeed);
  50712. }
  50713. }
  50714. }
  50715. };
  50716. }
  50717. Object.defineProperty(ParticleSystem.prototype, "direction1", {
  50718. /**
  50719. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  50720. * This only works when particleEmitterTyps is a BoxParticleEmitter
  50721. */
  50722. get: function () {
  50723. if (this.particleEmitterType.direction1) {
  50724. return this.particleEmitterType.direction1;
  50725. }
  50726. return BABYLON.Vector3.Zero();
  50727. },
  50728. set: function (value) {
  50729. if (this.particleEmitterType.direction1) {
  50730. this.particleEmitterType.direction1 = value;
  50731. }
  50732. },
  50733. enumerable: true,
  50734. configurable: true
  50735. });
  50736. Object.defineProperty(ParticleSystem.prototype, "direction2", {
  50737. /**
  50738. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  50739. * This only works when particleEmitterTyps is a BoxParticleEmitter
  50740. */
  50741. get: function () {
  50742. if (this.particleEmitterType.direction2) {
  50743. return this.particleEmitterType.direction2;
  50744. }
  50745. return BABYLON.Vector3.Zero();
  50746. },
  50747. set: function (value) {
  50748. if (this.particleEmitterType.direction2) {
  50749. this.particleEmitterType.direction2 = value;
  50750. }
  50751. },
  50752. enumerable: true,
  50753. configurable: true
  50754. });
  50755. Object.defineProperty(ParticleSystem.prototype, "minEmitBox", {
  50756. /**
  50757. * Minimum box point around our emitter. Our emitter is the center of particles source, but if you want your particles to emit from more than one point, then you can tell it to do so.
  50758. * This only works when particleEmitterTyps is a BoxParticleEmitter
  50759. */
  50760. get: function () {
  50761. if (this.particleEmitterType.minEmitBox) {
  50762. return this.particleEmitterType.minEmitBox;
  50763. }
  50764. return BABYLON.Vector3.Zero();
  50765. },
  50766. set: function (value) {
  50767. if (this.particleEmitterType.minEmitBox) {
  50768. this.particleEmitterType.minEmitBox = value;
  50769. }
  50770. },
  50771. enumerable: true,
  50772. configurable: true
  50773. });
  50774. Object.defineProperty(ParticleSystem.prototype, "maxEmitBox", {
  50775. /**
  50776. * Maximum box point around our emitter. Our emitter is the center of particles source, but if you want your particles to emit from more than one point, then you can tell it to do so.
  50777. * This only works when particleEmitterTyps is a BoxParticleEmitter
  50778. */
  50779. get: function () {
  50780. if (this.particleEmitterType.maxEmitBox) {
  50781. return this.particleEmitterType.maxEmitBox;
  50782. }
  50783. return BABYLON.Vector3.Zero();
  50784. },
  50785. set: function (value) {
  50786. if (this.particleEmitterType.maxEmitBox) {
  50787. this.particleEmitterType.maxEmitBox = value;
  50788. }
  50789. },
  50790. enumerable: true,
  50791. configurable: true
  50792. });
  50793. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  50794. /**
  50795. * Sets a callback that will be triggered when the system is disposed.
  50796. */
  50797. set: function (callback) {
  50798. if (this._onDisposeObserver) {
  50799. this.onDisposeObservable.remove(this._onDisposeObserver);
  50800. }
  50801. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  50802. },
  50803. enumerable: true,
  50804. configurable: true
  50805. });
  50806. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  50807. /**
  50808. * Gets wether an animation sprite sheet is enabled or not on the particle system.
  50809. */
  50810. get: function () {
  50811. return this._isAnimationSheetEnabled;
  50812. },
  50813. enumerable: true,
  50814. configurable: true
  50815. });
  50816. Object.defineProperty(ParticleSystem.prototype, "particles", {
  50817. /**
  50818. * Gets the current list of active particles
  50819. */
  50820. get: function () {
  50821. return this._particles;
  50822. },
  50823. enumerable: true,
  50824. configurable: true
  50825. });
  50826. /**
  50827. * Returns the string "ParticleSystem"
  50828. * @returns a string containing the class name
  50829. */
  50830. ParticleSystem.prototype.getClassName = function () {
  50831. return "ParticleSystem";
  50832. };
  50833. ParticleSystem.prototype._createIndexBuffer = function () {
  50834. var indices = [];
  50835. var index = 0;
  50836. for (var count = 0; count < this._capacity; count++) {
  50837. indices.push(index);
  50838. indices.push(index + 1);
  50839. indices.push(index + 2);
  50840. indices.push(index);
  50841. indices.push(index + 2);
  50842. indices.push(index + 3);
  50843. index += 4;
  50844. }
  50845. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  50846. };
  50847. /**
  50848. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  50849. * Its lifetime will start back at 0.
  50850. * @param particle The particle to recycle
  50851. */
  50852. ParticleSystem.prototype.recycleParticle = function (particle) {
  50853. var lastParticle = this._particles.pop();
  50854. if (lastParticle !== particle) {
  50855. lastParticle.copyTo(particle);
  50856. this._stockParticles.push(lastParticle);
  50857. }
  50858. };
  50859. /**
  50860. * Gets the maximum number of particles active at the same time.
  50861. * @returns The max number of active particles.
  50862. */
  50863. ParticleSystem.prototype.getCapacity = function () {
  50864. return this._capacity;
  50865. };
  50866. /**
  50867. * Gets Wether there are still active particles in the system.
  50868. * @returns True if it is alive, otherwise false.
  50869. */
  50870. ParticleSystem.prototype.isAlive = function () {
  50871. return this._alive;
  50872. };
  50873. /**
  50874. * Gets Wether the system has been started.
  50875. * @returns True if it has been started, otherwise false.
  50876. */
  50877. ParticleSystem.prototype.isStarted = function () {
  50878. return this._started;
  50879. };
  50880. /**
  50881. * Starts the particle system and begins to emit.
  50882. */
  50883. ParticleSystem.prototype.start = function () {
  50884. this._started = true;
  50885. this._stopped = false;
  50886. this._actualFrame = 0;
  50887. };
  50888. /**
  50889. * Stops the particle system.
  50890. */
  50891. ParticleSystem.prototype.stop = function () {
  50892. this._stopped = true;
  50893. };
  50894. /**
  50895. * Remove all active particles
  50896. */
  50897. ParticleSystem.prototype.reset = function () {
  50898. this._stockParticles = [];
  50899. this._particles = [];
  50900. };
  50901. /**
  50902. * @ignore (for internal use only)
  50903. */
  50904. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  50905. var offset = index * this._vertexBufferSize;
  50906. this._vertexData[offset] = particle.position.x;
  50907. this._vertexData[offset + 1] = particle.position.y;
  50908. this._vertexData[offset + 2] = particle.position.z;
  50909. this._vertexData[offset + 3] = particle.color.r;
  50910. this._vertexData[offset + 4] = particle.color.g;
  50911. this._vertexData[offset + 5] = particle.color.b;
  50912. this._vertexData[offset + 6] = particle.color.a;
  50913. this._vertexData[offset + 7] = particle.angle;
  50914. this._vertexData[offset + 8] = particle.size;
  50915. this._vertexData[offset + 9] = offsetX;
  50916. this._vertexData[offset + 10] = offsetY;
  50917. };
  50918. /**
  50919. * @ignore (for internal use only)
  50920. */
  50921. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  50922. if (offsetX === 0)
  50923. offsetX = this._epsilon;
  50924. else if (offsetX === 1)
  50925. offsetX = 1 - this._epsilon;
  50926. if (offsetY === 0)
  50927. offsetY = this._epsilon;
  50928. else if (offsetY === 1)
  50929. offsetY = 1 - this._epsilon;
  50930. var offset = index * this._vertexBufferSize;
  50931. this._vertexData[offset] = particle.position.x;
  50932. this._vertexData[offset + 1] = particle.position.y;
  50933. this._vertexData[offset + 2] = particle.position.z;
  50934. this._vertexData[offset + 3] = particle.color.r;
  50935. this._vertexData[offset + 4] = particle.color.g;
  50936. this._vertexData[offset + 5] = particle.color.b;
  50937. this._vertexData[offset + 6] = particle.color.a;
  50938. this._vertexData[offset + 7] = particle.angle;
  50939. this._vertexData[offset + 8] = particle.size;
  50940. this._vertexData[offset + 9] = offsetX;
  50941. this._vertexData[offset + 10] = offsetY;
  50942. this._vertexData[offset + 11] = particle.cellIndex;
  50943. };
  50944. ParticleSystem.prototype._update = function (newParticles) {
  50945. // Update current
  50946. this._alive = this._particles.length > 0;
  50947. this.updateFunction(this._particles);
  50948. // Add new ones
  50949. var worldMatrix;
  50950. if (this.emitter.position) {
  50951. var emitterMesh = this.emitter;
  50952. worldMatrix = emitterMesh.getWorldMatrix();
  50953. }
  50954. else {
  50955. var emitterPosition = this.emitter;
  50956. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  50957. }
  50958. var particle;
  50959. for (var index = 0; index < newParticles; index++) {
  50960. if (this._particles.length === this._capacity) {
  50961. break;
  50962. }
  50963. if (this._stockParticles.length !== 0) {
  50964. particle = this._stockParticles.pop();
  50965. particle.age = 0;
  50966. particle.cellIndex = this.startSpriteCellID;
  50967. }
  50968. else {
  50969. particle = new BABYLON.Particle(this);
  50970. }
  50971. this._particles.push(particle);
  50972. var emitPower = BABYLON.Scalar.RandomRange(this.minEmitPower, this.maxEmitPower);
  50973. if (this.startPositionFunction) {
  50974. this.startPositionFunction(worldMatrix, particle.position, particle);
  50975. }
  50976. else {
  50977. this.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  50978. }
  50979. if (this.startDirectionFunction) {
  50980. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  50981. }
  50982. else {
  50983. this.particleEmitterType.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  50984. }
  50985. particle.lifeTime = BABYLON.Scalar.RandomRange(this.minLifeTime, this.maxLifeTime);
  50986. particle.size = BABYLON.Scalar.RandomRange(this.minSize, this.maxSize);
  50987. particle.angularSpeed = BABYLON.Scalar.RandomRange(this.minAngularSpeed, this.maxAngularSpeed);
  50988. var step = BABYLON.Scalar.RandomRange(0, 1.0);
  50989. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  50990. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  50991. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  50992. }
  50993. };
  50994. ParticleSystem.prototype._getEffect = function () {
  50995. if (this._customEffect) {
  50996. return this._customEffect;
  50997. }
  50998. ;
  50999. var defines = [];
  51000. if (this._scene.clipPlane) {
  51001. defines.push("#define CLIPPLANE");
  51002. }
  51003. if (this._isAnimationSheetEnabled) {
  51004. defines.push("#define ANIMATESHEET");
  51005. }
  51006. // Effect
  51007. var join = defines.join("\n");
  51008. if (this._cachedDefines !== join) {
  51009. this._cachedDefines = join;
  51010. var attributesNamesOrOptions;
  51011. var effectCreationOption;
  51012. if (this._isAnimationSheetEnabled) {
  51013. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  51014. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  51015. }
  51016. else {
  51017. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  51018. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  51019. }
  51020. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  51021. }
  51022. return this._effect;
  51023. };
  51024. /**
  51025. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  51026. */
  51027. ParticleSystem.prototype.animate = function () {
  51028. if (!this._started)
  51029. return;
  51030. var effect = this._getEffect();
  51031. // Check
  51032. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  51033. return;
  51034. if (this._currentRenderId === this._scene.getRenderId()) {
  51035. return;
  51036. }
  51037. this._currentRenderId = this._scene.getRenderId();
  51038. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  51039. // determine the number of particles we need to create
  51040. var newParticles;
  51041. if (this.manualEmitCount > -1) {
  51042. newParticles = this.manualEmitCount;
  51043. this._newPartsExcess = 0;
  51044. this.manualEmitCount = 0;
  51045. }
  51046. else {
  51047. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  51048. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  51049. }
  51050. if (this._newPartsExcess > 1.0) {
  51051. newParticles += this._newPartsExcess >> 0;
  51052. this._newPartsExcess -= this._newPartsExcess >> 0;
  51053. }
  51054. this._alive = false;
  51055. if (!this._stopped) {
  51056. this._actualFrame += this._scaledUpdateSpeed;
  51057. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  51058. this.stop();
  51059. }
  51060. else {
  51061. newParticles = 0;
  51062. }
  51063. this._update(newParticles);
  51064. // Stopped?
  51065. if (this._stopped) {
  51066. if (!this._alive) {
  51067. this._started = false;
  51068. if (this.onAnimationEnd) {
  51069. this.onAnimationEnd();
  51070. }
  51071. if (this.disposeOnStop) {
  51072. this._scene._toBeDisposed.push(this);
  51073. }
  51074. }
  51075. }
  51076. // Animation sheet
  51077. if (this._isAnimationSheetEnabled) {
  51078. this._appendParticleVertexes = this._appenedParticleVertexesWithSheet;
  51079. }
  51080. else {
  51081. this._appendParticleVertexes = this._appenedParticleVertexesNoSheet;
  51082. }
  51083. // Update VBO
  51084. var offset = 0;
  51085. for (var index = 0; index < this._particles.length; index++) {
  51086. var particle = this._particles[index];
  51087. this._appendParticleVertexes(offset, particle);
  51088. offset += 4;
  51089. }
  51090. if (this._vertexBuffer) {
  51091. this._vertexBuffer.update(this._vertexData);
  51092. }
  51093. };
  51094. ParticleSystem.prototype._appenedParticleVertexesWithSheet = function (offset, particle) {
  51095. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  51096. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  51097. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  51098. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  51099. };
  51100. ParticleSystem.prototype._appenedParticleVertexesNoSheet = function (offset, particle) {
  51101. this._appendParticleVertex(offset++, particle, 0, 0);
  51102. this._appendParticleVertex(offset++, particle, 1, 0);
  51103. this._appendParticleVertex(offset++, particle, 1, 1);
  51104. this._appendParticleVertex(offset++, particle, 0, 1);
  51105. };
  51106. /**
  51107. * Rebuilds the particle system.
  51108. */
  51109. ParticleSystem.prototype.rebuild = function () {
  51110. this._createIndexBuffer();
  51111. if (this._vertexBuffer) {
  51112. this._vertexBuffer._rebuild();
  51113. }
  51114. };
  51115. /**
  51116. * Renders the particle system in its current state.
  51117. * @returns the current number of particles
  51118. */
  51119. ParticleSystem.prototype.render = function () {
  51120. var effect = this._getEffect();
  51121. // Check
  51122. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this._particles.length) {
  51123. return 0;
  51124. }
  51125. var engine = this._scene.getEngine();
  51126. // Render
  51127. engine.enableEffect(effect);
  51128. engine.setState(false);
  51129. var viewMatrix = this._scene.getViewMatrix();
  51130. effect.setTexture("diffuseSampler", this.particleTexture);
  51131. effect.setMatrix("view", viewMatrix);
  51132. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  51133. if (this._isAnimationSheetEnabled) {
  51134. var baseSize = this.particleTexture.getBaseSize();
  51135. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  51136. }
  51137. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  51138. if (this._scene.clipPlane) {
  51139. var clipPlane = this._scene.clipPlane;
  51140. var invView = viewMatrix.clone();
  51141. invView.invert();
  51142. effect.setMatrix("invView", invView);
  51143. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  51144. }
  51145. // VBOs
  51146. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  51147. // Draw order
  51148. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  51149. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  51150. }
  51151. else {
  51152. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  51153. }
  51154. if (this.forceDepthWrite) {
  51155. engine.setDepthWrite(true);
  51156. }
  51157. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  51158. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  51159. return this._particles.length;
  51160. };
  51161. /**
  51162. * Disposes the particle system and free the associated resources
  51163. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  51164. */
  51165. ParticleSystem.prototype.dispose = function (disposeTexture) {
  51166. if (disposeTexture === void 0) { disposeTexture = true; }
  51167. if (this._vertexBuffer) {
  51168. this._vertexBuffer.dispose();
  51169. this._vertexBuffer = null;
  51170. }
  51171. if (this._indexBuffer) {
  51172. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  51173. this._indexBuffer = null;
  51174. }
  51175. if (disposeTexture && this.particleTexture) {
  51176. this.particleTexture.dispose();
  51177. this.particleTexture = null;
  51178. }
  51179. // Remove from scene
  51180. var index = this._scene.particleSystems.indexOf(this);
  51181. if (index > -1) {
  51182. this._scene.particleSystems.splice(index, 1);
  51183. }
  51184. // Callback
  51185. this.onDisposeObservable.notifyObservers(this);
  51186. this.onDisposeObservable.clear();
  51187. };
  51188. /**
  51189. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  51190. * @param radius The radius of the sphere to emit from
  51191. * @returns the emitter
  51192. */
  51193. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  51194. if (radius === void 0) { radius = 1; }
  51195. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  51196. this.particleEmitterType = particleEmitter;
  51197. return particleEmitter;
  51198. };
  51199. /**
  51200. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  51201. * @param radius The radius of the sphere to emit from
  51202. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  51203. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  51204. * @returns the emitter
  51205. */
  51206. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  51207. if (radius === void 0) { radius = 1; }
  51208. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  51209. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  51210. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  51211. this.particleEmitterType = particleEmitter;
  51212. return particleEmitter;
  51213. };
  51214. /**
  51215. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  51216. * @param radius The radius of the cone to emit from
  51217. * @param angle The base angle of the cone
  51218. * @returns the emitter
  51219. */
  51220. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  51221. if (radius === void 0) { radius = 1; }
  51222. if (angle === void 0) { angle = Math.PI / 4; }
  51223. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  51224. this.particleEmitterType = particleEmitter;
  51225. return particleEmitter;
  51226. };
  51227. // this method needs to be changed when breaking changes will be allowed to match the sphere and cone methods and properties direction1,2 and minEmitBox,maxEmitBox to be removed from the system.
  51228. /**
  51229. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  51230. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  51231. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  51232. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  51233. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  51234. * @returns the emitter
  51235. */
  51236. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  51237. var particleEmitter = new BABYLON.BoxParticleEmitter();
  51238. this.direction1 = direction1;
  51239. this.direction2 = direction2;
  51240. this.minEmitBox = minEmitBox;
  51241. this.maxEmitBox = maxEmitBox;
  51242. this.particleEmitterType = particleEmitter;
  51243. return particleEmitter;
  51244. };
  51245. /**
  51246. * Clones the particle system.
  51247. * @param name The name of the cloned object
  51248. * @param newEmitter The new emitter to use
  51249. * @returns the cloned particle system
  51250. */
  51251. ParticleSystem.prototype.clone = function (name, newEmitter) {
  51252. var custom = null;
  51253. var program = null;
  51254. if (this.customShader != null) {
  51255. program = this.customShader;
  51256. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  51257. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  51258. }
  51259. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  51260. result.customShader = program;
  51261. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  51262. if (newEmitter === undefined) {
  51263. newEmitter = this.emitter;
  51264. }
  51265. result.emitter = newEmitter;
  51266. if (this.particleTexture) {
  51267. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  51268. }
  51269. if (!this.preventAutoStart) {
  51270. result.start();
  51271. }
  51272. return result;
  51273. };
  51274. /**
  51275. * Serializes the particle system to a JSON object.
  51276. * @returns the JSON object
  51277. */
  51278. ParticleSystem.prototype.serialize = function () {
  51279. var serializationObject = {};
  51280. serializationObject.name = this.name;
  51281. serializationObject.id = this.id;
  51282. // Emitter
  51283. if (this.emitter.position) {
  51284. var emitterMesh = this.emitter;
  51285. serializationObject.emitterId = emitterMesh.id;
  51286. }
  51287. else {
  51288. var emitterPosition = this.emitter;
  51289. serializationObject.emitter = emitterPosition.asArray();
  51290. }
  51291. serializationObject.capacity = this.getCapacity();
  51292. if (this.particleTexture) {
  51293. serializationObject.textureName = this.particleTexture.name;
  51294. }
  51295. // Animations
  51296. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  51297. // Particle system
  51298. serializationObject.minAngularSpeed = this.minAngularSpeed;
  51299. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  51300. serializationObject.minSize = this.minSize;
  51301. serializationObject.maxSize = this.maxSize;
  51302. serializationObject.minEmitPower = this.minEmitPower;
  51303. serializationObject.maxEmitPower = this.maxEmitPower;
  51304. serializationObject.minLifeTime = this.minLifeTime;
  51305. serializationObject.maxLifeTime = this.maxLifeTime;
  51306. serializationObject.emitRate = this.emitRate;
  51307. serializationObject.minEmitBox = this.minEmitBox.asArray();
  51308. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  51309. serializationObject.gravity = this.gravity.asArray();
  51310. serializationObject.direction1 = this.direction1.asArray();
  51311. serializationObject.direction2 = this.direction2.asArray();
  51312. serializationObject.color1 = this.color1.asArray();
  51313. serializationObject.color2 = this.color2.asArray();
  51314. serializationObject.colorDead = this.colorDead.asArray();
  51315. serializationObject.updateSpeed = this.updateSpeed;
  51316. serializationObject.targetStopDuration = this.targetStopDuration;
  51317. serializationObject.textureMask = this.textureMask.asArray();
  51318. serializationObject.blendMode = this.blendMode;
  51319. serializationObject.customShader = this.customShader;
  51320. serializationObject.preventAutoStart = this.preventAutoStart;
  51321. serializationObject.startSpriteCellID = this.startSpriteCellID;
  51322. serializationObject.endSpriteCellID = this.endSpriteCellID;
  51323. serializationObject.spriteCellLoop = this.spriteCellLoop;
  51324. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  51325. serializationObject.spriteCellWidth = this.spriteCellWidth;
  51326. serializationObject.spriteCellHeight = this.spriteCellHeight;
  51327. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  51328. // Emitter
  51329. if (this.particleEmitterType) {
  51330. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  51331. }
  51332. return serializationObject;
  51333. };
  51334. /**
  51335. * Parses a JSON object to create a particle system.
  51336. * @param parsedParticleSystem The JSON object to parse
  51337. * @param scene The scene to create the particle system in
  51338. * @param rootUrl The root url to use to load external dependencies like texture
  51339. * @returns the Parsed particle system
  51340. */
  51341. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  51342. var name = parsedParticleSystem.name;
  51343. var custom = null;
  51344. var program = null;
  51345. if (parsedParticleSystem.customShader) {
  51346. program = parsedParticleSystem.customShader;
  51347. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  51348. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  51349. }
  51350. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  51351. particleSystem.customShader = program;
  51352. if (parsedParticleSystem.id) {
  51353. particleSystem.id = parsedParticleSystem.id;
  51354. }
  51355. // Auto start
  51356. if (parsedParticleSystem.preventAutoStart) {
  51357. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  51358. }
  51359. // Texture
  51360. if (parsedParticleSystem.textureName) {
  51361. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  51362. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  51363. }
  51364. // Emitter
  51365. if (parsedParticleSystem.emitterId) {
  51366. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  51367. }
  51368. else {
  51369. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  51370. }
  51371. // Animations
  51372. if (parsedParticleSystem.animations) {
  51373. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  51374. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  51375. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  51376. }
  51377. }
  51378. if (parsedParticleSystem.autoAnimate) {
  51379. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  51380. }
  51381. // Particle system
  51382. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  51383. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  51384. particleSystem.minSize = parsedParticleSystem.minSize;
  51385. particleSystem.maxSize = parsedParticleSystem.maxSize;
  51386. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  51387. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  51388. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  51389. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  51390. particleSystem.emitRate = parsedParticleSystem.emitRate;
  51391. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  51392. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  51393. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  51394. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  51395. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  51396. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  51397. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  51398. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  51399. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  51400. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  51401. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  51402. particleSystem.blendMode = parsedParticleSystem.blendMode;
  51403. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  51404. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  51405. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  51406. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  51407. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  51408. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  51409. if (!particleSystem.preventAutoStart) {
  51410. particleSystem.start();
  51411. }
  51412. return particleSystem;
  51413. };
  51414. /**
  51415. * Source color is added to the destination color without alpha affecting the result.
  51416. */
  51417. ParticleSystem.BLENDMODE_ONEONE = 0;
  51418. /**
  51419. * Blend current color and particle color using particle’s alpha.
  51420. */
  51421. ParticleSystem.BLENDMODE_STANDARD = 1;
  51422. return ParticleSystem;
  51423. }());
  51424. BABYLON.ParticleSystem = ParticleSystem;
  51425. })(BABYLON || (BABYLON = {}));
  51426. //# sourceMappingURL=babylon.particleSystem.js.map
  51427. //# sourceMappingURL=babylon.IParticleEmitterType.js.map
  51428. var BABYLON;
  51429. (function (BABYLON) {
  51430. /**
  51431. * Particle emitter emitting particles from the inside of a box.
  51432. * It emits the particles randomly between 2 given directions.
  51433. */
  51434. var BoxParticleEmitter = /** @class */ (function () {
  51435. /**
  51436. * Creates a new instance of @see BoxParticleEmitter
  51437. */
  51438. function BoxParticleEmitter() {
  51439. /**
  51440. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  51441. */
  51442. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  51443. /**
  51444. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  51445. */
  51446. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  51447. /**
  51448. * Minimum box point around our emitter. Our emitter is the center of particles source, but if you want your particles to emit from more than one point, then you can tell it to do so.
  51449. */
  51450. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  51451. /**
  51452. * Maximum box point around our emitter. Our emitter is the center of particles source, but if you want your particles to emit from more than one point, then you can tell it to do so.
  51453. */
  51454. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  51455. }
  51456. /**
  51457. * Called by the particle System when the direction is computed for the created particle.
  51458. * @param emitPower is the power of the particle (speed)
  51459. * @param worldMatrix is the world matrix of the particle system
  51460. * @param directionToUpdate is the direction vector to update with the result
  51461. * @param particle is the particle we are computed the direction for
  51462. */
  51463. BoxParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  51464. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  51465. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  51466. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  51467. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  51468. };
  51469. /**
  51470. * Called by the particle System when the position is computed for the created particle.
  51471. * @param worldMatrix is the world matrix of the particle system
  51472. * @param positionToUpdate is the position vector to update with the result
  51473. * @param particle is the particle we are computed the position for
  51474. */
  51475. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  51476. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  51477. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  51478. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  51479. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  51480. };
  51481. /**
  51482. * Clones the current emitter and returns a copy of it
  51483. * @returns the new emitter
  51484. */
  51485. BoxParticleEmitter.prototype.clone = function () {
  51486. var newOne = new BoxParticleEmitter();
  51487. BABYLON.Tools.DeepCopy(this, newOne);
  51488. return newOne;
  51489. };
  51490. /**
  51491. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  51492. * @param effect defines the update shader
  51493. */
  51494. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  51495. effect.setVector3("direction1", this.direction1);
  51496. effect.setVector3("direction2", this.direction2);
  51497. effect.setVector3("minEmitBox", this.minEmitBox);
  51498. effect.setVector3("maxEmitBox", this.maxEmitBox);
  51499. };
  51500. /**
  51501. * Returns a string to use to update the GPU particles update shader
  51502. * @returns a string containng the defines string
  51503. */
  51504. BoxParticleEmitter.prototype.getEffectDefines = function () {
  51505. return "#define BOXEMITTER";
  51506. };
  51507. /**
  51508. * Returns the string "BoxEmitter"
  51509. * @returns a string containing the class name
  51510. */
  51511. BoxParticleEmitter.prototype.getClassName = function () {
  51512. return "BoxEmitter";
  51513. };
  51514. /**
  51515. * Serializes the particle system to a JSON object.
  51516. * @returns the JSON object
  51517. */
  51518. BoxParticleEmitter.prototype.serialize = function () {
  51519. var serializationObject = {};
  51520. serializationObject.type = this.getClassName();
  51521. serializationObject.direction1 = this.direction1.asArray();
  51522. ;
  51523. serializationObject.direction2 = this.direction2.asArray();
  51524. ;
  51525. serializationObject.minEmitBox = this.minEmitBox.asArray();
  51526. ;
  51527. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  51528. ;
  51529. return serializationObject;
  51530. };
  51531. /**
  51532. * Parse properties from a JSON object
  51533. * @param serializationObject defines the JSON object
  51534. */
  51535. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  51536. this.direction1.copyFrom(serializationObject.direction1);
  51537. this.direction2.copyFrom(serializationObject.direction2);
  51538. this.minEmitBox.copyFrom(serializationObject.minEmitBox);
  51539. this.maxEmitBox.copyFrom(serializationObject.maxEmitBox);
  51540. };
  51541. return BoxParticleEmitter;
  51542. }());
  51543. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  51544. })(BABYLON || (BABYLON = {}));
  51545. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  51546. var BABYLON;
  51547. (function (BABYLON) {
  51548. /**
  51549. * Particle emitter emitting particles from the inside of a cone.
  51550. * It emits the particles alongside the cone volume from the base to the particle.
  51551. * The emission direction might be randomized.
  51552. */
  51553. var ConeParticleEmitter = /** @class */ (function () {
  51554. /**
  51555. * Creates a new instance of @see ConeParticleEmitter
  51556. * @param radius the radius of the emission cone (1 by default)
  51557. * @param angles the cone base angle (PI by default)
  51558. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  51559. */
  51560. function ConeParticleEmitter(radius,
  51561. /**
  51562. * The radius of the emission cone.
  51563. */
  51564. angle,
  51565. /**
  51566. * The cone base angle.
  51567. */
  51568. directionRandomizer) {
  51569. if (radius === void 0) { radius = 1; }
  51570. if (angle === void 0) { angle = Math.PI; }
  51571. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  51572. this.angle = angle;
  51573. this.directionRandomizer = directionRandomizer;
  51574. this.radius = radius;
  51575. }
  51576. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  51577. /**
  51578. * Gets the radius of the emission cone.
  51579. */
  51580. get: function () {
  51581. return this._radius;
  51582. },
  51583. /**
  51584. * Sets the radius of the emission cone.
  51585. */
  51586. set: function (value) {
  51587. this._radius = value;
  51588. if (this.angle !== 0) {
  51589. this._height = value / Math.tan(this.angle / 2);
  51590. }
  51591. else {
  51592. this._height = 1;
  51593. }
  51594. },
  51595. enumerable: true,
  51596. configurable: true
  51597. });
  51598. /**
  51599. * Called by the particle System when the direction is computed for the created particle.
  51600. * @param emitPower is the power of the particle (speed)
  51601. * @param worldMatrix is the world matrix of the particle system
  51602. * @param directionToUpdate is the direction vector to update with the result
  51603. * @param particle is the particle we are computed the direction for
  51604. */
  51605. ConeParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  51606. if (this.angle === 0) {
  51607. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, emitPower, 0, worldMatrix, directionToUpdate);
  51608. }
  51609. else {
  51610. // measure the direction Vector from the emitter to the particle.
  51611. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  51612. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  51613. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  51614. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  51615. direction.x += randX;
  51616. direction.y += randY;
  51617. direction.z += randZ;
  51618. direction.normalize();
  51619. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  51620. }
  51621. };
  51622. /**
  51623. * Called by the particle System when the position is computed for the created particle.
  51624. * @param worldMatrix is the world matrix of the particle system
  51625. * @param positionToUpdate is the position vector to update with the result
  51626. * @param particle is the particle we are computed the position for
  51627. */
  51628. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  51629. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  51630. var h = BABYLON.Scalar.RandomRange(0, 1);
  51631. // Better distribution in a cone at normal angles.
  51632. h = 1 - h * h;
  51633. var radius = BABYLON.Scalar.RandomRange(0, this._radius);
  51634. radius = radius * h / this._height;
  51635. var randX = radius * Math.sin(s);
  51636. var randZ = radius * Math.cos(s);
  51637. var randY = h * this._height;
  51638. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  51639. };
  51640. /**
  51641. * Clones the current emitter and returns a copy of it
  51642. * @returns the new emitter
  51643. */
  51644. ConeParticleEmitter.prototype.clone = function () {
  51645. var newOne = new ConeParticleEmitter(this.radius, this.angle, this.directionRandomizer);
  51646. BABYLON.Tools.DeepCopy(this, newOne);
  51647. return newOne;
  51648. };
  51649. /**
  51650. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  51651. * @param effect defines the update shader
  51652. */
  51653. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  51654. effect.setFloat("radius", this.radius);
  51655. effect.setFloat("angle", this.angle);
  51656. effect.setFloat("height", this._height);
  51657. effect.setFloat("directionRandomizer", this.directionRandomizer);
  51658. };
  51659. /**
  51660. * Returns a string to use to update the GPU particles update shader
  51661. * @returns a string containng the defines string
  51662. */
  51663. ConeParticleEmitter.prototype.getEffectDefines = function () {
  51664. return "#define CONEEMITTER";
  51665. };
  51666. /**
  51667. * Returns the string "BoxEmitter"
  51668. * @returns a string containing the class name
  51669. */
  51670. ConeParticleEmitter.prototype.getClassName = function () {
  51671. return "ConeEmitter";
  51672. };
  51673. /**
  51674. * Serializes the particle system to a JSON object.
  51675. * @returns the JSON object
  51676. */
  51677. ConeParticleEmitter.prototype.serialize = function () {
  51678. var serializationObject = {};
  51679. serializationObject.type = this.getClassName();
  51680. serializationObject.radius = this.radius;
  51681. serializationObject.angle = this.angle;
  51682. serializationObject.directionRandomizer = this.directionRandomizer;
  51683. return serializationObject;
  51684. };
  51685. /**
  51686. * Parse properties from a JSON object
  51687. * @param serializationObject defines the JSON object
  51688. */
  51689. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  51690. this.radius = serializationObject.radius;
  51691. this.angle = serializationObject.angle;
  51692. this.directionRandomizer = serializationObject.directionRandomizer;
  51693. };
  51694. return ConeParticleEmitter;
  51695. }());
  51696. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  51697. })(BABYLON || (BABYLON = {}));
  51698. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  51699. var BABYLON;
  51700. (function (BABYLON) {
  51701. /**
  51702. * Particle emitter emitting particles from the inside of a sphere.
  51703. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  51704. */
  51705. var SphereParticleEmitter = /** @class */ (function () {
  51706. /**
  51707. * Creates a new instance of @see SphereParticleEmitter
  51708. * @param radius the radius of the emission sphere (1 by default)
  51709. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  51710. */
  51711. function SphereParticleEmitter(
  51712. /**
  51713. * The radius of the emission sphere.
  51714. */
  51715. radius,
  51716. /**
  51717. * How much to randomize the particle direction [0-1].
  51718. */
  51719. directionRandomizer) {
  51720. if (radius === void 0) { radius = 1; }
  51721. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  51722. this.radius = radius;
  51723. this.directionRandomizer = directionRandomizer;
  51724. }
  51725. /**
  51726. * Called by the particle System when the direction is computed for the created particle.
  51727. * @param emitPower is the power of the particle (speed)
  51728. * @param worldMatrix is the world matrix of the particle system
  51729. * @param directionToUpdate is the direction vector to update with the result
  51730. * @param particle is the particle we are computed the direction for
  51731. */
  51732. SphereParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  51733. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  51734. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  51735. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  51736. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  51737. direction.x += randX;
  51738. direction.y += randY;
  51739. direction.z += randZ;
  51740. direction.normalize();
  51741. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  51742. };
  51743. /**
  51744. * Called by the particle System when the position is computed for the created particle.
  51745. * @param worldMatrix is the world matrix of the particle system
  51746. * @param positionToUpdate is the position vector to update with the result
  51747. * @param particle is the particle we are computed the position for
  51748. */
  51749. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  51750. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  51751. var theta = BABYLON.Scalar.RandomRange(0, Math.PI);
  51752. var randRadius = BABYLON.Scalar.RandomRange(0, this.radius);
  51753. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  51754. var randY = randRadius * Math.cos(theta);
  51755. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  51756. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  51757. };
  51758. /**
  51759. * Clones the current emitter and returns a copy of it
  51760. * @returns the new emitter
  51761. */
  51762. SphereParticleEmitter.prototype.clone = function () {
  51763. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  51764. BABYLON.Tools.DeepCopy(this, newOne);
  51765. return newOne;
  51766. };
  51767. /**
  51768. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  51769. * @param effect defines the update shader
  51770. */
  51771. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  51772. effect.setFloat("radius", this.radius);
  51773. effect.setFloat("directionRandomizer", this.directionRandomizer);
  51774. };
  51775. /**
  51776. * Returns a string to use to update the GPU particles update shader
  51777. * @returns a string containng the defines string
  51778. */
  51779. SphereParticleEmitter.prototype.getEffectDefines = function () {
  51780. return "#define SPHEREEMITTER";
  51781. };
  51782. /**
  51783. * Returns the string "SphereParticleEmitter"
  51784. * @returns a string containing the class name
  51785. */
  51786. SphereParticleEmitter.prototype.getClassName = function () {
  51787. return "SphereParticleEmitter";
  51788. };
  51789. /**
  51790. * Serializes the particle system to a JSON object.
  51791. * @returns the JSON object
  51792. */
  51793. SphereParticleEmitter.prototype.serialize = function () {
  51794. var serializationObject = {};
  51795. serializationObject.type = this.getClassName();
  51796. serializationObject.radius = this.radius;
  51797. serializationObject.directionRandomizer = this.directionRandomizer;
  51798. return serializationObject;
  51799. };
  51800. /**
  51801. * Parse properties from a JSON object
  51802. * @param serializationObject defines the JSON object
  51803. */
  51804. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  51805. this.radius = serializationObject.radius;
  51806. this.directionRandomizer = serializationObject.directionRandomizer;
  51807. };
  51808. return SphereParticleEmitter;
  51809. }());
  51810. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  51811. /**
  51812. * Particle emitter emitting particles from the inside of a sphere.
  51813. * It emits the particles randomly between two vectors.
  51814. */
  51815. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  51816. __extends(SphereDirectedParticleEmitter, _super);
  51817. /**
  51818. * Creates a new instance of @see SphereDirectedParticleEmitter
  51819. * @param radius the radius of the emission sphere (1 by default)
  51820. * @param direction1 the min limit of the emission direction (up vector by default)
  51821. * @param direction2 the max limit of the emission direction (up vector by default)
  51822. */
  51823. function SphereDirectedParticleEmitter(radius,
  51824. /**
  51825. * The min limit of the emission direction.
  51826. */
  51827. direction1,
  51828. /**
  51829. * The max limit of the emission direction.
  51830. */
  51831. direction2) {
  51832. if (radius === void 0) { radius = 1; }
  51833. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  51834. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  51835. var _this = _super.call(this, radius) || this;
  51836. _this.direction1 = direction1;
  51837. _this.direction2 = direction2;
  51838. return _this;
  51839. }
  51840. /**
  51841. * Called by the particle System when the direction is computed for the created particle.
  51842. * @param emitPower is the power of the particle (speed)
  51843. * @param worldMatrix is the world matrix of the particle system
  51844. * @param directionToUpdate is the direction vector to update with the result
  51845. * @param particle is the particle we are computed the direction for
  51846. */
  51847. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  51848. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  51849. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  51850. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  51851. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  51852. };
  51853. /**
  51854. * Clones the current emitter and returns a copy of it
  51855. * @returns the new emitter
  51856. */
  51857. SphereDirectedParticleEmitter.prototype.clone = function () {
  51858. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  51859. BABYLON.Tools.DeepCopy(this, newOne);
  51860. return newOne;
  51861. };
  51862. /**
  51863. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  51864. * @param effect defines the update shader
  51865. */
  51866. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  51867. effect.setFloat("radius", this.radius);
  51868. effect.setVector3("direction1", this.direction1);
  51869. effect.setVector3("direction2", this.direction2);
  51870. };
  51871. /**
  51872. * Returns a string to use to update the GPU particles update shader
  51873. * @returns a string containng the defines string
  51874. */
  51875. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  51876. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  51877. };
  51878. /**
  51879. * Returns the string "SphereDirectedParticleEmitter"
  51880. * @returns a string containing the class name
  51881. */
  51882. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  51883. return "SphereDirectedParticleEmitter";
  51884. };
  51885. /**
  51886. * Serializes the particle system to a JSON object.
  51887. * @returns the JSON object
  51888. */
  51889. SphereDirectedParticleEmitter.prototype.serialize = function () {
  51890. var serializationObject = _super.prototype.serialize.call(this);
  51891. ;
  51892. serializationObject.direction1 = this.direction1.asArray();
  51893. ;
  51894. serializationObject.direction2 = this.direction2.asArray();
  51895. ;
  51896. return serializationObject;
  51897. };
  51898. /**
  51899. * Parse properties from a JSON object
  51900. * @param serializationObject defines the JSON object
  51901. */
  51902. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  51903. _super.prototype.parse.call(this, serializationObject);
  51904. this.direction1.copyFrom(serializationObject.direction1);
  51905. this.direction2.copyFrom(serializationObject.direction2);
  51906. };
  51907. return SphereDirectedParticleEmitter;
  51908. }(SphereParticleEmitter));
  51909. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  51910. })(BABYLON || (BABYLON = {}));
  51911. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  51912. var __assign = (this && this.__assign) || Object.assign || function(t) {
  51913. for (var s, i = 1, n = arguments.length; i < n; i++) {
  51914. s = arguments[i];
  51915. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  51916. t[p] = s[p];
  51917. }
  51918. return t;
  51919. };
  51920. var BABYLON;
  51921. (function (BABYLON) {
  51922. /**
  51923. * This represents a GPU particle system in Babylon
  51924. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  51925. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  51926. */
  51927. var GPUParticleSystem = /** @class */ (function () {
  51928. /**
  51929. * Instantiates a GPU particle system.
  51930. * Particles are often small sprites used to simulate hard-to-reproduce phenomena like fire, smoke, water, or abstract visual effects like magic glitter and faery dust.
  51931. * @param name The name of the particle system
  51932. * @param capacity The max number of particles alive at the same time
  51933. * @param scene The scene the particle system belongs to
  51934. */
  51935. function GPUParticleSystem(name, options, scene) {
  51936. /**
  51937. * The emitter represents the Mesh or position we are attaching the particle system to.
  51938. */
  51939. this.emitter = null;
  51940. /**
  51941. * The rendering group used by the Particle system to chose when to render.
  51942. */
  51943. this.renderingGroupId = 0;
  51944. /**
  51945. * The layer mask we are rendering the particles through.
  51946. */
  51947. this.layerMask = 0x0FFFFFFF;
  51948. this._targetIndex = 0;
  51949. this._currentRenderId = -1;
  51950. this._started = false;
  51951. this._stopped = false;
  51952. this._timeDelta = 0;
  51953. this._attributesStrideSize = 14;
  51954. this._actualFrame = 0;
  51955. /**
  51956. * List of animations used by the particle system.
  51957. */
  51958. this.animations = [];
  51959. /**
  51960. * An event triggered when the system is disposed.
  51961. */
  51962. this.onDisposeObservable = new BABYLON.Observable();
  51963. /**
  51964. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  51965. */
  51966. this.updateSpeed = 0.01;
  51967. /**
  51968. * The amount of time the particle system is running (depends of the overall update speed).
  51969. */
  51970. this.targetStopDuration = 0;
  51971. /**
  51972. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  51973. */
  51974. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  51975. /**
  51976. * Minimum life time of emitting particles.
  51977. */
  51978. this.minLifeTime = 1;
  51979. /**
  51980. * Maximum life time of emitting particles.
  51981. */
  51982. this.maxLifeTime = 1;
  51983. /**
  51984. * Minimum Size of emitting particles.
  51985. */
  51986. this.minSize = 1;
  51987. /**
  51988. * Maximum Size of emitting particles.
  51989. */
  51990. this.maxSize = 1;
  51991. /**
  51992. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  51993. */
  51994. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  51995. /**
  51996. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  51997. */
  51998. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  51999. /**
  52000. * Color the particle will have at the end of its lifetime.
  52001. */
  52002. this.colorDead = new BABYLON.Color4(0, 0, 0, 0);
  52003. /**
  52004. * The maximum number of particles to emit per frame until we reach the activeParticleCount value
  52005. */
  52006. this.emitRate = 100;
  52007. /**
  52008. * You can use gravity if you want to give an orientation to your particles.
  52009. */
  52010. this.gravity = BABYLON.Vector3.Zero();
  52011. /**
  52012. * Minimum power of emitting particles.
  52013. */
  52014. this.minEmitPower = 1;
  52015. /**
  52016. * Maximum power of emitting particles.
  52017. */
  52018. this.maxEmitPower = 1;
  52019. this.id = name;
  52020. this.name = name;
  52021. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  52022. this._engine = this._scene.getEngine();
  52023. var fullOptions = __assign({ capacity: 50000, randomTextureSize: this._engine.getCaps().maxTextureSize }, options);
  52024. this._capacity = fullOptions.capacity;
  52025. this._activeCount = fullOptions.capacity;
  52026. this._currentActiveCount = 0;
  52027. this._scene.particleSystems.push(this);
  52028. this._updateEffectOptions = {
  52029. attributes: ["position", "age", "life", "seed", "size", "color", "direction"],
  52030. uniformsNames: ["currentCount", "timeDelta", "generalRandoms", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "gravity", "emitPower",
  52031. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "angle"],
  52032. uniformBuffersNames: [],
  52033. samplers: ["randomSampler"],
  52034. defines: "",
  52035. fallbacks: null,
  52036. onCompiled: null,
  52037. onError: null,
  52038. indexParameters: null,
  52039. maxSimultaneousLights: 0,
  52040. transformFeedbackVaryings: ["outPosition", "outAge", "outLife", "outSeed", "outSize", "outColor", "outDirection"]
  52041. };
  52042. // Random data
  52043. var maxTextureSize = Math.min(this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  52044. var d = [];
  52045. for (var i = 0; i < maxTextureSize; ++i) {
  52046. d.push(Math.random());
  52047. d.push(Math.random());
  52048. d.push(Math.random());
  52049. d.push(Math.random());
  52050. }
  52051. this._randomTexture = new BABYLON.RawTexture(new Float32Array(d), maxTextureSize, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA32F, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, BABYLON.Engine.TEXTURETYPE_FLOAT);
  52052. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  52053. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  52054. this._randomTextureSize = maxTextureSize;
  52055. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  52056. }
  52057. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  52058. /**
  52059. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  52060. */
  52061. get: function () {
  52062. if (!BABYLON.Engine.LastCreatedEngine) {
  52063. return false;
  52064. }
  52065. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  52066. },
  52067. enumerable: true,
  52068. configurable: true
  52069. });
  52070. Object.defineProperty(GPUParticleSystem.prototype, "direction1", {
  52071. /**
  52072. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  52073. * This only works when particleEmitterTyps is a BoxParticleEmitter
  52074. */
  52075. get: function () {
  52076. if (this.particleEmitterType.direction1) {
  52077. return this.particleEmitterType.direction1;
  52078. }
  52079. return BABYLON.Vector3.Zero();
  52080. },
  52081. set: function (value) {
  52082. if (this.particleEmitterType.direction1) {
  52083. this.particleEmitterType.direction1 = value;
  52084. }
  52085. },
  52086. enumerable: true,
  52087. configurable: true
  52088. });
  52089. Object.defineProperty(GPUParticleSystem.prototype, "direction2", {
  52090. /**
  52091. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  52092. * This only works when particleEmitterTyps is a BoxParticleEmitter
  52093. */
  52094. get: function () {
  52095. if (this.particleEmitterType.direction2) {
  52096. return this.particleEmitterType.direction2;
  52097. }
  52098. return BABYLON.Vector3.Zero();
  52099. },
  52100. set: function (value) {
  52101. if (this.particleEmitterType.direction2) {
  52102. this.particleEmitterType.direction2 = value;
  52103. }
  52104. },
  52105. enumerable: true,
  52106. configurable: true
  52107. });
  52108. Object.defineProperty(GPUParticleSystem.prototype, "minEmitBox", {
  52109. /**
  52110. * Minimum box point around our emitter. Our emitter is the center of particles source, but if you want your particles to emit from more than one point, then you can tell it to do so.
  52111. * This only works when particleEmitterTyps is a BoxParticleEmitter
  52112. */
  52113. get: function () {
  52114. if (this.particleEmitterType.minEmitBox) {
  52115. return this.particleEmitterType.minEmitBox;
  52116. }
  52117. return BABYLON.Vector3.Zero();
  52118. },
  52119. set: function (value) {
  52120. if (this.particleEmitterType.minEmitBox) {
  52121. this.particleEmitterType.minEmitBox = value;
  52122. }
  52123. },
  52124. enumerable: true,
  52125. configurable: true
  52126. });
  52127. Object.defineProperty(GPUParticleSystem.prototype, "maxEmitBox", {
  52128. /**
  52129. * Maximum box point around our emitter. Our emitter is the center of particles source, but if you want your particles to emit from more than one point, then you can tell it to do so.
  52130. * This only works when particleEmitterTyps is a BoxParticleEmitter
  52131. */
  52132. get: function () {
  52133. if (this.particleEmitterType.maxEmitBox) {
  52134. return this.particleEmitterType.maxEmitBox;
  52135. }
  52136. return BABYLON.Vector3.Zero();
  52137. },
  52138. set: function (value) {
  52139. if (this.particleEmitterType.maxEmitBox) {
  52140. this.particleEmitterType.maxEmitBox = value;
  52141. }
  52142. },
  52143. enumerable: true,
  52144. configurable: true
  52145. });
  52146. /**
  52147. * Gets the maximum number of particles active at the same time.
  52148. * @returns The max number of active particles.
  52149. */
  52150. GPUParticleSystem.prototype.getCapacity = function () {
  52151. return this._capacity;
  52152. };
  52153. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  52154. /**
  52155. * Gets or set the number of active particles
  52156. */
  52157. get: function () {
  52158. return this._activeCount;
  52159. },
  52160. set: function (value) {
  52161. this._activeCount = Math.min(value, this._capacity);
  52162. },
  52163. enumerable: true,
  52164. configurable: true
  52165. });
  52166. /**
  52167. * Gets Wether the system has been started.
  52168. * @returns True if it has been started, otherwise false.
  52169. */
  52170. GPUParticleSystem.prototype.isStarted = function () {
  52171. return this._started;
  52172. };
  52173. /**
  52174. * Starts the particle system and begins to emit.
  52175. */
  52176. GPUParticleSystem.prototype.start = function () {
  52177. this._started = true;
  52178. this._stopped = false;
  52179. };
  52180. /**
  52181. * Stops the particle system.
  52182. */
  52183. GPUParticleSystem.prototype.stop = function () {
  52184. this._stopped = true;
  52185. };
  52186. /**
  52187. * Remove all active particles
  52188. */
  52189. GPUParticleSystem.prototype.reset = function () {
  52190. this._releaseBuffers();
  52191. this._releaseVAOs();
  52192. this._currentActiveCount = 0;
  52193. this._targetIndex = 0;
  52194. };
  52195. /**
  52196. * Returns the string "GPUParticleSystem"
  52197. * @returns a string containing the class name
  52198. */
  52199. GPUParticleSystem.prototype.getClassName = function () {
  52200. return "GPUParticleSystem";
  52201. };
  52202. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  52203. var updateVertexBuffers = {};
  52204. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  52205. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  52206. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  52207. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 1);
  52208. updateVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1);
  52209. updateVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4);
  52210. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", 11, 3);
  52211. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  52212. this._engine.bindArrayBuffer(null);
  52213. return vao;
  52214. };
  52215. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  52216. var renderVertexBuffers = {};
  52217. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  52218. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  52219. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  52220. renderVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1, this._attributesStrideSize, true);
  52221. renderVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4, this._attributesStrideSize, true);
  52222. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  52223. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  52224. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  52225. this._engine.bindArrayBuffer(null);
  52226. return vao;
  52227. };
  52228. GPUParticleSystem.prototype._initialize = function (force) {
  52229. if (force === void 0) { force = false; }
  52230. if (this._buffer0 && !force) {
  52231. return;
  52232. }
  52233. var engine = this._scene.getEngine();
  52234. var data = new Array();
  52235. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  52236. // position
  52237. data.push(0.0);
  52238. data.push(0.0);
  52239. data.push(0.0);
  52240. // Age and life
  52241. data.push(0.0); // create the particle as a dead one to create a new one at start
  52242. data.push(0.0);
  52243. // Seed
  52244. data.push(Math.random());
  52245. // Size
  52246. data.push(0.0);
  52247. // color
  52248. data.push(0.0);
  52249. data.push(0.0);
  52250. data.push(0.0);
  52251. data.push(0.0);
  52252. // direction
  52253. data.push(0.0);
  52254. data.push(0.0);
  52255. data.push(0.0);
  52256. }
  52257. // Sprite data
  52258. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  52259. -0.5, 0.5, 0, 1,
  52260. -0.5, -0.5, 0, 0,
  52261. 0.5, -0.5, 1, 0]);
  52262. // Buffers
  52263. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  52264. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  52265. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  52266. // Update VAO
  52267. this._updateVAO = [];
  52268. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  52269. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  52270. // Render VAO
  52271. this._renderVAO = [];
  52272. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  52273. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  52274. // Links
  52275. this._sourceBuffer = this._buffer0;
  52276. this._targetBuffer = this._buffer1;
  52277. };
  52278. /** @ignore */
  52279. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  52280. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  52281. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  52282. return;
  52283. }
  52284. this._updateEffectOptions.defines = defines;
  52285. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  52286. };
  52287. /** @ignore */
  52288. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  52289. var defines = "";
  52290. if (this._scene.clipPlane) {
  52291. defines = "\n#define CLIPPLANE";
  52292. }
  52293. if (this._renderEffect && this._renderEffect.defines === defines) {
  52294. return;
  52295. }
  52296. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv"], ["view", "projection", "colorDead", "invView", "vClipPlane"], ["textureSampler"], this._scene.getEngine(), defines);
  52297. };
  52298. /**
  52299. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  52300. */
  52301. GPUParticleSystem.prototype.animate = function () {
  52302. if (!this._stopped) {
  52303. this._timeDelta = this.updateSpeed * this._scene.getAnimationRatio();
  52304. this._actualFrame += this._timeDelta;
  52305. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  52306. this.stop();
  52307. }
  52308. else {
  52309. this._timeDelta = 0;
  52310. }
  52311. };
  52312. /**
  52313. * Renders the particle system in its current state.
  52314. * @returns the current number of particles
  52315. */
  52316. GPUParticleSystem.prototype.render = function () {
  52317. if (!this._started) {
  52318. return 0;
  52319. }
  52320. this._recreateUpdateEffect();
  52321. this._recreateRenderEffect();
  52322. if (!this.emitter || !this._updateEffect.isReady() || !this._renderEffect.isReady()) {
  52323. return 0;
  52324. }
  52325. if (this._currentRenderId === this._scene.getRenderId()) {
  52326. return 0;
  52327. }
  52328. this._currentRenderId = this._scene.getRenderId();
  52329. // Get everything ready to render
  52330. this._initialize();
  52331. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + (this.emitRate * this._timeDelta) | 0);
  52332. // Enable update effect
  52333. this._engine.enableEffect(this._updateEffect);
  52334. this._engine.setState(false);
  52335. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  52336. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  52337. this._updateEffect.setFloat3("generalRandoms", Math.random(), Math.random(), Math.random());
  52338. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  52339. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  52340. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  52341. this._updateEffect.setDirectColor4("color1", this.color1);
  52342. this._updateEffect.setDirectColor4("color2", this.color2);
  52343. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  52344. this._updateEffect.setVector3("gravity", this.gravity);
  52345. if (this.particleEmitterType) {
  52346. this.particleEmitterType.applyToShader(this._updateEffect);
  52347. }
  52348. var emitterWM;
  52349. if (this.emitter.position) {
  52350. var emitterMesh = this.emitter;
  52351. emitterWM = emitterMesh.getWorldMatrix();
  52352. }
  52353. else {
  52354. var emitterPosition = this.emitter;
  52355. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  52356. }
  52357. this._updateEffect.setMatrix("emitterWM", emitterWM);
  52358. // Bind source VAO
  52359. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  52360. // Update
  52361. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  52362. this._engine.setRasterizerState(false);
  52363. this._engine.beginTransformFeedback();
  52364. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  52365. this._engine.endTransformFeedback();
  52366. this._engine.setRasterizerState(true);
  52367. this._engine.bindTransformFeedbackBuffer(null);
  52368. // Enable render effect
  52369. this._engine.enableEffect(this._renderEffect);
  52370. var viewMatrix = this._scene.getViewMatrix();
  52371. this._renderEffect.setMatrix("view", viewMatrix);
  52372. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  52373. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  52374. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  52375. if (this._scene.clipPlane) {
  52376. var clipPlane = this._scene.clipPlane;
  52377. var invView = viewMatrix.clone();
  52378. invView.invert();
  52379. this._renderEffect.setMatrix("invView", invView);
  52380. this._renderEffect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  52381. }
  52382. // Draw order
  52383. if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_ONEONE) {
  52384. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  52385. }
  52386. else {
  52387. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  52388. }
  52389. // Bind source VAO
  52390. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  52391. // Render
  52392. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  52393. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  52394. // Switch VAOs
  52395. this._targetIndex++;
  52396. if (this._targetIndex === 2) {
  52397. this._targetIndex = 0;
  52398. }
  52399. // Switch buffers
  52400. var tmpBuffer = this._sourceBuffer;
  52401. this._sourceBuffer = this._targetBuffer;
  52402. this._targetBuffer = tmpBuffer;
  52403. return this._currentActiveCount;
  52404. };
  52405. /**
  52406. * Rebuilds the particle system
  52407. */
  52408. GPUParticleSystem.prototype.rebuild = function () {
  52409. this._initialize(true);
  52410. };
  52411. GPUParticleSystem.prototype._releaseBuffers = function () {
  52412. if (this._buffer0) {
  52413. this._buffer0.dispose();
  52414. this._buffer0 = null;
  52415. }
  52416. if (this._buffer1) {
  52417. this._buffer1.dispose();
  52418. this._buffer1 = null;
  52419. }
  52420. if (this._spriteBuffer) {
  52421. this._spriteBuffer.dispose();
  52422. this._spriteBuffer = null;
  52423. }
  52424. };
  52425. GPUParticleSystem.prototype._releaseVAOs = function () {
  52426. for (var index = 0; index < this._updateVAO.length; index++) {
  52427. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  52428. }
  52429. this._updateVAO = [];
  52430. for (var index = 0; index < this._renderVAO.length; index++) {
  52431. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  52432. }
  52433. this._renderVAO = [];
  52434. };
  52435. /**
  52436. * Disposes the particle system and free the associated resources
  52437. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  52438. */
  52439. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  52440. if (disposeTexture === void 0) { disposeTexture = true; }
  52441. var index = this._scene.particleSystems.indexOf(this);
  52442. if (index > -1) {
  52443. this._scene.particleSystems.splice(index, 1);
  52444. }
  52445. this._releaseBuffers();
  52446. this._releaseVAOs();
  52447. if (this._randomTexture) {
  52448. this._randomTexture.dispose();
  52449. this._randomTexture = null;
  52450. }
  52451. if (disposeTexture && this.particleTexture) {
  52452. this.particleTexture.dispose();
  52453. this.particleTexture = null;
  52454. }
  52455. // Callback
  52456. this.onDisposeObservable.notifyObservers(this);
  52457. this.onDisposeObservable.clear();
  52458. };
  52459. /**
  52460. * Clones the particle system.
  52461. * @param name The name of the cloned object
  52462. * @param newEmitter The new emitter to use
  52463. * @returns the cloned particle system
  52464. */
  52465. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  52466. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  52467. BABYLON.Tools.DeepCopy(this, result);
  52468. if (newEmitter === undefined) {
  52469. newEmitter = this.emitter;
  52470. }
  52471. result.emitter = newEmitter;
  52472. if (this.particleTexture) {
  52473. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  52474. }
  52475. return result;
  52476. };
  52477. /**
  52478. * Serializes the particle system to a JSON object.
  52479. * @returns the JSON object
  52480. */
  52481. GPUParticleSystem.prototype.serialize = function () {
  52482. var serializationObject = {};
  52483. serializationObject.name = this.name;
  52484. serializationObject.id = this.id;
  52485. // Emitter
  52486. if (this.emitter.position) {
  52487. var emitterMesh = this.emitter;
  52488. serializationObject.emitterId = emitterMesh.id;
  52489. }
  52490. else {
  52491. var emitterPosition = this.emitter;
  52492. serializationObject.emitter = emitterPosition.asArray();
  52493. }
  52494. serializationObject.capacity = this.getCapacity();
  52495. if (this.particleTexture) {
  52496. serializationObject.textureName = this.particleTexture.name;
  52497. }
  52498. // Animations
  52499. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  52500. // Particle system
  52501. serializationObject.activeParticleCount = this.activeParticleCount;
  52502. serializationObject.randomTextureSize = this._randomTextureSize;
  52503. serializationObject.minSize = this.minSize;
  52504. serializationObject.maxSize = this.maxSize;
  52505. serializationObject.minEmitPower = this.minEmitPower;
  52506. serializationObject.maxEmitPower = this.maxEmitPower;
  52507. serializationObject.minLifeTime = this.minLifeTime;
  52508. serializationObject.maxLifeTime = this.maxLifeTime;
  52509. serializationObject.emitRate = this.emitRate;
  52510. serializationObject.gravity = this.gravity.asArray();
  52511. serializationObject.color1 = this.color1.asArray();
  52512. serializationObject.color2 = this.color2.asArray();
  52513. serializationObject.colorDead = this.colorDead.asArray();
  52514. serializationObject.updateSpeed = this.updateSpeed;
  52515. serializationObject.targetStopDuration = this.targetStopDuration;
  52516. serializationObject.blendMode = this.blendMode;
  52517. // Emitter
  52518. if (this.particleEmitterType) {
  52519. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  52520. }
  52521. return serializationObject;
  52522. };
  52523. /**
  52524. * Parses a JSON object to create a GPU particle system.
  52525. * @param parsedParticleSystem The JSON object to parse
  52526. * @param scene The scene to create the particle system in
  52527. * @param rootUrl The root url to use to load external dependencies like texture
  52528. * @returns the parsed GPU particle system
  52529. */
  52530. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  52531. var name = parsedParticleSystem.name;
  52532. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  52533. if (parsedParticleSystem.id) {
  52534. particleSystem.id = parsedParticleSystem.id;
  52535. }
  52536. // Texture
  52537. if (parsedParticleSystem.textureName) {
  52538. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  52539. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  52540. }
  52541. // Emitter
  52542. if (parsedParticleSystem.emitterId) {
  52543. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  52544. }
  52545. else {
  52546. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  52547. }
  52548. // Animations
  52549. if (parsedParticleSystem.animations) {
  52550. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  52551. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  52552. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  52553. }
  52554. }
  52555. // Particle system
  52556. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  52557. particleSystem.minSize = parsedParticleSystem.minSize;
  52558. particleSystem.maxSize = parsedParticleSystem.maxSize;
  52559. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  52560. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  52561. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  52562. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  52563. particleSystem.emitRate = parsedParticleSystem.emitRate;
  52564. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  52565. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  52566. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  52567. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  52568. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  52569. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  52570. particleSystem.blendMode = parsedParticleSystem.blendMode;
  52571. // Emitter
  52572. if (parsedParticleSystem.particleEmitterType) {
  52573. var emitterType = void 0;
  52574. switch (parsedParticleSystem.particleEmitterType.type) {
  52575. case "SphereEmitter":
  52576. emitterType = new BABYLON.SphereParticleEmitter();
  52577. break;
  52578. case "SphereDirectedParticleEmitter":
  52579. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  52580. break;
  52581. case "ConeEmitter":
  52582. emitterType = new BABYLON.ConeParticleEmitter();
  52583. break;
  52584. case "BoxEmitter":
  52585. default:
  52586. emitterType = new BABYLON.BoxParticleEmitter();
  52587. break;
  52588. }
  52589. emitterType.parse(parsedParticleSystem.particleEmitterType);
  52590. particleSystem.particleEmitterType = emitterType;
  52591. }
  52592. return particleSystem;
  52593. };
  52594. return GPUParticleSystem;
  52595. }());
  52596. BABYLON.GPUParticleSystem = GPUParticleSystem;
  52597. })(BABYLON || (BABYLON = {}));
  52598. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  52599. var BABYLON;
  52600. (function (BABYLON) {
  52601. /**
  52602. * Represents one particle of a solid particle system.
  52603. * @see SolidParticleSystem
  52604. */
  52605. var SolidParticle = /** @class */ (function () {
  52606. /**
  52607. * Creates a Solid Particle object.
  52608. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  52609. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  52610. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  52611. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  52612. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  52613. * @param shapeId (integer) is the model shape identifier in the SPS.
  52614. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  52615. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  52616. */
  52617. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  52618. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  52619. /**
  52620. * particle global index
  52621. */
  52622. this.idx = 0;
  52623. /**
  52624. * The color of the particle
  52625. */
  52626. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  52627. /**
  52628. * The world space position of the particle.
  52629. */
  52630. this.position = BABYLON.Vector3.Zero();
  52631. /**
  52632. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  52633. */
  52634. this.rotation = BABYLON.Vector3.Zero();
  52635. /**
  52636. * The scaling of the particle.
  52637. */
  52638. this.scaling = BABYLON.Vector3.One();
  52639. /**
  52640. * The uvs of the particle.
  52641. */
  52642. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  52643. /**
  52644. * The current speed of the particle.
  52645. */
  52646. this.velocity = BABYLON.Vector3.Zero();
  52647. /**
  52648. * The pivot point in the particle local space.
  52649. */
  52650. this.pivot = BABYLON.Vector3.Zero();
  52651. /**
  52652. * Must the particle be translated from its pivot point in its local space ?
  52653. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  52654. * Default : false
  52655. */
  52656. this.translateFromPivot = false;
  52657. /**
  52658. * Is the particle active or not ?
  52659. */
  52660. this.alive = true;
  52661. /**
  52662. * Is the particle visible or not ?
  52663. */
  52664. this.isVisible = true;
  52665. /**
  52666. * Index of this particle in the global "positions" array (Internal use)
  52667. */
  52668. this._pos = 0;
  52669. /**
  52670. * Index of this particle in the global "indices" array (Internal use)
  52671. */
  52672. this._ind = 0;
  52673. /**
  52674. * ModelShape id of this particle
  52675. */
  52676. this.shapeId = 0;
  52677. /**
  52678. * Index of the particle in its shape id (Internal use)
  52679. */
  52680. this.idxInShape = 0;
  52681. /**
  52682. * Still set as invisible in order to skip useless computations (Internal use)
  52683. */
  52684. this._stillInvisible = false;
  52685. /**
  52686. * Last computed particle rotation matrix
  52687. */
  52688. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  52689. /**
  52690. * Parent particle Id, if any.
  52691. * Default null.
  52692. */
  52693. this.parentId = null;
  52694. /**
  52695. * Internal global position in the SPS.
  52696. */
  52697. this._globalPosition = BABYLON.Vector3.Zero();
  52698. this.idx = particleIndex;
  52699. this._pos = positionIndex;
  52700. this._ind = indiceIndex;
  52701. this._model = model;
  52702. this.shapeId = shapeId;
  52703. this.idxInShape = idxInShape;
  52704. this._sps = sps;
  52705. if (modelBoundingInfo) {
  52706. this._modelBoundingInfo = modelBoundingInfo;
  52707. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  52708. }
  52709. }
  52710. Object.defineProperty(SolidParticle.prototype, "scale", {
  52711. /**
  52712. * Legacy support, changed scale to scaling
  52713. */
  52714. get: function () {
  52715. return this.scaling;
  52716. },
  52717. /**
  52718. * Legacy support, changed scale to scaling
  52719. */
  52720. set: function (scale) {
  52721. this.scaling = scale;
  52722. },
  52723. enumerable: true,
  52724. configurable: true
  52725. });
  52726. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  52727. /**
  52728. * Legacy support, changed quaternion to rotationQuaternion
  52729. */
  52730. get: function () {
  52731. return this.rotationQuaternion;
  52732. },
  52733. /**
  52734. * Legacy support, changed quaternion to rotationQuaternion
  52735. */
  52736. set: function (q) {
  52737. this.rotationQuaternion = q;
  52738. },
  52739. enumerable: true,
  52740. configurable: true
  52741. });
  52742. /**
  52743. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  52744. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  52745. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  52746. * @returns true if it intersects
  52747. */
  52748. SolidParticle.prototype.intersectsMesh = function (target) {
  52749. if (!this._boundingInfo || !target._boundingInfo) {
  52750. return false;
  52751. }
  52752. if (this._sps._bSphereOnly) {
  52753. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  52754. }
  52755. return this._boundingInfo.intersects(target._boundingInfo, false);
  52756. };
  52757. return SolidParticle;
  52758. }());
  52759. BABYLON.SolidParticle = SolidParticle;
  52760. /**
  52761. * Represents the shape of the model used by one particle of a solid particle system.
  52762. * SPS internal tool, don't use it manually.
  52763. * @see SolidParticleSystem
  52764. */
  52765. var ModelShape = /** @class */ (function () {
  52766. /**
  52767. * 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.
  52768. * SPS internal tool, don't use it manually.
  52769. * @ignore
  52770. */
  52771. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  52772. /**
  52773. * length of the shape in the model indices array (internal use)
  52774. */
  52775. this._indicesLength = 0;
  52776. this.shapeID = id;
  52777. this._shape = shape;
  52778. this._indicesLength = indicesLength;
  52779. this._shapeUV = shapeUV;
  52780. this._positionFunction = posFunction;
  52781. this._vertexFunction = vtxFunction;
  52782. }
  52783. return ModelShape;
  52784. }());
  52785. BABYLON.ModelShape = ModelShape;
  52786. /**
  52787. * Represents a Depth Sorted Particle in the solid particle system.
  52788. * @see SolidParticleSystem
  52789. */
  52790. var DepthSortedParticle = /** @class */ (function () {
  52791. function DepthSortedParticle() {
  52792. /**
  52793. * Index of the particle in the "indices" array
  52794. */
  52795. this.ind = 0;
  52796. /**
  52797. * Length of the particle shape in the "indices" array
  52798. */
  52799. this.indicesLength = 0;
  52800. /**
  52801. * Squared distance from the particle to the camera
  52802. */
  52803. this.sqDistance = 0.0;
  52804. }
  52805. return DepthSortedParticle;
  52806. }());
  52807. BABYLON.DepthSortedParticle = DepthSortedParticle;
  52808. })(BABYLON || (BABYLON = {}));
  52809. //# sourceMappingURL=babylon.solidParticle.js.map
  52810. var BABYLON;
  52811. (function (BABYLON) {
  52812. /**
  52813. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  52814. *As it is just a mesh, the SPS has all the same properties than any other BJS mesh : not more, not less. It can be scaled, rotated, translated, enlighted, textured, moved, etc.
  52815. * The SPS is also a particle system. It provides some methods to manage the particles.
  52816. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  52817. *
  52818. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  52819. */
  52820. var SolidParticleSystem = /** @class */ (function () {
  52821. /**
  52822. * Creates a SPS (Solid Particle System) object.
  52823. * @param name (String) is the SPS name, this will be the underlying mesh name.
  52824. * @param scene (Scene) is the scene in which the SPS is added.
  52825. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  52826. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  52827. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  52828. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  52829. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  52830. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  52831. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  52832. */
  52833. function SolidParticleSystem(name, scene, options) {
  52834. /**
  52835. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  52836. * Example : var p = SPS.particles[i];
  52837. */
  52838. this.particles = new Array();
  52839. /**
  52840. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  52841. */
  52842. this.nbParticles = 0;
  52843. /**
  52844. * If the particles must ever face the camera (default false). Useful for planar particles.
  52845. */
  52846. this.billboard = false;
  52847. /**
  52848. * Recompute normals when adding a shape
  52849. */
  52850. this.recomputeNormals = true;
  52851. /**
  52852. * This a counter ofr your own usage. It's not set by any SPS functions.
  52853. */
  52854. this.counter = 0;
  52855. /**
  52856. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  52857. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  52858. */
  52859. this.vars = {};
  52860. /**
  52861. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  52862. */
  52863. this._bSphereOnly = false;
  52864. /**
  52865. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  52866. */
  52867. this._bSphereRadiusFactor = 1.0;
  52868. this._positions = new Array();
  52869. this._indices = new Array();
  52870. this._normals = new Array();
  52871. this._colors = new Array();
  52872. this._uvs = new Array();
  52873. this._index = 0; // indices index
  52874. this._updatable = true;
  52875. this._pickable = false;
  52876. this._isVisibilityBoxLocked = false;
  52877. this._alwaysVisible = false;
  52878. this._depthSort = false;
  52879. this._shapeCounter = 0;
  52880. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  52881. this._color = new BABYLON.Color4(0, 0, 0, 0);
  52882. this._computeParticleColor = true;
  52883. this._computeParticleTexture = true;
  52884. this._computeParticleRotation = true;
  52885. this._computeParticleVertex = false;
  52886. this._computeBoundingBox = false;
  52887. this._depthSortParticles = true;
  52888. this._cam_axisZ = BABYLON.Vector3.Zero();
  52889. this._cam_axisY = BABYLON.Vector3.Zero();
  52890. this._cam_axisX = BABYLON.Vector3.Zero();
  52891. this._axisZ = BABYLON.Axis.Z;
  52892. this._camDir = BABYLON.Vector3.Zero();
  52893. this._camInvertedPosition = BABYLON.Vector3.Zero();
  52894. this._rotMatrix = new BABYLON.Matrix();
  52895. this._invertMatrix = new BABYLON.Matrix();
  52896. this._rotated = BABYLON.Vector3.Zero();
  52897. this._quaternion = new BABYLON.Quaternion();
  52898. this._vertex = BABYLON.Vector3.Zero();
  52899. this._normal = BABYLON.Vector3.Zero();
  52900. this._yaw = 0.0;
  52901. this._pitch = 0.0;
  52902. this._roll = 0.0;
  52903. this._halfroll = 0.0;
  52904. this._halfpitch = 0.0;
  52905. this._halfyaw = 0.0;
  52906. this._sinRoll = 0.0;
  52907. this._cosRoll = 0.0;
  52908. this._sinPitch = 0.0;
  52909. this._cosPitch = 0.0;
  52910. this._sinYaw = 0.0;
  52911. this._cosYaw = 0.0;
  52912. this._mustUnrotateFixedNormals = false;
  52913. this._minimum = BABYLON.Vector3.Zero();
  52914. this._maximum = BABYLON.Vector3.Zero();
  52915. this._minBbox = BABYLON.Vector3.Zero();
  52916. this._maxBbox = BABYLON.Vector3.Zero();
  52917. this._particlesIntersect = false;
  52918. this._depthSortFunction = function (p1, p2) {
  52919. return (p2.sqDistance - p1.sqDistance);
  52920. };
  52921. this._needs32Bits = false;
  52922. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  52923. this._scaledPivot = BABYLON.Vector3.Zero();
  52924. this._particleHasParent = false;
  52925. this.name = name;
  52926. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  52927. this._camera = scene.activeCamera;
  52928. this._pickable = options ? options.isPickable : false;
  52929. this._depthSort = options ? options.enableDepthSort : false;
  52930. this._particlesIntersect = options ? options.particleIntersection : false;
  52931. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  52932. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  52933. if (options && options.updatable) {
  52934. this._updatable = options.updatable;
  52935. }
  52936. else {
  52937. this._updatable = true;
  52938. }
  52939. if (this._pickable) {
  52940. this.pickedParticles = [];
  52941. }
  52942. if (this._depthSort) {
  52943. this.depthSortedParticles = [];
  52944. }
  52945. }
  52946. /**
  52947. * Builds the SPS underlying mesh. Returns a standard Mesh.
  52948. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  52949. * @returns the created mesh
  52950. */
  52951. SolidParticleSystem.prototype.buildMesh = function () {
  52952. if (this.nbParticles === 0) {
  52953. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  52954. this.addShape(triangle, 1);
  52955. triangle.dispose();
  52956. }
  52957. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  52958. this._positions32 = new Float32Array(this._positions);
  52959. this._uvs32 = new Float32Array(this._uvs);
  52960. this._colors32 = new Float32Array(this._colors);
  52961. if (this.recomputeNormals) {
  52962. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  52963. }
  52964. this._normals32 = new Float32Array(this._normals);
  52965. this._fixedNormal32 = new Float32Array(this._normals);
  52966. if (this._mustUnrotateFixedNormals) {
  52967. this._unrotateFixedNormals();
  52968. }
  52969. var vertexData = new BABYLON.VertexData();
  52970. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  52971. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  52972. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  52973. if (this._uvs32) {
  52974. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  52975. ;
  52976. }
  52977. if (this._colors32) {
  52978. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  52979. }
  52980. var mesh = new BABYLON.Mesh(this.name, this._scene);
  52981. vertexData.applyToMesh(mesh, this._updatable);
  52982. this.mesh = mesh;
  52983. this.mesh.isPickable = this._pickable;
  52984. // free memory
  52985. if (!this._depthSort) {
  52986. this._indices = null;
  52987. }
  52988. this._positions = null;
  52989. this._normals = null;
  52990. this._uvs = null;
  52991. this._colors = null;
  52992. if (!this._updatable) {
  52993. this.particles.length = 0;
  52994. }
  52995. return mesh;
  52996. };
  52997. /**
  52998. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  52999. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  53000. * Thus the particles generated from `digest()` have their property `position` set yet.
  53001. * @param mesh ( Mesh ) is the mesh to be digested
  53002. * @param options {facetNb} (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any
  53003. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  53004. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  53005. * @returns the current SPS
  53006. */
  53007. SolidParticleSystem.prototype.digest = function (mesh, options) {
  53008. var size = (options && options.facetNb) || 1;
  53009. var number = (options && options.number) || 0;
  53010. var delta = (options && options.delta) || 0;
  53011. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  53012. var meshInd = mesh.getIndices();
  53013. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  53014. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  53015. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  53016. var f = 0; // facet counter
  53017. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  53018. // compute size from number
  53019. if (number) {
  53020. number = (number > totalFacets) ? totalFacets : number;
  53021. size = Math.round(totalFacets / number);
  53022. delta = 0;
  53023. }
  53024. else {
  53025. size = (size > totalFacets) ? totalFacets : size;
  53026. }
  53027. var facetPos = []; // submesh positions
  53028. var facetInd = []; // submesh indices
  53029. var facetUV = []; // submesh UV
  53030. var facetCol = []; // submesh colors
  53031. var barycenter = BABYLON.Vector3.Zero();
  53032. var sizeO = size;
  53033. while (f < totalFacets) {
  53034. size = sizeO + Math.floor((1 + delta) * Math.random());
  53035. if (f > totalFacets - size) {
  53036. size = totalFacets - f;
  53037. }
  53038. // reset temp arrays
  53039. facetPos.length = 0;
  53040. facetInd.length = 0;
  53041. facetUV.length = 0;
  53042. facetCol.length = 0;
  53043. // iterate over "size" facets
  53044. var fi = 0;
  53045. for (var j = f * 3; j < (f + size) * 3; j++) {
  53046. facetInd.push(fi);
  53047. var i = meshInd[j];
  53048. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  53049. if (meshUV) {
  53050. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  53051. }
  53052. if (meshCol) {
  53053. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  53054. }
  53055. fi++;
  53056. }
  53057. // create a model shape for each single particle
  53058. var idx = this.nbParticles;
  53059. var shape = this._posToShape(facetPos);
  53060. var shapeUV = this._uvsToShapeUV(facetUV);
  53061. // compute the barycenter of the shape
  53062. var v;
  53063. for (v = 0; v < shape.length; v++) {
  53064. barycenter.addInPlace(shape[v]);
  53065. }
  53066. barycenter.scaleInPlace(1 / shape.length);
  53067. // shift the shape from its barycenter to the origin
  53068. for (v = 0; v < shape.length; v++) {
  53069. shape[v].subtractInPlace(barycenter);
  53070. }
  53071. var bInfo;
  53072. if (this._particlesIntersect) {
  53073. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  53074. }
  53075. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  53076. // add the particle in the SPS
  53077. var currentPos = this._positions.length;
  53078. var currentInd = this._indices.length;
  53079. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  53080. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  53081. // initialize the particle position
  53082. this.particles[this.nbParticles].position.addInPlace(barycenter);
  53083. this._index += shape.length;
  53084. idx++;
  53085. this.nbParticles++;
  53086. this._shapeCounter++;
  53087. f += size;
  53088. }
  53089. return this;
  53090. };
  53091. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  53092. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  53093. var index = 0;
  53094. var idx = 0;
  53095. for (var p = 0; p < this.particles.length; p++) {
  53096. this._particle = this.particles[p];
  53097. this._shape = this._particle._model._shape;
  53098. if (this._particle.rotationQuaternion) {
  53099. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  53100. }
  53101. else {
  53102. this._yaw = this._particle.rotation.y;
  53103. this._pitch = this._particle.rotation.x;
  53104. this._roll = this._particle.rotation.z;
  53105. this._quaternionRotationYPR();
  53106. }
  53107. this._quaternionToRotationMatrix();
  53108. this._rotMatrix.invertToRef(this._invertMatrix);
  53109. for (var pt = 0; pt < this._shape.length; pt++) {
  53110. idx = index + pt * 3;
  53111. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  53112. this._fixedNormal32[idx] = this._normal.x;
  53113. this._fixedNormal32[idx + 1] = this._normal.y;
  53114. this._fixedNormal32[idx + 2] = this._normal.z;
  53115. }
  53116. index = idx + 3;
  53117. }
  53118. };
  53119. //reset copy
  53120. SolidParticleSystem.prototype._resetCopy = function () {
  53121. this._copy.position.x = 0;
  53122. this._copy.position.y = 0;
  53123. this._copy.position.z = 0;
  53124. this._copy.rotation.x = 0;
  53125. this._copy.rotation.y = 0;
  53126. this._copy.rotation.z = 0;
  53127. this._copy.rotationQuaternion = null;
  53128. this._copy.scaling.x = 1.0;
  53129. this._copy.scaling.y = 1.0;
  53130. this._copy.scaling.z = 1.0;
  53131. this._copy.uvs.x = 0;
  53132. this._copy.uvs.y = 0;
  53133. this._copy.uvs.z = 1.0;
  53134. this._copy.uvs.w = 1.0;
  53135. this._copy.color = null;
  53136. this._copy.translateFromPivot = false;
  53137. };
  53138. // _meshBuilder : inserts the shape model in the global SPS mesh
  53139. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  53140. var i;
  53141. var u = 0;
  53142. var c = 0;
  53143. var n = 0;
  53144. this._resetCopy();
  53145. if (options && options.positionFunction) {
  53146. options.positionFunction(this._copy, idx, idxInShape);
  53147. this._mustUnrotateFixedNormals = true;
  53148. }
  53149. if (this._copy.rotationQuaternion) {
  53150. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  53151. }
  53152. else {
  53153. this._yaw = this._copy.rotation.y;
  53154. this._pitch = this._copy.rotation.x;
  53155. this._roll = this._copy.rotation.z;
  53156. this._quaternionRotationYPR();
  53157. }
  53158. this._quaternionToRotationMatrix();
  53159. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  53160. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  53161. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  53162. if (this._copy.translateFromPivot) {
  53163. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  53164. }
  53165. else {
  53166. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  53167. }
  53168. for (i = 0; i < shape.length; i++) {
  53169. this._vertex.x = shape[i].x;
  53170. this._vertex.y = shape[i].y;
  53171. this._vertex.z = shape[i].z;
  53172. if (options && options.vertexFunction) {
  53173. options.vertexFunction(this._copy, this._vertex, i);
  53174. }
  53175. this._vertex.x *= this._copy.scaling.x;
  53176. this._vertex.y *= this._copy.scaling.y;
  53177. this._vertex.z *= this._copy.scaling.z;
  53178. this._vertex.x -= this._scaledPivot.x;
  53179. this._vertex.y -= this._scaledPivot.y;
  53180. this._vertex.z -= this._scaledPivot.z;
  53181. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  53182. this._rotated.addInPlace(this._pivotBackTranslation);
  53183. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  53184. if (meshUV) {
  53185. 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);
  53186. u += 2;
  53187. }
  53188. if (this._copy.color) {
  53189. this._color = this._copy.color;
  53190. }
  53191. else if (meshCol && meshCol[c] !== undefined) {
  53192. this._color.r = meshCol[c];
  53193. this._color.g = meshCol[c + 1];
  53194. this._color.b = meshCol[c + 2];
  53195. this._color.a = meshCol[c + 3];
  53196. }
  53197. else {
  53198. this._color.r = 1.0;
  53199. this._color.g = 1.0;
  53200. this._color.b = 1.0;
  53201. this._color.a = 1.0;
  53202. }
  53203. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  53204. c += 4;
  53205. if (!this.recomputeNormals && meshNor) {
  53206. this._normal.x = meshNor[n];
  53207. this._normal.y = meshNor[n + 1];
  53208. this._normal.z = meshNor[n + 2];
  53209. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  53210. normals.push(this._normal.x, this._normal.y, this._normal.z);
  53211. n += 3;
  53212. }
  53213. }
  53214. for (i = 0; i < meshInd.length; i++) {
  53215. var current_ind = p + meshInd[i];
  53216. indices.push(current_ind);
  53217. if (current_ind > 65535) {
  53218. this._needs32Bits = true;
  53219. }
  53220. }
  53221. if (this._pickable) {
  53222. var nbfaces = meshInd.length / 3;
  53223. for (i = 0; i < nbfaces; i++) {
  53224. this.pickedParticles.push({ idx: idx, faceId: i });
  53225. }
  53226. }
  53227. if (this._depthSort) {
  53228. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  53229. }
  53230. return this._copy;
  53231. };
  53232. // returns a shape array from positions array
  53233. SolidParticleSystem.prototype._posToShape = function (positions) {
  53234. var shape = [];
  53235. for (var i = 0; i < positions.length; i += 3) {
  53236. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  53237. }
  53238. return shape;
  53239. };
  53240. // returns a shapeUV array from a Vector4 uvs
  53241. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  53242. var shapeUV = [];
  53243. if (uvs) {
  53244. for (var i = 0; i < uvs.length; i++)
  53245. shapeUV.push(uvs[i]);
  53246. }
  53247. return shapeUV;
  53248. };
  53249. // adds a new particle object in the particles array
  53250. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  53251. if (bInfo === void 0) { bInfo = null; }
  53252. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  53253. this.particles.push(sp);
  53254. return sp;
  53255. };
  53256. /**
  53257. * Adds some particles to the SPS from the model shape. Returns the shape id.
  53258. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  53259. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  53260. * @param nb (positive integer) the number of particles to be created from this model
  53261. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  53262. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  53263. * @returns the number of shapes in the system
  53264. */
  53265. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  53266. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  53267. var meshInd = mesh.getIndices();
  53268. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  53269. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  53270. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  53271. var bbInfo;
  53272. if (this._particlesIntersect) {
  53273. bbInfo = mesh.getBoundingInfo();
  53274. }
  53275. var shape = this._posToShape(meshPos);
  53276. var shapeUV = this._uvsToShapeUV(meshUV);
  53277. var posfunc = options ? options.positionFunction : null;
  53278. var vtxfunc = options ? options.vertexFunction : null;
  53279. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  53280. // particles
  53281. var sp;
  53282. var currentCopy;
  53283. var idx = this.nbParticles;
  53284. for (var i = 0; i < nb; i++) {
  53285. var currentPos = this._positions.length;
  53286. var currentInd = this._indices.length;
  53287. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  53288. if (this._updatable) {
  53289. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  53290. sp.position.copyFrom(currentCopy.position);
  53291. sp.rotation.copyFrom(currentCopy.rotation);
  53292. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  53293. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  53294. }
  53295. if (currentCopy.color && sp.color) {
  53296. sp.color.copyFrom(currentCopy.color);
  53297. }
  53298. sp.scaling.copyFrom(currentCopy.scaling);
  53299. sp.uvs.copyFrom(currentCopy.uvs);
  53300. }
  53301. this._index += shape.length;
  53302. idx++;
  53303. }
  53304. this.nbParticles += nb;
  53305. this._shapeCounter++;
  53306. return this._shapeCounter - 1;
  53307. };
  53308. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  53309. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  53310. this._resetCopy();
  53311. if (particle._model._positionFunction) {
  53312. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  53313. }
  53314. if (this._copy.rotationQuaternion) {
  53315. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  53316. }
  53317. else {
  53318. this._yaw = this._copy.rotation.y;
  53319. this._pitch = this._copy.rotation.x;
  53320. this._roll = this._copy.rotation.z;
  53321. this._quaternionRotationYPR();
  53322. }
  53323. this._quaternionToRotationMatrix();
  53324. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  53325. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  53326. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  53327. if (this._copy.translateFromPivot) {
  53328. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  53329. }
  53330. else {
  53331. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  53332. }
  53333. this._shape = particle._model._shape;
  53334. for (var pt = 0; pt < this._shape.length; pt++) {
  53335. this._vertex.x = this._shape[pt].x;
  53336. this._vertex.y = this._shape[pt].y;
  53337. this._vertex.z = this._shape[pt].z;
  53338. if (particle._model._vertexFunction) {
  53339. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  53340. }
  53341. this._vertex.x *= this._copy.scaling.x;
  53342. this._vertex.y *= this._copy.scaling.y;
  53343. this._vertex.z *= this._copy.scaling.z;
  53344. this._vertex.x -= this._scaledPivot.x;
  53345. this._vertex.y -= this._scaledPivot.y;
  53346. this._vertex.z -= this._scaledPivot.z;
  53347. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  53348. this._rotated.addInPlace(this._pivotBackTranslation);
  53349. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  53350. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  53351. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  53352. }
  53353. particle.position.x = 0.0;
  53354. particle.position.y = 0.0;
  53355. particle.position.z = 0.0;
  53356. particle.rotation.x = 0.0;
  53357. particle.rotation.y = 0.0;
  53358. particle.rotation.z = 0.0;
  53359. particle.rotationQuaternion = null;
  53360. particle.scaling.x = 1.0;
  53361. particle.scaling.y = 1.0;
  53362. particle.scaling.z = 1.0;
  53363. particle.uvs.x = 0.0;
  53364. particle.uvs.y = 0.0;
  53365. particle.uvs.z = 1.0;
  53366. particle.uvs.w = 1.0;
  53367. particle.pivot.x = 0.0;
  53368. particle.pivot.y = 0.0;
  53369. particle.pivot.z = 0.0;
  53370. particle.translateFromPivot = false;
  53371. particle.parentId = null;
  53372. };
  53373. /**
  53374. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  53375. * @returns the SPS.
  53376. */
  53377. SolidParticleSystem.prototype.rebuildMesh = function () {
  53378. for (var p = 0; p < this.particles.length; p++) {
  53379. this._rebuildParticle(this.particles[p]);
  53380. }
  53381. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  53382. return this;
  53383. };
  53384. /**
  53385. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  53386. * This method calls `updateParticle()` for each particle of the SPS.
  53387. * For an animated SPS, it is usually called within the render loop.
  53388. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  53389. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  53390. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  53391. * @returns the SPS.
  53392. */
  53393. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  53394. if (start === void 0) { start = 0; }
  53395. if (end === void 0) { end = this.nbParticles - 1; }
  53396. if (update === void 0) { update = true; }
  53397. if (!this._updatable) {
  53398. return this;
  53399. }
  53400. // custom beforeUpdate
  53401. this.beforeUpdateParticles(start, end, update);
  53402. this._cam_axisX.x = 1.0;
  53403. this._cam_axisX.y = 0.0;
  53404. this._cam_axisX.z = 0.0;
  53405. this._cam_axisY.x = 0.0;
  53406. this._cam_axisY.y = 1.0;
  53407. this._cam_axisY.z = 0.0;
  53408. this._cam_axisZ.x = 0.0;
  53409. this._cam_axisZ.y = 0.0;
  53410. this._cam_axisZ.z = 1.0;
  53411. // cases when the World Matrix is to be computed first
  53412. if (this.billboard || this._depthSort) {
  53413. this.mesh.computeWorldMatrix(true);
  53414. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  53415. }
  53416. // if the particles will always face the camera
  53417. if (this.billboard) {
  53418. // compute the camera position and un-rotate it by the current mesh rotation
  53419. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  53420. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  53421. this._cam_axisZ.normalize();
  53422. // same for camera up vector extracted from the cam view matrix
  53423. var view = this._camera.getViewMatrix(true);
  53424. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  53425. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  53426. this._cam_axisY.normalize();
  53427. this._cam_axisX.normalize();
  53428. }
  53429. // if depthSort, compute the camera global position in the mesh local system
  53430. if (this._depthSort) {
  53431. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  53432. }
  53433. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  53434. var idx = 0; // current position index in the global array positions32
  53435. var index = 0; // position start index in the global array positions32 of the current particle
  53436. var colidx = 0; // current color index in the global array colors32
  53437. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  53438. var uvidx = 0; // current uv index in the global array uvs32
  53439. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  53440. var pt = 0; // current index in the particle model shape
  53441. if (this.mesh.isFacetDataEnabled) {
  53442. this._computeBoundingBox = true;
  53443. }
  53444. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  53445. if (this._computeBoundingBox) {
  53446. if (start == 0 && end == this.nbParticles - 1) {
  53447. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  53448. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  53449. }
  53450. else {
  53451. if (this.mesh._boundingInfo) {
  53452. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  53453. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  53454. }
  53455. }
  53456. }
  53457. // particle loop
  53458. index = this.particles[start]._pos;
  53459. var vpos = (index / 3) | 0;
  53460. colorIndex = vpos * 4;
  53461. uvIndex = vpos * 2;
  53462. for (var p = start; p <= end; p++) {
  53463. this._particle = this.particles[p];
  53464. this._shape = this._particle._model._shape;
  53465. this._shapeUV = this._particle._model._shapeUV;
  53466. // call to custom user function to update the particle properties
  53467. this.updateParticle(this._particle);
  53468. // camera-particle distance for depth sorting
  53469. if (this._depthSort && this._depthSortParticles) {
  53470. var dsp = this.depthSortedParticles[p];
  53471. dsp.ind = this._particle._ind;
  53472. dsp.indicesLength = this._particle._model._indicesLength;
  53473. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  53474. }
  53475. // skip the computations for inactive or already invisible particles
  53476. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  53477. // increment indexes for the next particle
  53478. pt = this._shape.length;
  53479. index += pt * 3;
  53480. colorIndex += pt * 4;
  53481. uvIndex += pt * 2;
  53482. continue;
  53483. }
  53484. if (this._particle.isVisible) {
  53485. this._particle._stillInvisible = false; // un-mark permanent invisibility
  53486. this._particleHasParent = (this._particle.parentId !== null);
  53487. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  53488. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  53489. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  53490. // particle rotation matrix
  53491. if (this.billboard) {
  53492. this._particle.rotation.x = 0.0;
  53493. this._particle.rotation.y = 0.0;
  53494. }
  53495. if (this._computeParticleRotation || this.billboard) {
  53496. if (this._particle.rotationQuaternion) {
  53497. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  53498. }
  53499. else {
  53500. this._yaw = this._particle.rotation.y;
  53501. this._pitch = this._particle.rotation.x;
  53502. this._roll = this._particle.rotation.z;
  53503. this._quaternionRotationYPR();
  53504. }
  53505. this._quaternionToRotationMatrix();
  53506. }
  53507. if (this._particleHasParent) {
  53508. this._parent = this.particles[this._particle.parentId];
  53509. this._rotated.x = this._particle.position.x * this._parent._rotationMatrix[0] + this._particle.position.y * this._parent._rotationMatrix[3] + this._particle.position.z * this._parent._rotationMatrix[6];
  53510. this._rotated.y = this._particle.position.x * this._parent._rotationMatrix[1] + this._particle.position.y * this._parent._rotationMatrix[4] + this._particle.position.z * this._parent._rotationMatrix[7];
  53511. this._rotated.z = this._particle.position.x * this._parent._rotationMatrix[2] + this._particle.position.y * this._parent._rotationMatrix[5] + this._particle.position.z * this._parent._rotationMatrix[8];
  53512. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  53513. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  53514. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  53515. if (this._computeParticleRotation || this.billboard) {
  53516. this._particle._rotationMatrix[0] = this._rotMatrix.m[0] * this._parent._rotationMatrix[0] + this._rotMatrix.m[1] * this._parent._rotationMatrix[3] + this._rotMatrix.m[2] * this._parent._rotationMatrix[6];
  53517. this._particle._rotationMatrix[1] = this._rotMatrix.m[0] * this._parent._rotationMatrix[1] + this._rotMatrix.m[1] * this._parent._rotationMatrix[4] + this._rotMatrix.m[2] * this._parent._rotationMatrix[7];
  53518. this._particle._rotationMatrix[2] = this._rotMatrix.m[0] * this._parent._rotationMatrix[2] + this._rotMatrix.m[1] * this._parent._rotationMatrix[5] + this._rotMatrix.m[2] * this._parent._rotationMatrix[8];
  53519. this._particle._rotationMatrix[3] = this._rotMatrix.m[4] * this._parent._rotationMatrix[0] + this._rotMatrix.m[5] * this._parent._rotationMatrix[3] + this._rotMatrix.m[6] * this._parent._rotationMatrix[6];
  53520. this._particle._rotationMatrix[4] = this._rotMatrix.m[4] * this._parent._rotationMatrix[1] + this._rotMatrix.m[5] * this._parent._rotationMatrix[4] + this._rotMatrix.m[6] * this._parent._rotationMatrix[7];
  53521. this._particle._rotationMatrix[5] = this._rotMatrix.m[4] * this._parent._rotationMatrix[2] + this._rotMatrix.m[5] * this._parent._rotationMatrix[5] + this._rotMatrix.m[6] * this._parent._rotationMatrix[8];
  53522. this._particle._rotationMatrix[6] = this._rotMatrix.m[8] * this._parent._rotationMatrix[0] + this._rotMatrix.m[9] * this._parent._rotationMatrix[3] + this._rotMatrix.m[10] * this._parent._rotationMatrix[6];
  53523. this._particle._rotationMatrix[7] = this._rotMatrix.m[8] * this._parent._rotationMatrix[1] + this._rotMatrix.m[9] * this._parent._rotationMatrix[4] + this._rotMatrix.m[10] * this._parent._rotationMatrix[7];
  53524. this._particle._rotationMatrix[8] = this._rotMatrix.m[8] * this._parent._rotationMatrix[2] + this._rotMatrix.m[9] * this._parent._rotationMatrix[5] + this._rotMatrix.m[10] * this._parent._rotationMatrix[8];
  53525. }
  53526. }
  53527. else {
  53528. this._particle._globalPosition.x = this._particle.position.x;
  53529. this._particle._globalPosition.y = this._particle.position.y;
  53530. this._particle._globalPosition.z = this._particle.position.z;
  53531. if (this._computeParticleRotation || this.billboard) {
  53532. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  53533. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  53534. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  53535. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  53536. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  53537. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  53538. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  53539. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  53540. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  53541. }
  53542. }
  53543. if (this._particle.translateFromPivot) {
  53544. this._pivotBackTranslation.x = 0.0;
  53545. this._pivotBackTranslation.y = 0.0;
  53546. this._pivotBackTranslation.z = 0.0;
  53547. }
  53548. else {
  53549. this._pivotBackTranslation.x = this._scaledPivot.x;
  53550. this._pivotBackTranslation.y = this._scaledPivot.y;
  53551. this._pivotBackTranslation.z = this._scaledPivot.z;
  53552. }
  53553. // particle vertex loop
  53554. for (pt = 0; pt < this._shape.length; pt++) {
  53555. idx = index + pt * 3;
  53556. colidx = colorIndex + pt * 4;
  53557. uvidx = uvIndex + pt * 2;
  53558. this._vertex.x = this._shape[pt].x;
  53559. this._vertex.y = this._shape[pt].y;
  53560. this._vertex.z = this._shape[pt].z;
  53561. if (this._computeParticleVertex) {
  53562. this.updateParticleVertex(this._particle, this._vertex, pt);
  53563. }
  53564. // positions
  53565. this._vertex.x *= this._particle.scaling.x;
  53566. this._vertex.y *= this._particle.scaling.y;
  53567. this._vertex.z *= this._particle.scaling.z;
  53568. this._vertex.x -= this._scaledPivot.x;
  53569. this._vertex.y -= this._scaledPivot.y;
  53570. this._vertex.z -= this._scaledPivot.z;
  53571. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  53572. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  53573. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  53574. this._rotated.x += this._pivotBackTranslation.x;
  53575. this._rotated.y += this._pivotBackTranslation.y;
  53576. this._rotated.z += this._pivotBackTranslation.z;
  53577. this._positions32[idx] = this._particle._globalPosition.x + this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  53578. this._positions32[idx + 1] = this._particle._globalPosition.y + this._cam_axisX.y * this._rotated.x + this._cam_axisY.y * this._rotated.y + this._cam_axisZ.y * this._rotated.z;
  53579. this._positions32[idx + 2] = this._particle._globalPosition.z + this._cam_axisX.z * this._rotated.x + this._cam_axisY.z * this._rotated.y + this._cam_axisZ.z * this._rotated.z;
  53580. if (this._computeBoundingBox) {
  53581. if (this._positions32[idx] < this._minimum.x) {
  53582. this._minimum.x = this._positions32[idx];
  53583. }
  53584. if (this._positions32[idx] > this._maximum.x) {
  53585. this._maximum.x = this._positions32[idx];
  53586. }
  53587. if (this._positions32[idx + 1] < this._minimum.y) {
  53588. this._minimum.y = this._positions32[idx + 1];
  53589. }
  53590. if (this._positions32[idx + 1] > this._maximum.y) {
  53591. this._maximum.y = this._positions32[idx + 1];
  53592. }
  53593. if (this._positions32[idx + 2] < this._minimum.z) {
  53594. this._minimum.z = this._positions32[idx + 2];
  53595. }
  53596. if (this._positions32[idx + 2] > this._maximum.z) {
  53597. this._maximum.z = this._positions32[idx + 2];
  53598. }
  53599. }
  53600. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  53601. if (!this._computeParticleVertex) {
  53602. this._normal.x = this._fixedNormal32[idx];
  53603. this._normal.y = this._fixedNormal32[idx + 1];
  53604. this._normal.z = this._fixedNormal32[idx + 2];
  53605. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  53606. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  53607. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  53608. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  53609. 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;
  53610. 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;
  53611. }
  53612. if (this._computeParticleColor && this._particle.color) {
  53613. this._colors32[colidx] = this._particle.color.r;
  53614. this._colors32[colidx + 1] = this._particle.color.g;
  53615. this._colors32[colidx + 2] = this._particle.color.b;
  53616. this._colors32[colidx + 3] = this._particle.color.a;
  53617. }
  53618. if (this._computeParticleTexture) {
  53619. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  53620. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  53621. }
  53622. }
  53623. }
  53624. else {
  53625. this._particle._stillInvisible = true; // mark the particle as invisible
  53626. for (pt = 0; pt < this._shape.length; pt++) {
  53627. idx = index + pt * 3;
  53628. colidx = colorIndex + pt * 4;
  53629. uvidx = uvIndex + pt * 2;
  53630. this._positions32[idx] = 0.0;
  53631. this._positions32[idx + 1] = 0.0;
  53632. this._positions32[idx + 2] = 0.0;
  53633. this._normals32[idx] = 0.0;
  53634. this._normals32[idx + 1] = 0.0;
  53635. this._normals32[idx + 2] = 0.0;
  53636. if (this._computeParticleColor && this._particle.color) {
  53637. this._colors32[colidx] = this._particle.color.r;
  53638. this._colors32[colidx + 1] = this._particle.color.g;
  53639. this._colors32[colidx + 2] = this._particle.color.b;
  53640. this._colors32[colidx + 3] = this._particle.color.a;
  53641. }
  53642. if (this._computeParticleTexture) {
  53643. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  53644. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  53645. }
  53646. }
  53647. }
  53648. // if the particle intersections must be computed : update the bbInfo
  53649. if (this._particlesIntersect) {
  53650. var bInfo = this._particle._boundingInfo;
  53651. var bBox = bInfo.boundingBox;
  53652. var bSphere = bInfo.boundingSphere;
  53653. if (!this._bSphereOnly) {
  53654. // place, scale and rotate the particle bbox within the SPS local system, then update it
  53655. for (var b = 0; b < bBox.vectors.length; b++) {
  53656. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  53657. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  53658. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  53659. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  53660. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  53661. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  53662. 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;
  53663. 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;
  53664. 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;
  53665. }
  53666. bBox._update(this.mesh._worldMatrix);
  53667. }
  53668. // place and scale the particle bouding sphere in the SPS local system, then update it
  53669. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  53670. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  53671. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  53672. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  53673. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  53674. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  53675. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  53676. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  53677. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  53678. 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));
  53679. bSphere._update(this.mesh._worldMatrix);
  53680. }
  53681. // increment indexes for the next particle
  53682. index = idx + 3;
  53683. colorIndex = colidx + 4;
  53684. uvIndex = uvidx + 2;
  53685. }
  53686. // if the VBO must be updated
  53687. if (update) {
  53688. if (this._computeParticleColor) {
  53689. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  53690. }
  53691. if (this._computeParticleTexture) {
  53692. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  53693. }
  53694. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  53695. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  53696. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  53697. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  53698. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  53699. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  53700. for (var i = 0; i < this._normals32.length; i++) {
  53701. this._fixedNormal32[i] = this._normals32[i];
  53702. }
  53703. }
  53704. if (!this.mesh.areNormalsFrozen) {
  53705. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  53706. }
  53707. }
  53708. if (this._depthSort && this._depthSortParticles) {
  53709. this.depthSortedParticles.sort(this._depthSortFunction);
  53710. var dspl = this.depthSortedParticles.length;
  53711. var sorted = 0;
  53712. var lind = 0;
  53713. var sind = 0;
  53714. var sid = 0;
  53715. for (sorted = 0; sorted < dspl; sorted++) {
  53716. lind = this.depthSortedParticles[sorted].indicesLength;
  53717. sind = this.depthSortedParticles[sorted].ind;
  53718. for (var i = 0; i < lind; i++) {
  53719. this._indices32[sid] = this._indices[sind + i];
  53720. sid++;
  53721. }
  53722. }
  53723. this.mesh.updateIndices(this._indices32);
  53724. }
  53725. }
  53726. if (this._computeBoundingBox) {
  53727. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  53728. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  53729. }
  53730. this.afterUpdateParticles(start, end, update);
  53731. return this;
  53732. };
  53733. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  53734. this._halfroll = this._roll * 0.5;
  53735. this._halfpitch = this._pitch * 0.5;
  53736. this._halfyaw = this._yaw * 0.5;
  53737. this._sinRoll = Math.sin(this._halfroll);
  53738. this._cosRoll = Math.cos(this._halfroll);
  53739. this._sinPitch = Math.sin(this._halfpitch);
  53740. this._cosPitch = Math.cos(this._halfpitch);
  53741. this._sinYaw = Math.sin(this._halfyaw);
  53742. this._cosYaw = Math.cos(this._halfyaw);
  53743. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  53744. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  53745. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  53746. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  53747. };
  53748. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  53749. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  53750. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  53751. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  53752. this._rotMatrix.m[3] = 0;
  53753. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  53754. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  53755. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  53756. this._rotMatrix.m[7] = 0;
  53757. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  53758. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  53759. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  53760. this._rotMatrix.m[11] = 0;
  53761. this._rotMatrix.m[12] = 0;
  53762. this._rotMatrix.m[13] = 0;
  53763. this._rotMatrix.m[14] = 0;
  53764. this._rotMatrix.m[15] = 1.0;
  53765. };
  53766. /**
  53767. * Disposes the SPS.
  53768. */
  53769. SolidParticleSystem.prototype.dispose = function () {
  53770. this.mesh.dispose();
  53771. this.vars = null;
  53772. // drop references to internal big arrays for the GC
  53773. this._positions = null;
  53774. this._indices = null;
  53775. this._normals = null;
  53776. this._uvs = null;
  53777. this._colors = null;
  53778. this._indices32 = null;
  53779. this._positions32 = null;
  53780. this._normals32 = null;
  53781. this._fixedNormal32 = null;
  53782. this._uvs32 = null;
  53783. this._colors32 = null;
  53784. this.pickedParticles = null;
  53785. };
  53786. /**
  53787. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  53788. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  53789. * @returns the SPS.
  53790. */
  53791. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  53792. if (!this._isVisibilityBoxLocked) {
  53793. this.mesh.refreshBoundingInfo();
  53794. }
  53795. return this;
  53796. };
  53797. /**
  53798. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  53799. * @param size the size (float) of the visibility box
  53800. * note : this doesn't lock the SPS mesh bounding box.
  53801. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  53802. */
  53803. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  53804. var vis = size / 2;
  53805. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  53806. };
  53807. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  53808. /**
  53809. * Gets whether the SPS as always visible or not
  53810. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  53811. */
  53812. get: function () {
  53813. return this._alwaysVisible;
  53814. },
  53815. /**
  53816. * Sets the SPS as always visible or not
  53817. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  53818. */
  53819. set: function (val) {
  53820. this._alwaysVisible = val;
  53821. this.mesh.alwaysSelectAsActiveMesh = val;
  53822. },
  53823. enumerable: true,
  53824. configurable: true
  53825. });
  53826. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  53827. /**
  53828. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  53829. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  53830. */
  53831. get: function () {
  53832. return this._isVisibilityBoxLocked;
  53833. },
  53834. /**
  53835. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  53836. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  53837. */
  53838. set: function (val) {
  53839. this._isVisibilityBoxLocked = val;
  53840. var boundingInfo = this.mesh.getBoundingInfo();
  53841. boundingInfo.isLocked = val;
  53842. },
  53843. enumerable: true,
  53844. configurable: true
  53845. });
  53846. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  53847. /**
  53848. * Gets if `setParticles()` computes the particle rotations or not.
  53849. * Default value : true. The SPS is faster when it's set to false.
  53850. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  53851. */
  53852. get: function () {
  53853. return this._computeParticleRotation;
  53854. },
  53855. /**
  53856. * Tells to `setParticles()` to compute the particle rotations or not.
  53857. * Default value : true. The SPS is faster when it's set to false.
  53858. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  53859. */
  53860. set: function (val) {
  53861. this._computeParticleRotation = val;
  53862. },
  53863. enumerable: true,
  53864. configurable: true
  53865. });
  53866. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  53867. /**
  53868. * Gets if `setParticles()` computes the particle colors or not.
  53869. * Default value : true. The SPS is faster when it's set to false.
  53870. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  53871. */
  53872. get: function () {
  53873. return this._computeParticleColor;
  53874. },
  53875. /**
  53876. * Tells to `setParticles()` to compute the particle colors or not.
  53877. * Default value : true. The SPS is faster when it's set to false.
  53878. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  53879. */
  53880. set: function (val) {
  53881. this._computeParticleColor = val;
  53882. },
  53883. enumerable: true,
  53884. configurable: true
  53885. });
  53886. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  53887. /**
  53888. * Gets if `setParticles()` computes the particle textures or not.
  53889. * Default value : true. The SPS is faster when it's set to false.
  53890. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  53891. */
  53892. get: function () {
  53893. return this._computeParticleTexture;
  53894. },
  53895. set: function (val) {
  53896. this._computeParticleTexture = val;
  53897. },
  53898. enumerable: true,
  53899. configurable: true
  53900. });
  53901. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  53902. /**
  53903. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  53904. * Default value : false. The SPS is faster when it's set to false.
  53905. * Note : the particle custom vertex positions aren't stored values.
  53906. */
  53907. get: function () {
  53908. return this._computeParticleVertex;
  53909. },
  53910. /**
  53911. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  53912. * Default value : false. The SPS is faster when it's set to false.
  53913. * Note : the particle custom vertex positions aren't stored values.
  53914. */
  53915. set: function (val) {
  53916. this._computeParticleVertex = val;
  53917. },
  53918. enumerable: true,
  53919. configurable: true
  53920. });
  53921. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  53922. /**
  53923. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  53924. */
  53925. get: function () {
  53926. return this._computeBoundingBox;
  53927. },
  53928. /**
  53929. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  53930. */
  53931. set: function (val) {
  53932. this._computeBoundingBox = val;
  53933. },
  53934. enumerable: true,
  53935. configurable: true
  53936. });
  53937. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  53938. /**
  53939. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  53940. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  53941. * Default : `true`
  53942. */
  53943. get: function () {
  53944. return this._depthSortParticles;
  53945. },
  53946. /**
  53947. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  53948. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  53949. * Default : `true`
  53950. */
  53951. set: function (val) {
  53952. this._depthSortParticles = val;
  53953. },
  53954. enumerable: true,
  53955. configurable: true
  53956. });
  53957. // =======================================================================
  53958. // Particle behavior logic
  53959. // these following methods may be overwritten by the user to fit his needs
  53960. /**
  53961. * This function does nothing. It may be overwritten to set all the particle first values.
  53962. * The SPS doesn't call this function, you may have to call it by your own.
  53963. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  53964. */
  53965. SolidParticleSystem.prototype.initParticles = function () {
  53966. };
  53967. /**
  53968. * This function does nothing. It may be overwritten to recycle a particle.
  53969. * The SPS doesn't call this function, you may have to call it by your own.
  53970. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  53971. * @param particle The particle to recycle
  53972. * @returns the recycled particle
  53973. */
  53974. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  53975. return particle;
  53976. };
  53977. /**
  53978. * Updates a particle : this function should be overwritten by the user.
  53979. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  53980. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  53981. * @example : just set a particle position or velocity and recycle conditions
  53982. * @param particle The particle to update
  53983. * @returns the updated particle
  53984. */
  53985. SolidParticleSystem.prototype.updateParticle = function (particle) {
  53986. return particle;
  53987. };
  53988. /**
  53989. * Updates a vertex of a particle : it can be overwritten by the user.
  53990. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  53991. * @param particle the current particle
  53992. * @param vertex the current index of the current particle
  53993. * @param pt the index of the current vertex in the particle shape
  53994. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  53995. * @example : just set a vertex particle position
  53996. * @returns the updated vertex
  53997. */
  53998. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  53999. return vertex;
  54000. };
  54001. /**
  54002. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  54003. * This does nothing and may be overwritten by the user.
  54004. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  54005. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  54006. * @param update the boolean update value actually passed to setParticles()
  54007. */
  54008. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  54009. };
  54010. /**
  54011. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  54012. * This will be passed three parameters.
  54013. * This does nothing and may be overwritten by the user.
  54014. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  54015. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  54016. * @param update the boolean update value actually passed to setParticles()
  54017. */
  54018. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  54019. };
  54020. return SolidParticleSystem;
  54021. }());
  54022. BABYLON.SolidParticleSystem = SolidParticleSystem;
  54023. })(BABYLON || (BABYLON = {}));
  54024. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  54025. var BABYLON;
  54026. (function (BABYLON) {
  54027. var ShaderMaterial = /** @class */ (function (_super) {
  54028. __extends(ShaderMaterial, _super);
  54029. function ShaderMaterial(name, scene, shaderPath, options) {
  54030. var _this = _super.call(this, name, scene) || this;
  54031. _this._textures = {};
  54032. _this._textureArrays = {};
  54033. _this._floats = {};
  54034. _this._ints = {};
  54035. _this._floatsArrays = {};
  54036. _this._colors3 = {};
  54037. _this._colors3Arrays = {};
  54038. _this._colors4 = {};
  54039. _this._vectors2 = {};
  54040. _this._vectors3 = {};
  54041. _this._vectors4 = {};
  54042. _this._matrices = {};
  54043. _this._matrices3x3 = {};
  54044. _this._matrices2x2 = {};
  54045. _this._vectors2Arrays = {};
  54046. _this._vectors3Arrays = {};
  54047. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  54048. _this._shaderPath = shaderPath;
  54049. options.needAlphaBlending = options.needAlphaBlending || false;
  54050. options.needAlphaTesting = options.needAlphaTesting || false;
  54051. options.attributes = options.attributes || ["position", "normal", "uv"];
  54052. options.uniforms = options.uniforms || ["worldViewProjection"];
  54053. options.uniformBuffers = options.uniformBuffers || [];
  54054. options.samplers = options.samplers || [];
  54055. options.defines = options.defines || [];
  54056. _this._options = options;
  54057. return _this;
  54058. }
  54059. ShaderMaterial.prototype.getClassName = function () {
  54060. return "ShaderMaterial";
  54061. };
  54062. ShaderMaterial.prototype.needAlphaBlending = function () {
  54063. return this._options.needAlphaBlending;
  54064. };
  54065. ShaderMaterial.prototype.needAlphaTesting = function () {
  54066. return this._options.needAlphaTesting;
  54067. };
  54068. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  54069. if (this._options.uniforms.indexOf(uniformName) === -1) {
  54070. this._options.uniforms.push(uniformName);
  54071. }
  54072. };
  54073. ShaderMaterial.prototype.setTexture = function (name, texture) {
  54074. if (this._options.samplers.indexOf(name) === -1) {
  54075. this._options.samplers.push(name);
  54076. }
  54077. this._textures[name] = texture;
  54078. return this;
  54079. };
  54080. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  54081. if (this._options.samplers.indexOf(name) === -1) {
  54082. this._options.samplers.push(name);
  54083. }
  54084. this._checkUniform(name);
  54085. this._textureArrays[name] = textures;
  54086. return this;
  54087. };
  54088. ShaderMaterial.prototype.setFloat = function (name, value) {
  54089. this._checkUniform(name);
  54090. this._floats[name] = value;
  54091. return this;
  54092. };
  54093. ShaderMaterial.prototype.setInt = function (name, value) {
  54094. this._checkUniform(name);
  54095. this._ints[name] = value;
  54096. return this;
  54097. };
  54098. ShaderMaterial.prototype.setFloats = function (name, value) {
  54099. this._checkUniform(name);
  54100. this._floatsArrays[name] = value;
  54101. return this;
  54102. };
  54103. ShaderMaterial.prototype.setColor3 = function (name, value) {
  54104. this._checkUniform(name);
  54105. this._colors3[name] = value;
  54106. return this;
  54107. };
  54108. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  54109. this._checkUniform(name);
  54110. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  54111. color.toArray(arr, arr.length);
  54112. return arr;
  54113. }, []);
  54114. return this;
  54115. };
  54116. ShaderMaterial.prototype.setColor4 = function (name, value) {
  54117. this._checkUniform(name);
  54118. this._colors4[name] = value;
  54119. return this;
  54120. };
  54121. ShaderMaterial.prototype.setVector2 = function (name, value) {
  54122. this._checkUniform(name);
  54123. this._vectors2[name] = value;
  54124. return this;
  54125. };
  54126. ShaderMaterial.prototype.setVector3 = function (name, value) {
  54127. this._checkUniform(name);
  54128. this._vectors3[name] = value;
  54129. return this;
  54130. };
  54131. ShaderMaterial.prototype.setVector4 = function (name, value) {
  54132. this._checkUniform(name);
  54133. this._vectors4[name] = value;
  54134. return this;
  54135. };
  54136. ShaderMaterial.prototype.setMatrix = function (name, value) {
  54137. this._checkUniform(name);
  54138. this._matrices[name] = value;
  54139. return this;
  54140. };
  54141. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  54142. this._checkUniform(name);
  54143. this._matrices3x3[name] = value;
  54144. return this;
  54145. };
  54146. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  54147. this._checkUniform(name);
  54148. this._matrices2x2[name] = value;
  54149. return this;
  54150. };
  54151. ShaderMaterial.prototype.setArray2 = function (name, value) {
  54152. this._checkUniform(name);
  54153. this._vectors2Arrays[name] = value;
  54154. return this;
  54155. };
  54156. ShaderMaterial.prototype.setArray3 = function (name, value) {
  54157. this._checkUniform(name);
  54158. this._vectors3Arrays[name] = value;
  54159. return this;
  54160. };
  54161. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  54162. if (!mesh) {
  54163. return true;
  54164. }
  54165. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  54166. return false;
  54167. }
  54168. return false;
  54169. };
  54170. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  54171. var scene = this.getScene();
  54172. var engine = scene.getEngine();
  54173. if (!this.checkReadyOnEveryCall) {
  54174. if (this._renderId === scene.getRenderId()) {
  54175. if (this._checkCache(scene, mesh, useInstances)) {
  54176. return true;
  54177. }
  54178. }
  54179. }
  54180. // Instances
  54181. var defines = [];
  54182. var attribs = [];
  54183. var fallbacks = new BABYLON.EffectFallbacks();
  54184. if (useInstances) {
  54185. defines.push("#define INSTANCES");
  54186. }
  54187. for (var index = 0; index < this._options.defines.length; index++) {
  54188. defines.push(this._options.defines[index]);
  54189. }
  54190. for (var index = 0; index < this._options.attributes.length; index++) {
  54191. attribs.push(this._options.attributes[index]);
  54192. }
  54193. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  54194. attribs.push(BABYLON.VertexBuffer.ColorKind);
  54195. defines.push("#define VERTEXCOLOR");
  54196. }
  54197. // Bones
  54198. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  54199. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  54200. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  54201. if (mesh.numBoneInfluencers > 4) {
  54202. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  54203. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  54204. }
  54205. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  54206. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  54207. fallbacks.addCPUSkinningFallback(0, mesh);
  54208. if (this._options.uniforms.indexOf("mBones") === -1) {
  54209. this._options.uniforms.push("mBones");
  54210. }
  54211. }
  54212. else {
  54213. defines.push("#define NUM_BONE_INFLUENCERS 0");
  54214. }
  54215. // Textures
  54216. for (var name in this._textures) {
  54217. if (!this._textures[name].isReady()) {
  54218. return false;
  54219. }
  54220. }
  54221. // Alpha test
  54222. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  54223. defines.push("#define ALPHATEST");
  54224. }
  54225. var previousEffect = this._effect;
  54226. var join = defines.join("\n");
  54227. this._effect = engine.createEffect(this._shaderPath, {
  54228. attributes: attribs,
  54229. uniformsNames: this._options.uniforms,
  54230. uniformBuffersNames: this._options.uniformBuffers,
  54231. samplers: this._options.samplers,
  54232. defines: join,
  54233. fallbacks: fallbacks,
  54234. onCompiled: this.onCompiled,
  54235. onError: this.onError
  54236. }, engine);
  54237. if (!this._effect.isReady()) {
  54238. return false;
  54239. }
  54240. if (previousEffect !== this._effect) {
  54241. scene.resetCachedMaterial();
  54242. }
  54243. this._renderId = scene.getRenderId();
  54244. return true;
  54245. };
  54246. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  54247. var scene = this.getScene();
  54248. if (!this._effect) {
  54249. return;
  54250. }
  54251. if (this._options.uniforms.indexOf("world") !== -1) {
  54252. this._effect.setMatrix("world", world);
  54253. }
  54254. if (this._options.uniforms.indexOf("worldView") !== -1) {
  54255. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  54256. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  54257. }
  54258. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  54259. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  54260. }
  54261. };
  54262. ShaderMaterial.prototype.bind = function (world, mesh) {
  54263. // Std values
  54264. this.bindOnlyWorldMatrix(world);
  54265. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  54266. if (this._options.uniforms.indexOf("view") !== -1) {
  54267. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  54268. }
  54269. if (this._options.uniforms.indexOf("projection") !== -1) {
  54270. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  54271. }
  54272. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  54273. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  54274. }
  54275. // Bones
  54276. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  54277. var name;
  54278. // Texture
  54279. for (name in this._textures) {
  54280. this._effect.setTexture(name, this._textures[name]);
  54281. }
  54282. // Texture arrays
  54283. for (name in this._textureArrays) {
  54284. this._effect.setTextureArray(name, this._textureArrays[name]);
  54285. }
  54286. // Int
  54287. for (name in this._ints) {
  54288. this._effect.setInt(name, this._ints[name]);
  54289. }
  54290. // Float
  54291. for (name in this._floats) {
  54292. this._effect.setFloat(name, this._floats[name]);
  54293. }
  54294. // Floats
  54295. for (name in this._floatsArrays) {
  54296. this._effect.setArray(name, this._floatsArrays[name]);
  54297. }
  54298. // Color3
  54299. for (name in this._colors3) {
  54300. this._effect.setColor3(name, this._colors3[name]);
  54301. }
  54302. for (name in this._colors3Arrays) {
  54303. this._effect.setArray3(name, this._colors3Arrays[name]);
  54304. }
  54305. // Color4
  54306. for (name in this._colors4) {
  54307. var color = this._colors4[name];
  54308. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  54309. }
  54310. // Vector2
  54311. for (name in this._vectors2) {
  54312. this._effect.setVector2(name, this._vectors2[name]);
  54313. }
  54314. // Vector3
  54315. for (name in this._vectors3) {
  54316. this._effect.setVector3(name, this._vectors3[name]);
  54317. }
  54318. // Vector4
  54319. for (name in this._vectors4) {
  54320. this._effect.setVector4(name, this._vectors4[name]);
  54321. }
  54322. // Matrix
  54323. for (name in this._matrices) {
  54324. this._effect.setMatrix(name, this._matrices[name]);
  54325. }
  54326. // Matrix 3x3
  54327. for (name in this._matrices3x3) {
  54328. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  54329. }
  54330. // Matrix 2x2
  54331. for (name in this._matrices2x2) {
  54332. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  54333. }
  54334. // Vector2Array
  54335. for (name in this._vectors2Arrays) {
  54336. this._effect.setArray2(name, this._vectors2Arrays[name]);
  54337. }
  54338. // Vector3Array
  54339. for (name in this._vectors3Arrays) {
  54340. this._effect.setArray3(name, this._vectors3Arrays[name]);
  54341. }
  54342. }
  54343. this._afterBind(mesh);
  54344. };
  54345. ShaderMaterial.prototype.getActiveTextures = function () {
  54346. var activeTextures = _super.prototype.getActiveTextures.call(this);
  54347. for (var name in this._textures) {
  54348. activeTextures.push(this._textures[name]);
  54349. }
  54350. for (var name in this._textureArrays) {
  54351. var array = this._textureArrays[name];
  54352. for (var index = 0; index < array.length; index++) {
  54353. activeTextures.push(array[index]);
  54354. }
  54355. }
  54356. return activeTextures;
  54357. };
  54358. ShaderMaterial.prototype.hasTexture = function (texture) {
  54359. if (_super.prototype.hasTexture.call(this, texture)) {
  54360. return true;
  54361. }
  54362. for (var name in this._textures) {
  54363. if (this._textures[name] === texture) {
  54364. return true;
  54365. }
  54366. }
  54367. for (var name in this._textureArrays) {
  54368. var array = this._textureArrays[name];
  54369. for (var index = 0; index < array.length; index++) {
  54370. if (array[index] === texture) {
  54371. return true;
  54372. }
  54373. }
  54374. }
  54375. return false;
  54376. };
  54377. ShaderMaterial.prototype.clone = function (name) {
  54378. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  54379. return newShaderMaterial;
  54380. };
  54381. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  54382. if (forceDisposeTextures) {
  54383. var name;
  54384. for (name in this._textures) {
  54385. this._textures[name].dispose();
  54386. }
  54387. for (name in this._textureArrays) {
  54388. var array = this._textureArrays[name];
  54389. for (var index = 0; index < array.length; index++) {
  54390. array[index].dispose();
  54391. }
  54392. }
  54393. }
  54394. this._textures = {};
  54395. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  54396. };
  54397. ShaderMaterial.prototype.serialize = function () {
  54398. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  54399. serializationObject.customType = "BABYLON.ShaderMaterial";
  54400. serializationObject.options = this._options;
  54401. serializationObject.shaderPath = this._shaderPath;
  54402. var name;
  54403. // Texture
  54404. serializationObject.textures = {};
  54405. for (name in this._textures) {
  54406. serializationObject.textures[name] = this._textures[name].serialize();
  54407. }
  54408. // Texture arrays
  54409. serializationObject.textureArrays = {};
  54410. for (name in this._textureArrays) {
  54411. serializationObject.textureArrays[name] = [];
  54412. var array = this._textureArrays[name];
  54413. for (var index = 0; index < array.length; index++) {
  54414. serializationObject.textureArrays[name].push(array[index].serialize());
  54415. }
  54416. }
  54417. // Float
  54418. serializationObject.floats = {};
  54419. for (name in this._floats) {
  54420. serializationObject.floats[name] = this._floats[name];
  54421. }
  54422. // Float s
  54423. serializationObject.FloatArrays = {};
  54424. for (name in this._floatsArrays) {
  54425. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  54426. }
  54427. // Color3
  54428. serializationObject.colors3 = {};
  54429. for (name in this._colors3) {
  54430. serializationObject.colors3[name] = this._colors3[name].asArray();
  54431. }
  54432. // Color3 array
  54433. serializationObject.colors3Arrays = {};
  54434. for (name in this._colors3Arrays) {
  54435. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  54436. }
  54437. // Color4
  54438. serializationObject.colors4 = {};
  54439. for (name in this._colors4) {
  54440. serializationObject.colors4[name] = this._colors4[name].asArray();
  54441. }
  54442. // Vector2
  54443. serializationObject.vectors2 = {};
  54444. for (name in this._vectors2) {
  54445. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  54446. }
  54447. // Vector3
  54448. serializationObject.vectors3 = {};
  54449. for (name in this._vectors3) {
  54450. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  54451. }
  54452. // Vector4
  54453. serializationObject.vectors4 = {};
  54454. for (name in this._vectors4) {
  54455. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  54456. }
  54457. // Matrix
  54458. serializationObject.matrices = {};
  54459. for (name in this._matrices) {
  54460. serializationObject.matrices[name] = this._matrices[name].asArray();
  54461. }
  54462. // Matrix 3x3
  54463. serializationObject.matrices3x3 = {};
  54464. for (name in this._matrices3x3) {
  54465. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  54466. }
  54467. // Matrix 2x2
  54468. serializationObject.matrices2x2 = {};
  54469. for (name in this._matrices2x2) {
  54470. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  54471. }
  54472. // Vector2Array
  54473. serializationObject.vectors2Arrays = {};
  54474. for (name in this._vectors2Arrays) {
  54475. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  54476. }
  54477. // Vector3Array
  54478. serializationObject.vectors3Arrays = {};
  54479. for (name in this._vectors3Arrays) {
  54480. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  54481. }
  54482. return serializationObject;
  54483. };
  54484. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  54485. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  54486. var name;
  54487. // Texture
  54488. for (name in source.textures) {
  54489. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  54490. }
  54491. // Texture arrays
  54492. for (name in source.textureArrays) {
  54493. var array = source.textureArrays[name];
  54494. var textureArray = new Array();
  54495. for (var index = 0; index < array.length; index++) {
  54496. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  54497. }
  54498. material.setTextureArray(name, textureArray);
  54499. }
  54500. // Float
  54501. for (name in source.floats) {
  54502. material.setFloat(name, source.floats[name]);
  54503. }
  54504. // Float s
  54505. for (name in source.floatsArrays) {
  54506. material.setFloats(name, source.floatsArrays[name]);
  54507. }
  54508. // Color3
  54509. for (name in source.colors3) {
  54510. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  54511. }
  54512. // Color3 arrays
  54513. for (name in source.colors3Arrays) {
  54514. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  54515. if (i % 3 === 0) {
  54516. arr.push([num]);
  54517. }
  54518. else {
  54519. arr[arr.length - 1].push(num);
  54520. }
  54521. return arr;
  54522. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  54523. material.setColor3Array(name, colors);
  54524. }
  54525. // Color4
  54526. for (name in source.colors4) {
  54527. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  54528. }
  54529. // Vector2
  54530. for (name in source.vectors2) {
  54531. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  54532. }
  54533. // Vector3
  54534. for (name in source.vectors3) {
  54535. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  54536. }
  54537. // Vector4
  54538. for (name in source.vectors4) {
  54539. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  54540. }
  54541. // Matrix
  54542. for (name in source.matrices) {
  54543. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  54544. }
  54545. // Matrix 3x3
  54546. for (name in source.matrices3x3) {
  54547. material.setMatrix3x3(name, source.matrices3x3[name]);
  54548. }
  54549. // Matrix 2x2
  54550. for (name in source.matrices2x2) {
  54551. material.setMatrix2x2(name, source.matrices2x2[name]);
  54552. }
  54553. // Vector2Array
  54554. for (name in source.vectors2Arrays) {
  54555. material.setArray2(name, source.vectors2Arrays[name]);
  54556. }
  54557. // Vector3Array
  54558. for (name in source.vectors3Arrays) {
  54559. material.setArray3(name, source.vectors3Arrays[name]);
  54560. }
  54561. return material;
  54562. };
  54563. return ShaderMaterial;
  54564. }(BABYLON.Material));
  54565. BABYLON.ShaderMaterial = ShaderMaterial;
  54566. })(BABYLON || (BABYLON = {}));
  54567. //# sourceMappingURL=babylon.shaderMaterial.js.map
  54568. var BABYLON;
  54569. (function (BABYLON) {
  54570. var GroundMesh = /** @class */ (function (_super) {
  54571. __extends(GroundMesh, _super);
  54572. function GroundMesh(name, scene) {
  54573. var _this = _super.call(this, name, scene) || this;
  54574. _this.generateOctree = false;
  54575. return _this;
  54576. }
  54577. GroundMesh.prototype.getClassName = function () {
  54578. return "GroundMesh";
  54579. };
  54580. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  54581. get: function () {
  54582. return Math.min(this._subdivisionsX, this._subdivisionsY);
  54583. },
  54584. enumerable: true,
  54585. configurable: true
  54586. });
  54587. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  54588. get: function () {
  54589. return this._subdivisionsX;
  54590. },
  54591. enumerable: true,
  54592. configurable: true
  54593. });
  54594. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  54595. get: function () {
  54596. return this._subdivisionsY;
  54597. },
  54598. enumerable: true,
  54599. configurable: true
  54600. });
  54601. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  54602. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  54603. this._subdivisionsX = chunksCount;
  54604. this._subdivisionsY = chunksCount;
  54605. this.subdivide(chunksCount);
  54606. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  54607. };
  54608. /**
  54609. * Returns a height (y) value in the Worl system :
  54610. * the ground altitude at the coordinates (x, z) expressed in the World system.
  54611. * Returns the ground y position if (x, z) are outside the ground surface.
  54612. */
  54613. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  54614. var world = this.getWorldMatrix();
  54615. var invMat = BABYLON.Tmp.Matrix[5];
  54616. world.invertToRef(invMat);
  54617. var tmpVect = BABYLON.Tmp.Vector3[8];
  54618. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  54619. x = tmpVect.x;
  54620. z = tmpVect.z;
  54621. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  54622. return this.position.y;
  54623. }
  54624. if (!this._heightQuads || this._heightQuads.length == 0) {
  54625. this._initHeightQuads();
  54626. this._computeHeightQuads();
  54627. }
  54628. var facet = this._getFacetAt(x, z);
  54629. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  54630. // return y in the World system
  54631. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  54632. return tmpVect.y;
  54633. };
  54634. /**
  54635. * Returns a normalized vector (Vector3) orthogonal to the ground
  54636. * at the ground coordinates (x, z) expressed in the World system.
  54637. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  54638. */
  54639. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  54640. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  54641. this.getNormalAtCoordinatesToRef(x, z, normal);
  54642. return normal;
  54643. };
  54644. /**
  54645. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  54646. * at the ground coordinates (x, z) expressed in the World system.
  54647. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  54648. * Returns the GroundMesh.
  54649. */
  54650. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  54651. var world = this.getWorldMatrix();
  54652. var tmpMat = BABYLON.Tmp.Matrix[5];
  54653. world.invertToRef(tmpMat);
  54654. var tmpVect = BABYLON.Tmp.Vector3[8];
  54655. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  54656. x = tmpVect.x;
  54657. z = tmpVect.z;
  54658. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  54659. return this;
  54660. }
  54661. if (!this._heightQuads || this._heightQuads.length == 0) {
  54662. this._initHeightQuads();
  54663. this._computeHeightQuads();
  54664. }
  54665. var facet = this._getFacetAt(x, z);
  54666. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  54667. return this;
  54668. };
  54669. /**
  54670. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  54671. * if the ground has been updated.
  54672. * This can be used in the render loop.
  54673. * Returns the GroundMesh.
  54674. */
  54675. GroundMesh.prototype.updateCoordinateHeights = function () {
  54676. if (!this._heightQuads || this._heightQuads.length == 0) {
  54677. this._initHeightQuads();
  54678. }
  54679. this._computeHeightQuads();
  54680. return this;
  54681. };
  54682. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  54683. GroundMesh.prototype._getFacetAt = function (x, z) {
  54684. // retrieve col and row from x, z coordinates in the ground local system
  54685. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  54686. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  54687. var quad = this._heightQuads[row * this._subdivisionsX + col];
  54688. var facet;
  54689. if (z < quad.slope.x * x + quad.slope.y) {
  54690. facet = quad.facet1;
  54691. }
  54692. else {
  54693. facet = quad.facet2;
  54694. }
  54695. return facet;
  54696. };
  54697. // Creates and populates the heightMap array with "facet" elements :
  54698. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  54699. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  54700. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  54701. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  54702. // Returns the GroundMesh.
  54703. GroundMesh.prototype._initHeightQuads = function () {
  54704. var subdivisionsX = this._subdivisionsX;
  54705. var subdivisionsY = this._subdivisionsY;
  54706. this._heightQuads = new Array();
  54707. for (var row = 0; row < subdivisionsY; row++) {
  54708. for (var col = 0; col < subdivisionsX; col++) {
  54709. 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) };
  54710. this._heightQuads[row * subdivisionsX + col] = quad;
  54711. }
  54712. }
  54713. return this;
  54714. };
  54715. // Compute each quad element values and update the the heightMap array :
  54716. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  54717. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  54718. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  54719. // Returns the GroundMesh.
  54720. GroundMesh.prototype._computeHeightQuads = function () {
  54721. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54722. if (!positions) {
  54723. return this;
  54724. }
  54725. var v1 = BABYLON.Tmp.Vector3[3];
  54726. var v2 = BABYLON.Tmp.Vector3[2];
  54727. var v3 = BABYLON.Tmp.Vector3[1];
  54728. var v4 = BABYLON.Tmp.Vector3[0];
  54729. var v1v2 = BABYLON.Tmp.Vector3[4];
  54730. var v1v3 = BABYLON.Tmp.Vector3[5];
  54731. var v1v4 = BABYLON.Tmp.Vector3[6];
  54732. var norm1 = BABYLON.Tmp.Vector3[7];
  54733. var norm2 = BABYLON.Tmp.Vector3[8];
  54734. var i = 0;
  54735. var j = 0;
  54736. var k = 0;
  54737. var cd = 0; // 2D slope coefficient : z = cd * x + h
  54738. var h = 0;
  54739. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  54740. var d2 = 0;
  54741. var subdivisionsX = this._subdivisionsX;
  54742. var subdivisionsY = this._subdivisionsY;
  54743. for (var row = 0; row < subdivisionsY; row++) {
  54744. for (var col = 0; col < subdivisionsX; col++) {
  54745. i = col * 3;
  54746. j = row * (subdivisionsX + 1) * 3;
  54747. k = (row + 1) * (subdivisionsX + 1) * 3;
  54748. v1.x = positions[j + i];
  54749. v1.y = positions[j + i + 1];
  54750. v1.z = positions[j + i + 2];
  54751. v2.x = positions[j + i + 3];
  54752. v2.y = positions[j + i + 4];
  54753. v2.z = positions[j + i + 5];
  54754. v3.x = positions[k + i];
  54755. v3.y = positions[k + i + 1];
  54756. v3.z = positions[k + i + 2];
  54757. v4.x = positions[k + i + 3];
  54758. v4.y = positions[k + i + 4];
  54759. v4.z = positions[k + i + 5];
  54760. // 2D slope V1V4
  54761. cd = (v4.z - v1.z) / (v4.x - v1.x);
  54762. h = v1.z - cd * v1.x; // v1 belongs to the slope
  54763. // facet equations :
  54764. // we compute each facet normal vector
  54765. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  54766. // we compute the value d by applying the equation to v1 which belongs to the plane
  54767. // then we store the facet equation in a Vector4
  54768. v2.subtractToRef(v1, v1v2);
  54769. v3.subtractToRef(v1, v1v3);
  54770. v4.subtractToRef(v1, v1v4);
  54771. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  54772. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  54773. norm1.normalize();
  54774. norm2.normalize();
  54775. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  54776. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  54777. var quad = this._heightQuads[row * subdivisionsX + col];
  54778. quad.slope.copyFromFloats(cd, h);
  54779. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  54780. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  54781. }
  54782. }
  54783. return this;
  54784. };
  54785. GroundMesh.prototype.serialize = function (serializationObject) {
  54786. _super.prototype.serialize.call(this, serializationObject);
  54787. serializationObject.subdivisionsX = this._subdivisionsX;
  54788. serializationObject.subdivisionsY = this._subdivisionsY;
  54789. serializationObject.minX = this._minX;
  54790. serializationObject.maxX = this._maxX;
  54791. serializationObject.minZ = this._minZ;
  54792. serializationObject.maxZ = this._maxZ;
  54793. serializationObject.width = this._width;
  54794. serializationObject.height = this._height;
  54795. };
  54796. GroundMesh.Parse = function (parsedMesh, scene) {
  54797. var result = new GroundMesh(parsedMesh.name, scene);
  54798. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  54799. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  54800. result._minX = parsedMesh.minX;
  54801. result._maxX = parsedMesh.maxX;
  54802. result._minZ = parsedMesh.minZ;
  54803. result._maxZ = parsedMesh.maxZ;
  54804. result._width = parsedMesh.width;
  54805. result._height = parsedMesh.height;
  54806. return result;
  54807. };
  54808. return GroundMesh;
  54809. }(BABYLON.Mesh));
  54810. BABYLON.GroundMesh = GroundMesh;
  54811. })(BABYLON || (BABYLON = {}));
  54812. //# sourceMappingURL=babylon.groundMesh.js.map
  54813. var BABYLON;
  54814. (function (BABYLON) {
  54815. /**
  54816. * Creates an instance based on a source mesh.
  54817. */
  54818. var InstancedMesh = /** @class */ (function (_super) {
  54819. __extends(InstancedMesh, _super);
  54820. function InstancedMesh(name, source) {
  54821. var _this = _super.call(this, name, source.getScene()) || this;
  54822. source.instances.push(_this);
  54823. _this._sourceMesh = source;
  54824. _this.position.copyFrom(source.position);
  54825. _this.rotation.copyFrom(source.rotation);
  54826. _this.scaling.copyFrom(source.scaling);
  54827. if (source.rotationQuaternion) {
  54828. _this.rotationQuaternion = source.rotationQuaternion.clone();
  54829. }
  54830. _this.infiniteDistance = source.infiniteDistance;
  54831. _this.setPivotMatrix(source.getPivotMatrix());
  54832. _this.refreshBoundingInfo();
  54833. _this._syncSubMeshes();
  54834. return _this;
  54835. }
  54836. /**
  54837. * Returns the string "InstancedMesh".
  54838. */
  54839. InstancedMesh.prototype.getClassName = function () {
  54840. return "InstancedMesh";
  54841. };
  54842. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  54843. // Methods
  54844. get: function () {
  54845. return this._sourceMesh.receiveShadows;
  54846. },
  54847. enumerable: true,
  54848. configurable: true
  54849. });
  54850. Object.defineProperty(InstancedMesh.prototype, "material", {
  54851. get: function () {
  54852. return this._sourceMesh.material;
  54853. },
  54854. enumerable: true,
  54855. configurable: true
  54856. });
  54857. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  54858. get: function () {
  54859. return this._sourceMesh.visibility;
  54860. },
  54861. enumerable: true,
  54862. configurable: true
  54863. });
  54864. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  54865. get: function () {
  54866. return this._sourceMesh.skeleton;
  54867. },
  54868. enumerable: true,
  54869. configurable: true
  54870. });
  54871. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  54872. get: function () {
  54873. return this._sourceMesh.renderingGroupId;
  54874. },
  54875. enumerable: true,
  54876. configurable: true
  54877. });
  54878. /**
  54879. * Returns the total number of vertices (integer).
  54880. */
  54881. InstancedMesh.prototype.getTotalVertices = function () {
  54882. return this._sourceMesh.getTotalVertices();
  54883. };
  54884. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  54885. get: function () {
  54886. return this._sourceMesh;
  54887. },
  54888. enumerable: true,
  54889. configurable: true
  54890. });
  54891. /**
  54892. * Is this node ready to be used/rendered
  54893. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  54894. * @return {boolean} is it ready
  54895. */
  54896. InstancedMesh.prototype.isReady = function (completeCheck) {
  54897. if (completeCheck === void 0) { completeCheck = false; }
  54898. return this._sourceMesh.isReady(completeCheck, true);
  54899. };
  54900. /**
  54901. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  54902. */
  54903. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  54904. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  54905. };
  54906. /**
  54907. * Sets the vertex data of the mesh geometry for the requested `kind`.
  54908. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  54909. * The `data` are either a numeric array either a Float32Array.
  54910. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  54911. * 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).
  54912. * Note that a new underlying VertexBuffer object is created each call.
  54913. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  54914. *
  54915. * Possible `kind` values :
  54916. * - BABYLON.VertexBuffer.PositionKind
  54917. * - BABYLON.VertexBuffer.UVKind
  54918. * - BABYLON.VertexBuffer.UV2Kind
  54919. * - BABYLON.VertexBuffer.UV3Kind
  54920. * - BABYLON.VertexBuffer.UV4Kind
  54921. * - BABYLON.VertexBuffer.UV5Kind
  54922. * - BABYLON.VertexBuffer.UV6Kind
  54923. * - BABYLON.VertexBuffer.ColorKind
  54924. * - BABYLON.VertexBuffer.MatricesIndicesKind
  54925. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  54926. * - BABYLON.VertexBuffer.MatricesWeightsKind
  54927. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  54928. *
  54929. * Returns the Mesh.
  54930. */
  54931. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  54932. if (this.sourceMesh) {
  54933. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  54934. }
  54935. return this.sourceMesh;
  54936. };
  54937. /**
  54938. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  54939. * If the mesh has no geometry, it is simply returned as it is.
  54940. * The `data` are either a numeric array either a Float32Array.
  54941. * No new underlying VertexBuffer object is created.
  54942. * 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.
  54943. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  54944. *
  54945. * Possible `kind` values :
  54946. * - BABYLON.VertexBuffer.PositionKind
  54947. * - BABYLON.VertexBuffer.UVKind
  54948. * - BABYLON.VertexBuffer.UV2Kind
  54949. * - BABYLON.VertexBuffer.UV3Kind
  54950. * - BABYLON.VertexBuffer.UV4Kind
  54951. * - BABYLON.VertexBuffer.UV5Kind
  54952. * - BABYLON.VertexBuffer.UV6Kind
  54953. * - BABYLON.VertexBuffer.ColorKind
  54954. * - BABYLON.VertexBuffer.MatricesIndicesKind
  54955. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  54956. * - BABYLON.VertexBuffer.MatricesWeightsKind
  54957. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  54958. *
  54959. * Returns the Mesh.
  54960. */
  54961. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  54962. if (this.sourceMesh) {
  54963. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  54964. }
  54965. return this.sourceMesh;
  54966. };
  54967. /**
  54968. * Sets the mesh indices.
  54969. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  54970. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  54971. * This method creates a new index buffer each call.
  54972. * Returns the Mesh.
  54973. */
  54974. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  54975. if (totalVertices === void 0) { totalVertices = null; }
  54976. if (this.sourceMesh) {
  54977. this.sourceMesh.setIndices(indices, totalVertices);
  54978. }
  54979. return this.sourceMesh;
  54980. };
  54981. /**
  54982. * Boolean : True if the mesh owns the requested kind of data.
  54983. */
  54984. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  54985. return this._sourceMesh.isVerticesDataPresent(kind);
  54986. };
  54987. /**
  54988. * Returns an array of indices (IndicesArray).
  54989. */
  54990. InstancedMesh.prototype.getIndices = function () {
  54991. return this._sourceMesh.getIndices();
  54992. };
  54993. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  54994. get: function () {
  54995. return this._sourceMesh._positions;
  54996. },
  54997. enumerable: true,
  54998. configurable: true
  54999. });
  55000. /**
  55001. * Sets a new updated BoundingInfo to the mesh.
  55002. * Returns the mesh.
  55003. */
  55004. InstancedMesh.prototype.refreshBoundingInfo = function () {
  55005. var meshBB = this._sourceMesh.getBoundingInfo();
  55006. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  55007. this._updateBoundingInfo();
  55008. return this;
  55009. };
  55010. InstancedMesh.prototype._preActivate = function () {
  55011. if (this._currentLOD) {
  55012. this._currentLOD._preActivate();
  55013. }
  55014. return this;
  55015. };
  55016. InstancedMesh.prototype._activate = function (renderId) {
  55017. if (this._currentLOD) {
  55018. this._currentLOD._registerInstanceForRenderId(this, renderId);
  55019. }
  55020. return this;
  55021. };
  55022. /**
  55023. * Returns the current associated LOD AbstractMesh.
  55024. */
  55025. InstancedMesh.prototype.getLOD = function (camera) {
  55026. if (!camera) {
  55027. return this;
  55028. }
  55029. var boundingInfo = this.getBoundingInfo();
  55030. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  55031. if (this._currentLOD === this.sourceMesh) {
  55032. return this;
  55033. }
  55034. return this._currentLOD;
  55035. };
  55036. InstancedMesh.prototype._syncSubMeshes = function () {
  55037. this.releaseSubMeshes();
  55038. if (this._sourceMesh.subMeshes) {
  55039. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  55040. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  55041. }
  55042. }
  55043. return this;
  55044. };
  55045. InstancedMesh.prototype._generatePointsArray = function () {
  55046. return this._sourceMesh._generatePointsArray();
  55047. };
  55048. /**
  55049. * Creates a new InstancedMesh from the current mesh.
  55050. * - name (string) : the cloned mesh name
  55051. * - newParent (optional Node) : the optional Node to parent the clone to.
  55052. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  55053. *
  55054. * Returns the clone.
  55055. */
  55056. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  55057. var result = this._sourceMesh.createInstance(name);
  55058. // Deep copy
  55059. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  55060. // Bounding info
  55061. this.refreshBoundingInfo();
  55062. // Parent
  55063. if (newParent) {
  55064. result.parent = newParent;
  55065. }
  55066. if (!doNotCloneChildren) {
  55067. // Children
  55068. for (var index = 0; index < this.getScene().meshes.length; index++) {
  55069. var mesh = this.getScene().meshes[index];
  55070. if (mesh.parent === this) {
  55071. mesh.clone(mesh.name, result);
  55072. }
  55073. }
  55074. }
  55075. result.computeWorldMatrix(true);
  55076. return result;
  55077. };
  55078. /**
  55079. * Disposes the InstancedMesh.
  55080. * Returns nothing.
  55081. */
  55082. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  55083. // Remove from mesh
  55084. var index = this._sourceMesh.instances.indexOf(this);
  55085. this._sourceMesh.instances.splice(index, 1);
  55086. _super.prototype.dispose.call(this, doNotRecurse);
  55087. };
  55088. return InstancedMesh;
  55089. }(BABYLON.AbstractMesh));
  55090. BABYLON.InstancedMesh = InstancedMesh;
  55091. })(BABYLON || (BABYLON = {}));
  55092. //# sourceMappingURL=babylon.instancedMesh.js.map
  55093. var BABYLON;
  55094. (function (BABYLON) {
  55095. var LinesMesh = /** @class */ (function (_super) {
  55096. __extends(LinesMesh, _super);
  55097. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  55098. if (scene === void 0) { scene = null; }
  55099. if (parent === void 0) { parent = null; }
  55100. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  55101. _this.useVertexColor = useVertexColor;
  55102. _this.useVertexAlpha = useVertexAlpha;
  55103. _this.color = new BABYLON.Color3(1, 1, 1);
  55104. _this.alpha = 1;
  55105. if (source) {
  55106. _this.color = source.color.clone();
  55107. _this.alpha = source.alpha;
  55108. _this.useVertexColor = source.useVertexColor;
  55109. _this.useVertexAlpha = source.useVertexAlpha;
  55110. }
  55111. _this._intersectionThreshold = 0.1;
  55112. var defines = [];
  55113. var options = {
  55114. attributes: [BABYLON.VertexBuffer.PositionKind],
  55115. uniforms: ["world", "viewProjection"],
  55116. needAlphaBlending: true,
  55117. defines: defines
  55118. };
  55119. if (useVertexAlpha === false) {
  55120. options.needAlphaBlending = false;
  55121. }
  55122. if (!useVertexColor) {
  55123. options.uniforms.push("color");
  55124. }
  55125. else {
  55126. options.defines.push("#define VERTEXCOLOR");
  55127. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  55128. }
  55129. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  55130. return _this;
  55131. }
  55132. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  55133. /**
  55134. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  55135. * This margin is expressed in world space coordinates, so its value may vary.
  55136. * Default value is 0.1
  55137. * @returns the intersection Threshold value.
  55138. */
  55139. get: function () {
  55140. return this._intersectionThreshold;
  55141. },
  55142. /**
  55143. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  55144. * This margin is expressed in world space coordinates, so its value may vary.
  55145. * @param value the new threshold to apply
  55146. */
  55147. set: function (value) {
  55148. if (this._intersectionThreshold === value) {
  55149. return;
  55150. }
  55151. this._intersectionThreshold = value;
  55152. if (this.geometry) {
  55153. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  55154. }
  55155. },
  55156. enumerable: true,
  55157. configurable: true
  55158. });
  55159. /**
  55160. * Returns the string "LineMesh"
  55161. */
  55162. LinesMesh.prototype.getClassName = function () {
  55163. return "LinesMesh";
  55164. };
  55165. Object.defineProperty(LinesMesh.prototype, "material", {
  55166. get: function () {
  55167. return this._colorShader;
  55168. },
  55169. set: function (value) {
  55170. // Do nothing
  55171. },
  55172. enumerable: true,
  55173. configurable: true
  55174. });
  55175. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  55176. get: function () {
  55177. return false;
  55178. },
  55179. enumerable: true,
  55180. configurable: true
  55181. });
  55182. LinesMesh.prototype.createInstance = function (name) {
  55183. throw new Error("LinesMeshes do not support createInstance.");
  55184. };
  55185. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  55186. if (!this._geometry) {
  55187. return this;
  55188. }
  55189. // VBOs
  55190. this._geometry._bind(this._colorShader.getEffect());
  55191. // Color
  55192. if (!this.useVertexColor) {
  55193. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  55194. }
  55195. return this;
  55196. };
  55197. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  55198. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  55199. return this;
  55200. }
  55201. var engine = this.getScene().getEngine();
  55202. // Draw order
  55203. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  55204. return this;
  55205. };
  55206. LinesMesh.prototype.dispose = function (doNotRecurse) {
  55207. this._colorShader.dispose();
  55208. _super.prototype.dispose.call(this, doNotRecurse);
  55209. };
  55210. /**
  55211. * Returns a new LineMesh object cloned from the current one.
  55212. */
  55213. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  55214. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  55215. };
  55216. return LinesMesh;
  55217. }(BABYLON.Mesh));
  55218. BABYLON.LinesMesh = LinesMesh;
  55219. })(BABYLON || (BABYLON = {}));
  55220. //# sourceMappingURL=babylon.linesMesh.js.map
  55221. var BABYLON;
  55222. (function (BABYLON) {
  55223. var MeshBuilder = /** @class */ (function () {
  55224. function MeshBuilder() {
  55225. }
  55226. MeshBuilder.updateSideOrientation = function (orientation) {
  55227. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  55228. return BABYLON.Mesh.DOUBLESIDE;
  55229. }
  55230. if (orientation === undefined || orientation === null) {
  55231. return BABYLON.Mesh.FRONTSIDE;
  55232. }
  55233. return orientation;
  55234. };
  55235. /**
  55236. * Creates a box mesh.
  55237. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  55238. * The parameter `size` sets the size (float) of each box side (default 1).
  55239. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  55240. * 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).
  55241. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  55242. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55243. * 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).
  55244. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55245. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55246. */
  55247. MeshBuilder.CreateBox = function (name, options, scene) {
  55248. if (scene === void 0) { scene = null; }
  55249. var box = new BABYLON.Mesh(name, scene);
  55250. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55251. box._originalBuilderSideOrientation = options.sideOrientation;
  55252. var vertexData = BABYLON.VertexData.CreateBox(options);
  55253. vertexData.applyToMesh(box, options.updatable);
  55254. return box;
  55255. };
  55256. /**
  55257. * Creates a sphere mesh.
  55258. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  55259. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  55260. * 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`).
  55261. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  55262. * 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
  55263. * 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).
  55264. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55265. * 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).
  55266. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55267. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55268. */
  55269. MeshBuilder.CreateSphere = function (name, options, scene) {
  55270. var sphere = new BABYLON.Mesh(name, scene);
  55271. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55272. sphere._originalBuilderSideOrientation = options.sideOrientation;
  55273. var vertexData = BABYLON.VertexData.CreateSphere(options);
  55274. vertexData.applyToMesh(sphere, options.updatable);
  55275. return sphere;
  55276. };
  55277. /**
  55278. * Creates a plane polygonal mesh. By default, this is a disc.
  55279. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  55280. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  55281. * 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.
  55282. * 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
  55283. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55284. * 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).
  55285. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55286. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55287. */
  55288. MeshBuilder.CreateDisc = function (name, options, scene) {
  55289. if (scene === void 0) { scene = null; }
  55290. var disc = new BABYLON.Mesh(name, scene);
  55291. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55292. disc._originalBuilderSideOrientation = options.sideOrientation;
  55293. var vertexData = BABYLON.VertexData.CreateDisc(options);
  55294. vertexData.applyToMesh(disc, options.updatable);
  55295. return disc;
  55296. };
  55297. /**
  55298. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  55299. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  55300. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  55301. * 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`).
  55302. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  55303. * 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.
  55304. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55305. * 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).
  55306. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55307. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55308. */
  55309. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  55310. var sphere = new BABYLON.Mesh(name, scene);
  55311. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55312. sphere._originalBuilderSideOrientation = options.sideOrientation;
  55313. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  55314. vertexData.applyToMesh(sphere, options.updatable);
  55315. return sphere;
  55316. };
  55317. ;
  55318. /**
  55319. * Creates a ribbon mesh.
  55320. * 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.
  55321. *
  55322. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  55323. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  55324. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  55325. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  55326. * 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.
  55327. * 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.
  55328. * 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
  55329. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55330. * 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).
  55331. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55332. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  55333. * 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.
  55334. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  55335. * 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
  55336. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  55337. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  55338. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55339. */
  55340. MeshBuilder.CreateRibbon = function (name, options, scene) {
  55341. if (scene === void 0) { scene = null; }
  55342. var pathArray = options.pathArray;
  55343. var closeArray = options.closeArray;
  55344. var closePath = options.closePath;
  55345. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55346. var instance = options.instance;
  55347. var updatable = options.updatable;
  55348. if (instance) {
  55349. // positionFunction : ribbon case
  55350. // only pathArray and sideOrientation parameters are taken into account for positions update
  55351. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  55352. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  55353. var positionFunction = function (positions) {
  55354. var minlg = pathArray[0].length;
  55355. var i = 0;
  55356. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  55357. for (var si = 1; si <= ns; si++) {
  55358. for (var p = 0; p < pathArray.length; p++) {
  55359. var path = pathArray[p];
  55360. var l = path.length;
  55361. minlg = (minlg < l) ? minlg : l;
  55362. var j = 0;
  55363. while (j < minlg) {
  55364. positions[i] = path[j].x;
  55365. positions[i + 1] = path[j].y;
  55366. positions[i + 2] = path[j].z;
  55367. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  55368. BABYLON.Tmp.Vector3[0].x = path[j].x;
  55369. }
  55370. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  55371. BABYLON.Tmp.Vector3[1].x = path[j].x;
  55372. }
  55373. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  55374. BABYLON.Tmp.Vector3[0].y = path[j].y;
  55375. }
  55376. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  55377. BABYLON.Tmp.Vector3[1].y = path[j].y;
  55378. }
  55379. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  55380. BABYLON.Tmp.Vector3[0].z = path[j].z;
  55381. }
  55382. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  55383. BABYLON.Tmp.Vector3[1].z = path[j].z;
  55384. }
  55385. j++;
  55386. i += 3;
  55387. }
  55388. if (instance._closePath) {
  55389. positions[i] = path[0].x;
  55390. positions[i + 1] = path[0].y;
  55391. positions[i + 2] = path[0].z;
  55392. i += 3;
  55393. }
  55394. }
  55395. }
  55396. };
  55397. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  55398. positionFunction(positions);
  55399. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  55400. instance._boundingInfo.update(instance._worldMatrix);
  55401. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  55402. if (options.colors) {
  55403. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  55404. for (var c = 0; c < options.colors.length; c++) {
  55405. colors[c * 4] = options.colors[c].r;
  55406. colors[c * 4 + 1] = options.colors[c].g;
  55407. colors[c * 4 + 2] = options.colors[c].b;
  55408. colors[c * 4 + 3] = options.colors[c].a;
  55409. }
  55410. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  55411. }
  55412. if (options.uvs) {
  55413. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  55414. for (var i = 0; i < options.uvs.length; i++) {
  55415. uvs[i * 2] = options.uvs[i].x;
  55416. uvs[i * 2 + 1] = options.uvs[i].y;
  55417. }
  55418. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  55419. }
  55420. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  55421. var indices = instance.getIndices();
  55422. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  55423. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  55424. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  55425. if (instance._closePath) {
  55426. var indexFirst = 0;
  55427. var indexLast = 0;
  55428. for (var p = 0; p < pathArray.length; p++) {
  55429. indexFirst = instance._idx[p] * 3;
  55430. if (p + 1 < pathArray.length) {
  55431. indexLast = (instance._idx[p + 1] - 1) * 3;
  55432. }
  55433. else {
  55434. indexLast = normals.length - 3;
  55435. }
  55436. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  55437. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  55438. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  55439. normals[indexLast] = normals[indexFirst];
  55440. normals[indexLast + 1] = normals[indexFirst + 1];
  55441. normals[indexLast + 2] = normals[indexFirst + 2];
  55442. }
  55443. }
  55444. if (!(instance.areNormalsFrozen)) {
  55445. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  55446. }
  55447. }
  55448. return instance;
  55449. }
  55450. else {
  55451. var ribbon = new BABYLON.Mesh(name, scene);
  55452. ribbon._originalBuilderSideOrientation = sideOrientation;
  55453. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  55454. if (closePath) {
  55455. ribbon._idx = vertexData._idx;
  55456. }
  55457. ribbon._closePath = closePath;
  55458. ribbon._closeArray = closeArray;
  55459. vertexData.applyToMesh(ribbon, updatable);
  55460. return ribbon;
  55461. }
  55462. };
  55463. /**
  55464. * Creates a cylinder or a cone mesh.
  55465. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  55466. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  55467. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  55468. * 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.
  55469. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  55470. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  55471. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  55472. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  55473. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  55474. * 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).
  55475. * 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
  55476. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  55477. * 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
  55478. * 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.
  55479. * If `enclose` is false, a ring surface is one element.
  55480. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  55481. * 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
  55482. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55483. * 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).
  55484. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55485. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55486. */
  55487. MeshBuilder.CreateCylinder = function (name, options, scene) {
  55488. var cylinder = new BABYLON.Mesh(name, scene);
  55489. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55490. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  55491. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  55492. vertexData.applyToMesh(cylinder, options.updatable);
  55493. return cylinder;
  55494. };
  55495. /**
  55496. * Creates a torus mesh.
  55497. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  55498. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  55499. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  55500. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  55501. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55502. * 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).
  55503. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55504. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55505. */
  55506. MeshBuilder.CreateTorus = function (name, options, scene) {
  55507. var torus = new BABYLON.Mesh(name, scene);
  55508. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55509. torus._originalBuilderSideOrientation = options.sideOrientation;
  55510. var vertexData = BABYLON.VertexData.CreateTorus(options);
  55511. vertexData.applyToMesh(torus, options.updatable);
  55512. return torus;
  55513. };
  55514. /**
  55515. * Creates a torus knot mesh.
  55516. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  55517. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  55518. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  55519. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  55520. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  55521. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55522. * 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).
  55523. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55524. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55525. */
  55526. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  55527. var torusKnot = new BABYLON.Mesh(name, scene);
  55528. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55529. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  55530. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  55531. vertexData.applyToMesh(torusKnot, options.updatable);
  55532. return torusKnot;
  55533. };
  55534. /**
  55535. * Creates a line system mesh.
  55536. * A line system is a pool of many lines gathered in a single mesh.
  55537. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  55538. * 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.
  55539. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  55540. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  55541. * 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
  55542. * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point.
  55543. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need the alpha blending (faster).
  55544. * 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
  55545. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  55546. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55547. */
  55548. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  55549. var instance = options.instance;
  55550. var lines = options.lines;
  55551. var colors = options.colors;
  55552. if (instance) {
  55553. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  55554. var vertexColor;
  55555. var lineColors;
  55556. if (colors) {
  55557. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  55558. }
  55559. var i = 0;
  55560. var c = 0;
  55561. for (var l = 0; l < lines.length; l++) {
  55562. var points = lines[l];
  55563. for (var p = 0; p < points.length; p++) {
  55564. positions[i] = points[p].x;
  55565. positions[i + 1] = points[p].y;
  55566. positions[i + 2] = points[p].z;
  55567. if (colors && vertexColor) {
  55568. lineColors = colors[l];
  55569. vertexColor[c] = lineColors[p].r;
  55570. vertexColor[c + 1] = lineColors[p].g;
  55571. vertexColor[c + 2] = lineColors[p].b;
  55572. vertexColor[c + 3] = lineColors[p].a;
  55573. c += 4;
  55574. }
  55575. i += 3;
  55576. }
  55577. }
  55578. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  55579. if (colors && vertexColor) {
  55580. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  55581. }
  55582. return instance;
  55583. }
  55584. // line system creation
  55585. var useVertexColor = (colors) ? true : false;
  55586. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  55587. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  55588. vertexData.applyToMesh(lineSystem, options.updatable);
  55589. return lineSystem;
  55590. };
  55591. /**
  55592. * Creates a line mesh.
  55593. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  55594. * 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.
  55595. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  55596. * The parameter `points` is an array successive Vector3.
  55597. * 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
  55598. * The optional parameter `colors` is an array of successive Color4, one per line point.
  55599. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need alpha blending (faster).
  55600. * When updating an instance, remember that only point positions can change, not the number of points.
  55601. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55602. */
  55603. MeshBuilder.CreateLines = function (name, options, scene) {
  55604. if (scene === void 0) { scene = null; }
  55605. var colors = (options.colors) ? [options.colors] : null;
  55606. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  55607. return lines;
  55608. };
  55609. /**
  55610. * Creates a dashed line mesh.
  55611. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  55612. * 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.
  55613. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  55614. * The parameter `points` is an array successive Vector3.
  55615. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  55616. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  55617. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  55618. * 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
  55619. * When updating an instance, remember that only point positions can change, not the number of points.
  55620. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55621. */
  55622. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  55623. if (scene === void 0) { scene = null; }
  55624. var points = options.points;
  55625. var instance = options.instance;
  55626. var gapSize = options.gapSize || 1;
  55627. var dashSize = options.dashSize || 3;
  55628. if (instance) {
  55629. var positionFunction = function (positions) {
  55630. var curvect = BABYLON.Vector3.Zero();
  55631. var nbSeg = positions.length / 6;
  55632. var lg = 0;
  55633. var nb = 0;
  55634. var shft = 0;
  55635. var dashshft = 0;
  55636. var curshft = 0;
  55637. var p = 0;
  55638. var i = 0;
  55639. var j = 0;
  55640. for (i = 0; i < points.length - 1; i++) {
  55641. points[i + 1].subtractToRef(points[i], curvect);
  55642. lg += curvect.length();
  55643. }
  55644. shft = lg / nbSeg;
  55645. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  55646. for (i = 0; i < points.length - 1; i++) {
  55647. points[i + 1].subtractToRef(points[i], curvect);
  55648. nb = Math.floor(curvect.length() / shft);
  55649. curvect.normalize();
  55650. j = 0;
  55651. while (j < nb && p < positions.length) {
  55652. curshft = shft * j;
  55653. positions[p] = points[i].x + curshft * curvect.x;
  55654. positions[p + 1] = points[i].y + curshft * curvect.y;
  55655. positions[p + 2] = points[i].z + curshft * curvect.z;
  55656. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  55657. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  55658. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  55659. p += 6;
  55660. j++;
  55661. }
  55662. }
  55663. while (p < positions.length) {
  55664. positions[p] = points[i].x;
  55665. positions[p + 1] = points[i].y;
  55666. positions[p + 2] = points[i].z;
  55667. p += 3;
  55668. }
  55669. };
  55670. instance.updateMeshPositions(positionFunction, false);
  55671. return instance;
  55672. }
  55673. // dashed lines creation
  55674. var dashedLines = new BABYLON.LinesMesh(name, scene);
  55675. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  55676. vertexData.applyToMesh(dashedLines, options.updatable);
  55677. dashedLines.dashSize = dashSize;
  55678. dashedLines.gapSize = gapSize;
  55679. return dashedLines;
  55680. };
  55681. /**
  55682. * Creates an extruded shape mesh.
  55683. * 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.
  55684. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  55685. *
  55686. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  55687. * 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
  55688. * extruded along the Z axis.
  55689. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  55690. * 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.
  55691. * The parameter `scale` (float, default 1) is the value to scale the shape.
  55692. * 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
  55693. * 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
  55694. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  55695. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55696. * 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).
  55697. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55698. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  55699. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55700. */
  55701. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  55702. if (scene === void 0) { scene = null; }
  55703. var path = options.path;
  55704. var shape = options.shape;
  55705. var scale = options.scale || 1;
  55706. var rotation = options.rotation || 0;
  55707. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  55708. var updatable = options.updatable;
  55709. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55710. var instance = options.instance || null;
  55711. var invertUV = options.invertUV || false;
  55712. 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);
  55713. };
  55714. /**
  55715. * Creates an custom extruded shape mesh.
  55716. * 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.
  55717. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  55718. *
  55719. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  55720. * 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
  55721. * extruded along the Z axis.
  55722. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  55723. * 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
  55724. * and the distance of this point from the begining of the path :
  55725. * ```javascript
  55726. * var rotationFunction = function(i, distance) {
  55727. * // do things
  55728. * return rotationValue; }
  55729. * ```
  55730. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  55731. * 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
  55732. * and the distance of this point from the begining of the path :
  55733. * ```javascript
  55734. * var scaleFunction = function(i, distance) {
  55735. * // do things
  55736. * return scaleValue;}
  55737. * ```
  55738. * It must returns a float value that will be the scale value applied to the shape on each path point.
  55739. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  55740. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  55741. * 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
  55742. * 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
  55743. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  55744. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55745. * 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).
  55746. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55747. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  55748. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55749. */
  55750. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  55751. var path = options.path;
  55752. var shape = options.shape;
  55753. var scaleFunction = options.scaleFunction || (function () { return 1; });
  55754. var rotationFunction = options.rotationFunction || (function () { return 0; });
  55755. var ribbonCloseArray = options.ribbonCloseArray || false;
  55756. var ribbonClosePath = options.ribbonClosePath || false;
  55757. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  55758. var updatable = options.updatable;
  55759. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55760. var instance = options.instance;
  55761. var invertUV = options.invertUV || false;
  55762. 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);
  55763. };
  55764. /**
  55765. * Creates lathe mesh.
  55766. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  55767. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  55768. *
  55769. * 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
  55770. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  55771. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  55772. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  55773. * 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.
  55774. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  55775. * 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
  55776. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55777. * 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).
  55778. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55779. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  55780. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55781. */
  55782. MeshBuilder.CreateLathe = function (name, options, scene) {
  55783. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  55784. var closed = (options.closed === undefined) ? true : options.closed;
  55785. var shape = options.shape;
  55786. var radius = options.radius || 1;
  55787. var tessellation = options.tessellation || 64;
  55788. var updatable = options.updatable;
  55789. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55790. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  55791. var pi2 = Math.PI * 2;
  55792. var paths = new Array();
  55793. var invertUV = options.invertUV || false;
  55794. var i = 0;
  55795. var p = 0;
  55796. var step = pi2 / tessellation * arc;
  55797. var rotated;
  55798. var path = new Array();
  55799. ;
  55800. for (i = 0; i <= tessellation; i++) {
  55801. var path = [];
  55802. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  55803. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  55804. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  55805. }
  55806. for (p = 0; p < shape.length; p++) {
  55807. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  55808. path.push(rotated);
  55809. }
  55810. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  55811. 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));
  55812. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  55813. }
  55814. paths.push(path);
  55815. }
  55816. // lathe ribbon
  55817. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  55818. return lathe;
  55819. };
  55820. /**
  55821. * Creates a plane mesh.
  55822. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  55823. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  55824. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  55825. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  55826. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55827. * 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).
  55828. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55829. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55830. */
  55831. MeshBuilder.CreatePlane = function (name, options, scene) {
  55832. var plane = new BABYLON.Mesh(name, scene);
  55833. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55834. plane._originalBuilderSideOrientation = options.sideOrientation;
  55835. var vertexData = BABYLON.VertexData.CreatePlane(options);
  55836. vertexData.applyToMesh(plane, options.updatable);
  55837. if (options.sourcePlane) {
  55838. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  55839. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  55840. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  55841. plane.rotate(vectorProduct, product);
  55842. }
  55843. return plane;
  55844. };
  55845. /**
  55846. * Creates a ground mesh.
  55847. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  55848. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  55849. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  55850. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55851. */
  55852. MeshBuilder.CreateGround = function (name, options, scene) {
  55853. var ground = new BABYLON.GroundMesh(name, scene);
  55854. ground._setReady(false);
  55855. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  55856. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  55857. ground._width = options.width || 1;
  55858. ground._height = options.height || 1;
  55859. ground._maxX = ground._width / 2;
  55860. ground._maxZ = ground._height / 2;
  55861. ground._minX = -ground._maxX;
  55862. ground._minZ = -ground._maxZ;
  55863. var vertexData = BABYLON.VertexData.CreateGround(options);
  55864. vertexData.applyToMesh(ground, options.updatable);
  55865. ground._setReady(true);
  55866. return ground;
  55867. };
  55868. /**
  55869. * Creates a tiled ground mesh.
  55870. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  55871. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  55872. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  55873. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  55874. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  55875. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  55876. * numbers of subdivisions on the ground width and height of each tile.
  55877. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55878. */
  55879. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  55880. var tiledGround = new BABYLON.Mesh(name, scene);
  55881. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  55882. vertexData.applyToMesh(tiledGround, options.updatable);
  55883. return tiledGround;
  55884. };
  55885. /**
  55886. * Creates a ground mesh from a height map.
  55887. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  55888. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  55889. * The parameter `url` sets the URL of the height map image resource.
  55890. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  55891. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  55892. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  55893. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  55894. * 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.
  55895. * 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).
  55896. * This function is passed the newly built mesh :
  55897. * ```javascript
  55898. * function(mesh) { // do things
  55899. * return; }
  55900. * ```
  55901. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55902. */
  55903. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  55904. var width = options.width || 10.0;
  55905. var height = options.height || 10.0;
  55906. var subdivisions = options.subdivisions || 1 | 0;
  55907. var minHeight = options.minHeight || 0.0;
  55908. var maxHeight = options.maxHeight || 1.0;
  55909. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  55910. var updatable = options.updatable;
  55911. var onReady = options.onReady;
  55912. var ground = new BABYLON.GroundMesh(name, scene);
  55913. ground._subdivisionsX = subdivisions;
  55914. ground._subdivisionsY = subdivisions;
  55915. ground._width = width;
  55916. ground._height = height;
  55917. ground._maxX = ground._width / 2.0;
  55918. ground._maxZ = ground._height / 2.0;
  55919. ground._minX = -ground._maxX;
  55920. ground._minZ = -ground._maxZ;
  55921. ground._setReady(false);
  55922. var onload = function (img) {
  55923. // Getting height map data
  55924. var canvas = document.createElement("canvas");
  55925. var context = canvas.getContext("2d");
  55926. if (!context) {
  55927. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  55928. }
  55929. if (scene.isDisposed) {
  55930. return;
  55931. }
  55932. var bufferWidth = img.width;
  55933. var bufferHeight = img.height;
  55934. canvas.width = bufferWidth;
  55935. canvas.height = bufferHeight;
  55936. context.drawImage(img, 0, 0);
  55937. // Create VertexData from map data
  55938. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  55939. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  55940. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  55941. width: width, height: height,
  55942. subdivisions: subdivisions,
  55943. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  55944. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  55945. });
  55946. vertexData.applyToMesh(ground, updatable);
  55947. ground._setReady(true);
  55948. //execute ready callback, if set
  55949. if (onReady) {
  55950. onReady(ground);
  55951. }
  55952. };
  55953. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  55954. return ground;
  55955. };
  55956. /**
  55957. * Creates a polygon mesh.
  55958. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  55959. * 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.
  55960. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55961. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55962. * 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).
  55963. * Remember you can only change the shape positions, not their number when updating a polygon.
  55964. */
  55965. MeshBuilder.CreatePolygon = function (name, options, scene) {
  55966. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55967. var shape = options.shape;
  55968. var holes = options.holes || [];
  55969. var depth = options.depth || 0;
  55970. var contours = [];
  55971. var hole = [];
  55972. for (var i = 0; i < shape.length; i++) {
  55973. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  55974. }
  55975. var epsilon = 0.00000001;
  55976. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  55977. contours.pop();
  55978. }
  55979. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  55980. for (var hNb = 0; hNb < holes.length; hNb++) {
  55981. hole = [];
  55982. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  55983. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  55984. }
  55985. polygonTriangulation.addHole(hole);
  55986. }
  55987. var polygon = polygonTriangulation.build(options.updatable, depth);
  55988. polygon._originalBuilderSideOrientation = options.sideOrientation;
  55989. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  55990. vertexData.applyToMesh(polygon, options.updatable);
  55991. return polygon;
  55992. };
  55993. ;
  55994. /**
  55995. * Creates an extruded polygon mesh, with depth in the Y direction.
  55996. * 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).
  55997. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  55998. */
  55999. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  56000. return MeshBuilder.CreatePolygon(name, options, scene);
  56001. };
  56002. ;
  56003. /**
  56004. * Creates a tube mesh.
  56005. * 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.
  56006. *
  56007. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  56008. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  56009. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  56010. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  56011. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  56012. * 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.
  56013. * It must return a radius value (positive float) :
  56014. * ```javascript
  56015. * var radiusFunction = function(i, distance) {
  56016. * // do things
  56017. * return radius; }
  56018. * ```
  56019. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  56020. * 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
  56021. * 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
  56022. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56023. * 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).
  56024. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56025. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  56026. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56027. */
  56028. MeshBuilder.CreateTube = function (name, options, scene) {
  56029. var path = options.path;
  56030. var instance = options.instance;
  56031. var radius = 1.0;
  56032. if (instance) {
  56033. radius = instance.radius;
  56034. }
  56035. if (options.radius !== undefined) {
  56036. radius = options.radius;
  56037. }
  56038. ;
  56039. var tessellation = options.tessellation || 64 | 0;
  56040. var radiusFunction = options.radiusFunction || null;
  56041. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  56042. var invertUV = options.invertUV || false;
  56043. var updatable = options.updatable;
  56044. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56045. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  56046. // tube geometry
  56047. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  56048. var tangents = path3D.getTangents();
  56049. var normals = path3D.getNormals();
  56050. var distances = path3D.getDistances();
  56051. var pi2 = Math.PI * 2;
  56052. var step = pi2 / tessellation * arc;
  56053. var returnRadius = function () { return radius; };
  56054. var radiusFunctionFinal = radiusFunction || returnRadius;
  56055. var circlePath;
  56056. var rad;
  56057. var normal;
  56058. var rotated;
  56059. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  56060. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  56061. for (var i = 0; i < path.length; i++) {
  56062. rad = radiusFunctionFinal(i, distances[i]); // current radius
  56063. circlePath = Array(); // current circle array
  56064. normal = normals[i]; // current normal
  56065. for (var t = 0; t < tessellation; t++) {
  56066. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  56067. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  56068. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  56069. rotated.scaleInPlace(rad).addInPlace(path[i]);
  56070. circlePath[t] = rotated;
  56071. }
  56072. circlePaths[index] = circlePath;
  56073. index++;
  56074. }
  56075. // cap
  56076. var capPath = function (nbPoints, pathIndex) {
  56077. var pointCap = Array();
  56078. for (var i = 0; i < nbPoints; i++) {
  56079. pointCap.push(path[pathIndex]);
  56080. }
  56081. return pointCap;
  56082. };
  56083. switch (cap) {
  56084. case BABYLON.Mesh.NO_CAP:
  56085. break;
  56086. case BABYLON.Mesh.CAP_START:
  56087. circlePaths[0] = capPath(tessellation, 0);
  56088. circlePaths[1] = circlePaths[2].slice(0);
  56089. break;
  56090. case BABYLON.Mesh.CAP_END:
  56091. circlePaths[index] = circlePaths[index - 1].slice(0);
  56092. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  56093. break;
  56094. case BABYLON.Mesh.CAP_ALL:
  56095. circlePaths[0] = capPath(tessellation, 0);
  56096. circlePaths[1] = circlePaths[2].slice(0);
  56097. circlePaths[index] = circlePaths[index - 1].slice(0);
  56098. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  56099. break;
  56100. default:
  56101. break;
  56102. }
  56103. return circlePaths;
  56104. };
  56105. var path3D;
  56106. var pathArray;
  56107. if (instance) {
  56108. var arc = options.arc || instance.arc;
  56109. path3D = (instance.path3D).update(path);
  56110. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  56111. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  56112. instance.path3D = path3D;
  56113. instance.pathArray = pathArray;
  56114. instance.arc = arc;
  56115. instance.radius = radius;
  56116. return instance;
  56117. }
  56118. // tube creation
  56119. path3D = new BABYLON.Path3D(path);
  56120. var newPathArray = new Array();
  56121. cap = (cap < 0 || cap > 3) ? 0 : cap;
  56122. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  56123. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  56124. tube.pathArray = pathArray;
  56125. tube.path3D = path3D;
  56126. tube.tessellation = tessellation;
  56127. tube.cap = cap;
  56128. tube.arc = options.arc;
  56129. tube.radius = radius;
  56130. return tube;
  56131. };
  56132. /**
  56133. * Creates a polyhedron mesh.
  56134. *
  56135. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  56136. * 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
  56137. * to choose the wanted type.
  56138. * The parameter `size` (positive float, default 1) sets the polygon size.
  56139. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  56140. * 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`.
  56141. * 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
  56142. * 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)`).
  56143. * 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
  56144. * 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.
  56145. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56146. * 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).
  56147. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56148. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56149. */
  56150. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  56151. var polyhedron = new BABYLON.Mesh(name, scene);
  56152. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56153. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  56154. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  56155. vertexData.applyToMesh(polyhedron, options.updatable);
  56156. return polyhedron;
  56157. };
  56158. /**
  56159. * Creates a decal mesh.
  56160. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  56161. * 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.
  56162. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  56163. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  56164. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  56165. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  56166. */
  56167. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  56168. var indices = sourceMesh.getIndices();
  56169. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  56170. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  56171. var position = options.position || BABYLON.Vector3.Zero();
  56172. var normal = options.normal || BABYLON.Vector3.Up();
  56173. var size = options.size || BABYLON.Vector3.One();
  56174. var angle = options.angle || 0;
  56175. // Getting correct rotation
  56176. if (!normal) {
  56177. var target = new BABYLON.Vector3(0, 0, 1);
  56178. var camera = sourceMesh.getScene().activeCamera;
  56179. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  56180. normal = camera.globalPosition.subtract(cameraWorldTarget);
  56181. }
  56182. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  56183. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  56184. var pitch = Math.atan2(normal.y, len);
  56185. // Matrix
  56186. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  56187. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  56188. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  56189. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  56190. var vertexData = new BABYLON.VertexData();
  56191. vertexData.indices = [];
  56192. vertexData.positions = [];
  56193. vertexData.normals = [];
  56194. vertexData.uvs = [];
  56195. var currentVertexDataIndex = 0;
  56196. var extractDecalVector3 = function (indexId) {
  56197. var result = new BABYLON.PositionNormalVertex();
  56198. if (!indices || !positions || !normals) {
  56199. return result;
  56200. }
  56201. var vertexId = indices[indexId];
  56202. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  56203. // Send vector to decal local world
  56204. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  56205. // Get normal
  56206. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  56207. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  56208. return result;
  56209. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  56210. var clip = function (vertices, axis) {
  56211. if (vertices.length === 0) {
  56212. return vertices;
  56213. }
  56214. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  56215. var clipVertices = function (v0, v1) {
  56216. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  56217. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  56218. };
  56219. var result = new Array();
  56220. for (var index = 0; index < vertices.length; index += 3) {
  56221. var v1Out;
  56222. var v2Out;
  56223. var v3Out;
  56224. var total = 0;
  56225. var nV1 = null;
  56226. var nV2 = null;
  56227. var nV3 = null;
  56228. var nV4 = null;
  56229. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  56230. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  56231. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  56232. v1Out = d1 > 0;
  56233. v2Out = d2 > 0;
  56234. v3Out = d3 > 0;
  56235. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  56236. switch (total) {
  56237. case 0:
  56238. result.push(vertices[index]);
  56239. result.push(vertices[index + 1]);
  56240. result.push(vertices[index + 2]);
  56241. break;
  56242. case 1:
  56243. if (v1Out) {
  56244. nV1 = vertices[index + 1];
  56245. nV2 = vertices[index + 2];
  56246. nV3 = clipVertices(vertices[index], nV1);
  56247. nV4 = clipVertices(vertices[index], nV2);
  56248. }
  56249. if (v2Out) {
  56250. nV1 = vertices[index];
  56251. nV2 = vertices[index + 2];
  56252. nV3 = clipVertices(vertices[index + 1], nV1);
  56253. nV4 = clipVertices(vertices[index + 1], nV2);
  56254. result.push(nV3);
  56255. result.push(nV2.clone());
  56256. result.push(nV1.clone());
  56257. result.push(nV2.clone());
  56258. result.push(nV3.clone());
  56259. result.push(nV4);
  56260. break;
  56261. }
  56262. if (v3Out) {
  56263. nV1 = vertices[index];
  56264. nV2 = vertices[index + 1];
  56265. nV3 = clipVertices(vertices[index + 2], nV1);
  56266. nV4 = clipVertices(vertices[index + 2], nV2);
  56267. }
  56268. if (nV1 && nV2 && nV3 && nV4) {
  56269. result.push(nV1.clone());
  56270. result.push(nV2.clone());
  56271. result.push(nV3);
  56272. result.push(nV4);
  56273. result.push(nV3.clone());
  56274. result.push(nV2.clone());
  56275. }
  56276. break;
  56277. case 2:
  56278. if (!v1Out) {
  56279. nV1 = vertices[index].clone();
  56280. nV2 = clipVertices(nV1, vertices[index + 1]);
  56281. nV3 = clipVertices(nV1, vertices[index + 2]);
  56282. result.push(nV1);
  56283. result.push(nV2);
  56284. result.push(nV3);
  56285. }
  56286. if (!v2Out) {
  56287. nV1 = vertices[index + 1].clone();
  56288. nV2 = clipVertices(nV1, vertices[index + 2]);
  56289. nV3 = clipVertices(nV1, vertices[index]);
  56290. result.push(nV1);
  56291. result.push(nV2);
  56292. result.push(nV3);
  56293. }
  56294. if (!v3Out) {
  56295. nV1 = vertices[index + 2].clone();
  56296. nV2 = clipVertices(nV1, vertices[index]);
  56297. nV3 = clipVertices(nV1, vertices[index + 1]);
  56298. result.push(nV1);
  56299. result.push(nV2);
  56300. result.push(nV3);
  56301. }
  56302. break;
  56303. case 3:
  56304. break;
  56305. }
  56306. }
  56307. return result;
  56308. };
  56309. for (var index = 0; index < indices.length; index += 3) {
  56310. var faceVertices = new Array();
  56311. faceVertices.push(extractDecalVector3(index));
  56312. faceVertices.push(extractDecalVector3(index + 1));
  56313. faceVertices.push(extractDecalVector3(index + 2));
  56314. // Clip
  56315. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  56316. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  56317. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  56318. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  56319. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  56320. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  56321. if (faceVertices.length === 0) {
  56322. continue;
  56323. }
  56324. // Add UVs and get back to world
  56325. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  56326. var vertex = faceVertices[vIndex];
  56327. //TODO check for Int32Array | Uint32Array | Uint16Array
  56328. vertexData.indices.push(currentVertexDataIndex);
  56329. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  56330. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  56331. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  56332. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  56333. currentVertexDataIndex++;
  56334. }
  56335. }
  56336. // Return mesh
  56337. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  56338. vertexData.applyToMesh(decal);
  56339. decal.position = position.clone();
  56340. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  56341. return decal;
  56342. };
  56343. // Privates
  56344. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  56345. // extrusion geometry
  56346. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  56347. var tangents = path3D.getTangents();
  56348. var normals = path3D.getNormals();
  56349. var binormals = path3D.getBinormals();
  56350. var distances = path3D.getDistances();
  56351. var angle = 0;
  56352. var returnScale = function () { return scale !== null ? scale : 1; };
  56353. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  56354. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  56355. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  56356. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  56357. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  56358. for (var i = 0; i < curve.length; i++) {
  56359. var shapePath = new Array();
  56360. var angleStep = rotate(i, distances[i]);
  56361. var scaleRatio = scl(i, distances[i]);
  56362. for (var p = 0; p < shape.length; p++) {
  56363. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  56364. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  56365. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  56366. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  56367. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  56368. shapePath[p] = rotated;
  56369. }
  56370. shapePaths[index] = shapePath;
  56371. angle += angleStep;
  56372. index++;
  56373. }
  56374. // cap
  56375. var capPath = function (shapePath) {
  56376. var pointCap = Array();
  56377. var barycenter = BABYLON.Vector3.Zero();
  56378. var i;
  56379. for (i = 0; i < shapePath.length; i++) {
  56380. barycenter.addInPlace(shapePath[i]);
  56381. }
  56382. barycenter.scaleInPlace(1.0 / shapePath.length);
  56383. for (i = 0; i < shapePath.length; i++) {
  56384. pointCap.push(barycenter);
  56385. }
  56386. return pointCap;
  56387. };
  56388. switch (cap) {
  56389. case BABYLON.Mesh.NO_CAP:
  56390. break;
  56391. case BABYLON.Mesh.CAP_START:
  56392. shapePaths[0] = capPath(shapePaths[2]);
  56393. shapePaths[1] = shapePaths[2];
  56394. break;
  56395. case BABYLON.Mesh.CAP_END:
  56396. shapePaths[index] = shapePaths[index - 1];
  56397. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  56398. break;
  56399. case BABYLON.Mesh.CAP_ALL:
  56400. shapePaths[0] = capPath(shapePaths[2]);
  56401. shapePaths[1] = shapePaths[2];
  56402. shapePaths[index] = shapePaths[index - 1];
  56403. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  56404. break;
  56405. default:
  56406. break;
  56407. }
  56408. return shapePaths;
  56409. };
  56410. var path3D;
  56411. var pathArray;
  56412. if (instance) {
  56413. path3D = (instance.path3D).update(curve);
  56414. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  56415. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  56416. return instance;
  56417. }
  56418. // extruded shape creation
  56419. path3D = new BABYLON.Path3D(curve);
  56420. var newShapePaths = new Array();
  56421. cap = (cap < 0 || cap > 3) ? 0 : cap;
  56422. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  56423. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  56424. extrudedGeneric.pathArray = pathArray;
  56425. extrudedGeneric.path3D = path3D;
  56426. extrudedGeneric.cap = cap;
  56427. return extrudedGeneric;
  56428. };
  56429. return MeshBuilder;
  56430. }());
  56431. BABYLON.MeshBuilder = MeshBuilder;
  56432. })(BABYLON || (BABYLON = {}));
  56433. //# sourceMappingURL=babylon.meshBuilder.js.map
  56434. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  56435. var BABYLON;
  56436. (function (BABYLON) {
  56437. /**
  56438. * Draco compression (https://google.github.io/draco/)
  56439. */
  56440. var DracoCompression = /** @class */ (function () {
  56441. /**
  56442. * Constructor
  56443. * @param numWorkers The number of workers for async operations
  56444. */
  56445. function DracoCompression(numWorkers) {
  56446. if (numWorkers === void 0) { numWorkers = (navigator.hardwareConcurrency || 4); }
  56447. var workers = new Array(numWorkers);
  56448. for (var i = 0; i < workers.length; i++) {
  56449. var worker = new Worker(DracoCompression._WorkerBlobUrl);
  56450. worker.postMessage({ id: "initDecoder", url: DracoCompression.DecoderUrl });
  56451. workers[i] = worker;
  56452. }
  56453. this._workerPool = new BABYLON.WorkerPool(workers);
  56454. }
  56455. /**
  56456. * Stop all async operations and release resources.
  56457. */
  56458. DracoCompression.prototype.dispose = function () {
  56459. this._workerPool.dispose();
  56460. delete this._workerPool;
  56461. };
  56462. /**
  56463. * Decode Draco compressed mesh data to vertex data.
  56464. * @param data The array buffer view for the Draco compression data
  56465. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  56466. * @returns A promise that resolves with the decoded vertex data
  56467. */
  56468. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  56469. var _this = this;
  56470. return new Promise(function (resolve, reject) {
  56471. _this._workerPool.push(function (worker, onComplete) {
  56472. var vertexData = new BABYLON.VertexData();
  56473. var onError = function (error) {
  56474. worker.removeEventListener("error", onError);
  56475. worker.removeEventListener("message", onMessage);
  56476. reject(error);
  56477. onComplete();
  56478. };
  56479. var onMessage = function (message) {
  56480. if (message.data === "done") {
  56481. worker.removeEventListener("error", onError);
  56482. worker.removeEventListener("message", onMessage);
  56483. resolve(vertexData);
  56484. onComplete();
  56485. }
  56486. else if (message.data.id === "indices") {
  56487. vertexData.indices = message.data.value;
  56488. }
  56489. else {
  56490. vertexData.set(message.data.value, message.data.id);
  56491. }
  56492. };
  56493. worker.addEventListener("error", onError);
  56494. worker.addEventListener("message", onMessage);
  56495. var dataCopy = new Uint8Array(data.byteLength);
  56496. dataCopy.set(new Uint8Array(data.buffer, data.byteOffset, data.byteLength));
  56497. worker.postMessage({ id: "decodeMesh", data: dataCopy, attributes: attributes }, [dataCopy.buffer]);
  56498. });
  56499. });
  56500. };
  56501. /**
  56502. * The worker function that gets converted to a blob url to pass into a worker.
  56503. */
  56504. DracoCompression._Worker = function () {
  56505. // self is actually a DedicatedWorkerGlobalScope
  56506. var _self = self;
  56507. var decodeMesh = function (data, attributes) {
  56508. var dracoModule = new DracoDecoderModule();
  56509. var buffer = new dracoModule.DecoderBuffer();
  56510. buffer.Init(data, data.byteLength);
  56511. var decoder = new dracoModule.Decoder();
  56512. var geometry;
  56513. var status;
  56514. try {
  56515. var type = decoder.GetEncodedGeometryType(buffer);
  56516. switch (type) {
  56517. case dracoModule.TRIANGULAR_MESH:
  56518. geometry = new dracoModule.Mesh();
  56519. status = decoder.DecodeBufferToMesh(buffer, geometry);
  56520. break;
  56521. case dracoModule.POINT_CLOUD:
  56522. geometry = new dracoModule.PointCloud();
  56523. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  56524. break;
  56525. default:
  56526. throw new Error("Invalid geometry type " + type);
  56527. }
  56528. if (!status.ok() || !geometry.ptr) {
  56529. throw new Error(status.error_msg());
  56530. }
  56531. var numPoints = geometry.num_points();
  56532. if (type === dracoModule.TRIANGULAR_MESH) {
  56533. var numFaces = geometry.num_faces();
  56534. var faceIndices = new dracoModule.DracoInt32Array();
  56535. try {
  56536. var indices = new Uint32Array(numFaces * 3);
  56537. for (var i = 0; i < numFaces; i++) {
  56538. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  56539. var offset = i * 3;
  56540. indices[offset + 0] = faceIndices.GetValue(0);
  56541. indices[offset + 1] = faceIndices.GetValue(1);
  56542. indices[offset + 2] = faceIndices.GetValue(2);
  56543. }
  56544. _self.postMessage({ id: "indices", value: indices }, [indices.buffer]);
  56545. }
  56546. finally {
  56547. dracoModule.destroy(faceIndices);
  56548. }
  56549. }
  56550. for (var kind in attributes) {
  56551. var uniqueId = attributes[kind];
  56552. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  56553. var dracoData = new dracoModule.DracoFloat32Array();
  56554. try {
  56555. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  56556. var babylonData = new Float32Array(numPoints * attribute.num_components());
  56557. for (var i = 0; i < babylonData.length; i++) {
  56558. babylonData[i] = dracoData.GetValue(i);
  56559. }
  56560. _self.postMessage({ id: kind, value: babylonData }, [babylonData.buffer]);
  56561. }
  56562. finally {
  56563. dracoModule.destroy(dracoData);
  56564. }
  56565. }
  56566. }
  56567. finally {
  56568. if (geometry) {
  56569. dracoModule.destroy(geometry);
  56570. }
  56571. dracoModule.destroy(decoder);
  56572. dracoModule.destroy(buffer);
  56573. }
  56574. _self.postMessage("done");
  56575. };
  56576. _self.onmessage = function (event) {
  56577. switch (event.data.id) {
  56578. case "initDecoder": {
  56579. importScripts(event.data.url);
  56580. break;
  56581. }
  56582. case "decodeMesh": {
  56583. decodeMesh(event.data.data, event.data.attributes);
  56584. break;
  56585. }
  56586. }
  56587. };
  56588. };
  56589. DracoCompression._GetDefaultDecoderUrl = function () {
  56590. for (var i = 0; i < document.scripts.length; i++) {
  56591. if (document.scripts[i].type === "text/x-draco-decoder") {
  56592. return document.scripts[i].src;
  56593. }
  56594. }
  56595. return null;
  56596. };
  56597. /**
  56598. * Gets the url to the draco decoder if available.
  56599. */
  56600. DracoCompression.DecoderUrl = DracoCompression._GetDefaultDecoderUrl();
  56601. DracoCompression._WorkerBlobUrl = URL.createObjectURL(new Blob(["(" + DracoCompression._Worker.toString() + ")()"], { type: "application/javascript" }));
  56602. return DracoCompression;
  56603. }());
  56604. BABYLON.DracoCompression = DracoCompression;
  56605. })(BABYLON || (BABYLON = {}));
  56606. //# sourceMappingURL=babylon.dracoCompression.js.map
  56607. var BABYLON;
  56608. (function (BABYLON) {
  56609. var AudioEngine = /** @class */ (function () {
  56610. function AudioEngine() {
  56611. this._audioContext = null;
  56612. this._audioContextInitialized = false;
  56613. this.canUseWebAudio = false;
  56614. this.WarnedWebAudioUnsupported = false;
  56615. this.unlocked = false;
  56616. this.isMP3supported = false;
  56617. this.isOGGsupported = false;
  56618. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  56619. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  56620. this.canUseWebAudio = true;
  56621. }
  56622. var audioElem = document.createElement('audio');
  56623. try {
  56624. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  56625. this.isMP3supported = true;
  56626. }
  56627. }
  56628. catch (e) {
  56629. // protect error during capability check.
  56630. }
  56631. try {
  56632. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  56633. this.isOGGsupported = true;
  56634. }
  56635. }
  56636. catch (e) {
  56637. // protect error during capability check.
  56638. }
  56639. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  56640. this._unlockiOSaudio();
  56641. }
  56642. else {
  56643. this.unlocked = true;
  56644. }
  56645. }
  56646. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  56647. get: function () {
  56648. if (!this._audioContextInitialized) {
  56649. this._initializeAudioContext();
  56650. }
  56651. return this._audioContext;
  56652. },
  56653. enumerable: true,
  56654. configurable: true
  56655. });
  56656. AudioEngine.prototype._unlockiOSaudio = function () {
  56657. var _this = this;
  56658. var unlockaudio = function () {
  56659. if (!_this.audioContext) {
  56660. return;
  56661. }
  56662. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  56663. var source = _this.audioContext.createBufferSource();
  56664. source.buffer = buffer;
  56665. source.connect(_this.audioContext.destination);
  56666. source.start(0);
  56667. setTimeout(function () {
  56668. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  56669. _this.unlocked = true;
  56670. window.removeEventListener('touchend', unlockaudio, false);
  56671. if (_this.onAudioUnlocked) {
  56672. _this.onAudioUnlocked();
  56673. }
  56674. }
  56675. }, 0);
  56676. };
  56677. window.addEventListener('touchend', unlockaudio, false);
  56678. };
  56679. AudioEngine.prototype._initializeAudioContext = function () {
  56680. try {
  56681. if (this.canUseWebAudio) {
  56682. this._audioContext = new AudioContext();
  56683. // create a global volume gain node
  56684. this.masterGain = this._audioContext.createGain();
  56685. this.masterGain.gain.value = 1;
  56686. this.masterGain.connect(this._audioContext.destination);
  56687. this._audioContextInitialized = true;
  56688. }
  56689. }
  56690. catch (e) {
  56691. this.canUseWebAudio = false;
  56692. BABYLON.Tools.Error("Web Audio: " + e.message);
  56693. }
  56694. };
  56695. AudioEngine.prototype.dispose = function () {
  56696. if (this.canUseWebAudio && this._audioContextInitialized) {
  56697. if (this._connectedAnalyser && this._audioContext) {
  56698. this._connectedAnalyser.stopDebugCanvas();
  56699. this._connectedAnalyser.dispose();
  56700. this.masterGain.disconnect();
  56701. this.masterGain.connect(this._audioContext.destination);
  56702. this._connectedAnalyser = null;
  56703. }
  56704. this.masterGain.gain.value = 1;
  56705. }
  56706. this.WarnedWebAudioUnsupported = false;
  56707. };
  56708. AudioEngine.prototype.getGlobalVolume = function () {
  56709. if (this.canUseWebAudio && this._audioContextInitialized) {
  56710. return this.masterGain.gain.value;
  56711. }
  56712. else {
  56713. return -1;
  56714. }
  56715. };
  56716. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  56717. if (this.canUseWebAudio && this._audioContextInitialized) {
  56718. this.masterGain.gain.value = newVolume;
  56719. }
  56720. };
  56721. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  56722. if (this._connectedAnalyser) {
  56723. this._connectedAnalyser.stopDebugCanvas();
  56724. }
  56725. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  56726. this._connectedAnalyser = analyser;
  56727. this.masterGain.disconnect();
  56728. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  56729. }
  56730. };
  56731. return AudioEngine;
  56732. }());
  56733. BABYLON.AudioEngine = AudioEngine;
  56734. })(BABYLON || (BABYLON = {}));
  56735. //# sourceMappingURL=babylon.audioEngine.js.map
  56736. var BABYLON;
  56737. (function (BABYLON) {
  56738. var Sound = /** @class */ (function () {
  56739. /**
  56740. * Create a sound and attach it to a scene
  56741. * @param name Name of your sound
  56742. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  56743. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  56744. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  56745. */
  56746. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  56747. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  56748. var _this = this;
  56749. this.autoplay = false;
  56750. this.loop = false;
  56751. this.useCustomAttenuation = false;
  56752. this.spatialSound = false;
  56753. this.refDistance = 1;
  56754. this.rolloffFactor = 1;
  56755. this.maxDistance = 100;
  56756. this.distanceModel = "linear";
  56757. this._panningModel = "equalpower";
  56758. this._playbackRate = 1;
  56759. this._streaming = false;
  56760. this._startTime = 0;
  56761. this._startOffset = 0;
  56762. this._position = BABYLON.Vector3.Zero();
  56763. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  56764. this._volume = 1;
  56765. this._isReadyToPlay = false;
  56766. this.isPlaying = false;
  56767. this.isPaused = false;
  56768. this._isDirectional = false;
  56769. // Used if you'd like to create a directional sound.
  56770. // If not set, the sound will be omnidirectional
  56771. this._coneInnerAngle = 360;
  56772. this._coneOuterAngle = 360;
  56773. this._coneOuterGain = 0;
  56774. this._isOutputConnected = false;
  56775. this._urlType = "Unknown";
  56776. this.name = name;
  56777. this._scene = scene;
  56778. this._readyToPlayCallback = readyToPlayCallback;
  56779. // Default custom attenuation function is a linear attenuation
  56780. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  56781. if (currentDistance < maxDistance) {
  56782. return currentVolume * (1 - currentDistance / maxDistance);
  56783. }
  56784. else {
  56785. return 0;
  56786. }
  56787. };
  56788. if (options) {
  56789. this.autoplay = options.autoplay || false;
  56790. this.loop = options.loop || false;
  56791. // if volume === 0, we need another way to check this option
  56792. if (options.volume !== undefined) {
  56793. this._volume = options.volume;
  56794. }
  56795. this.spatialSound = options.spatialSound || false;
  56796. this.maxDistance = options.maxDistance || 100;
  56797. this.useCustomAttenuation = options.useCustomAttenuation || false;
  56798. this.rolloffFactor = options.rolloffFactor || 1;
  56799. this.refDistance = options.refDistance || 1;
  56800. this.distanceModel = options.distanceModel || "linear";
  56801. this._playbackRate = options.playbackRate || 1;
  56802. this._streaming = options.streaming || false;
  56803. }
  56804. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  56805. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  56806. this._soundGain.gain.value = this._volume;
  56807. this._inputAudioNode = this._soundGain;
  56808. this._ouputAudioNode = this._soundGain;
  56809. if (this.spatialSound) {
  56810. this._createSpatialParameters();
  56811. }
  56812. this._scene.mainSoundTrack.AddSound(this);
  56813. var validParameter = true;
  56814. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  56815. if (urlOrArrayBuffer) {
  56816. if (typeof (urlOrArrayBuffer) === "string")
  56817. this._urlType = "String";
  56818. if (Array.isArray(urlOrArrayBuffer))
  56819. this._urlType = "Array";
  56820. if (urlOrArrayBuffer instanceof ArrayBuffer)
  56821. this._urlType = "ArrayBuffer";
  56822. var urls = [];
  56823. var codecSupportedFound = false;
  56824. switch (this._urlType) {
  56825. case "ArrayBuffer":
  56826. if (urlOrArrayBuffer.byteLength > 0) {
  56827. codecSupportedFound = true;
  56828. this._soundLoaded(urlOrArrayBuffer);
  56829. }
  56830. break;
  56831. case "String":
  56832. urls.push(urlOrArrayBuffer);
  56833. case "Array":
  56834. if (urls.length === 0)
  56835. urls = urlOrArrayBuffer;
  56836. // If we found a supported format, we load it immediately and stop the loop
  56837. for (var i = 0; i < urls.length; i++) {
  56838. var url = urls[i];
  56839. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  56840. codecSupportedFound = true;
  56841. }
  56842. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  56843. codecSupportedFound = true;
  56844. }
  56845. if (url.indexOf(".wav", url.length - 4) !== -1) {
  56846. codecSupportedFound = true;
  56847. }
  56848. if (url.indexOf("blob:") !== -1) {
  56849. codecSupportedFound = true;
  56850. }
  56851. if (codecSupportedFound) {
  56852. // Loading sound using XHR2
  56853. if (!this._streaming) {
  56854. this._scene._loadFile(url, function (data) { _this._soundLoaded(data); }, undefined, true, true);
  56855. }
  56856. else {
  56857. this._htmlAudioElement = new Audio(url);
  56858. this._htmlAudioElement.controls = false;
  56859. this._htmlAudioElement.loop = this.loop;
  56860. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  56861. this._htmlAudioElement.preload = "auto";
  56862. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  56863. _this._isReadyToPlay = true;
  56864. if (_this.autoplay) {
  56865. _this.play();
  56866. }
  56867. if (_this._readyToPlayCallback) {
  56868. _this._readyToPlayCallback();
  56869. }
  56870. });
  56871. document.body.appendChild(this._htmlAudioElement);
  56872. }
  56873. break;
  56874. }
  56875. }
  56876. break;
  56877. default:
  56878. validParameter = false;
  56879. break;
  56880. }
  56881. if (!validParameter) {
  56882. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  56883. }
  56884. else {
  56885. if (!codecSupportedFound) {
  56886. this._isReadyToPlay = true;
  56887. // Simulating a ready to play event to avoid breaking code path
  56888. if (this._readyToPlayCallback) {
  56889. window.setTimeout(function () {
  56890. if (_this._readyToPlayCallback) {
  56891. _this._readyToPlayCallback();
  56892. }
  56893. }, 1000);
  56894. }
  56895. }
  56896. }
  56897. }
  56898. }
  56899. else {
  56900. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  56901. this._scene.mainSoundTrack.AddSound(this);
  56902. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  56903. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  56904. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  56905. }
  56906. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  56907. if (this._readyToPlayCallback) {
  56908. window.setTimeout(function () {
  56909. if (_this._readyToPlayCallback) {
  56910. _this._readyToPlayCallback();
  56911. }
  56912. }, 1000);
  56913. }
  56914. }
  56915. }
  56916. Sound.prototype.dispose = function () {
  56917. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  56918. if (this.isPlaying) {
  56919. this.stop();
  56920. }
  56921. this._isReadyToPlay = false;
  56922. if (this.soundTrackId === -1) {
  56923. this._scene.mainSoundTrack.RemoveSound(this);
  56924. }
  56925. else {
  56926. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  56927. }
  56928. if (this._soundGain) {
  56929. this._soundGain.disconnect();
  56930. this._soundGain = null;
  56931. }
  56932. if (this._soundPanner) {
  56933. this._soundPanner.disconnect();
  56934. this._soundPanner = null;
  56935. }
  56936. if (this._soundSource) {
  56937. this._soundSource.disconnect();
  56938. this._soundSource = null;
  56939. }
  56940. this._audioBuffer = null;
  56941. if (this._htmlAudioElement) {
  56942. this._htmlAudioElement.pause();
  56943. this._htmlAudioElement.src = "";
  56944. document.body.removeChild(this._htmlAudioElement);
  56945. }
  56946. if (this._connectedMesh && this._registerFunc) {
  56947. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  56948. this._connectedMesh = null;
  56949. }
  56950. }
  56951. };
  56952. Sound.prototype.isReady = function () {
  56953. return this._isReadyToPlay;
  56954. };
  56955. Sound.prototype._soundLoaded = function (audioData) {
  56956. var _this = this;
  56957. if (!BABYLON.Engine.audioEngine.audioContext) {
  56958. return;
  56959. }
  56960. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  56961. _this._audioBuffer = buffer;
  56962. _this._isReadyToPlay = true;
  56963. if (_this.autoplay) {
  56964. _this.play();
  56965. }
  56966. if (_this._readyToPlayCallback) {
  56967. _this._readyToPlayCallback();
  56968. }
  56969. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  56970. };
  56971. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  56972. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  56973. this._audioBuffer = audioBuffer;
  56974. this._isReadyToPlay = true;
  56975. }
  56976. };
  56977. Sound.prototype.updateOptions = function (options) {
  56978. if (options) {
  56979. this.loop = options.loop || this.loop;
  56980. this.maxDistance = options.maxDistance || this.maxDistance;
  56981. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  56982. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  56983. this.refDistance = options.refDistance || this.refDistance;
  56984. this.distanceModel = options.distanceModel || this.distanceModel;
  56985. this._playbackRate = options.playbackRate || this._playbackRate;
  56986. this._updateSpatialParameters();
  56987. if (this.isPlaying) {
  56988. if (this._streaming) {
  56989. this._htmlAudioElement.playbackRate = this._playbackRate;
  56990. }
  56991. else {
  56992. if (this._soundSource) {
  56993. this._soundSource.playbackRate.value = this._playbackRate;
  56994. }
  56995. }
  56996. }
  56997. }
  56998. };
  56999. Sound.prototype._createSpatialParameters = function () {
  57000. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  57001. if (this._scene.headphone) {
  57002. this._panningModel = "HRTF";
  57003. }
  57004. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  57005. this._updateSpatialParameters();
  57006. this._soundPanner.connect(this._ouputAudioNode);
  57007. this._inputAudioNode = this._soundPanner;
  57008. }
  57009. };
  57010. Sound.prototype._updateSpatialParameters = function () {
  57011. if (this.spatialSound && this._soundPanner) {
  57012. if (this.useCustomAttenuation) {
  57013. // Tricks to disable in a way embedded Web Audio attenuation
  57014. this._soundPanner.distanceModel = "linear";
  57015. this._soundPanner.maxDistance = Number.MAX_VALUE;
  57016. this._soundPanner.refDistance = 1;
  57017. this._soundPanner.rolloffFactor = 1;
  57018. this._soundPanner.panningModel = this._panningModel;
  57019. }
  57020. else {
  57021. this._soundPanner.distanceModel = this.distanceModel;
  57022. this._soundPanner.maxDistance = this.maxDistance;
  57023. this._soundPanner.refDistance = this.refDistance;
  57024. this._soundPanner.rolloffFactor = this.rolloffFactor;
  57025. this._soundPanner.panningModel = this._panningModel;
  57026. }
  57027. }
  57028. };
  57029. Sound.prototype.switchPanningModelToHRTF = function () {
  57030. this._panningModel = "HRTF";
  57031. this._switchPanningModel();
  57032. };
  57033. Sound.prototype.switchPanningModelToEqualPower = function () {
  57034. this._panningModel = "equalpower";
  57035. this._switchPanningModel();
  57036. };
  57037. Sound.prototype._switchPanningModel = function () {
  57038. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  57039. this._soundPanner.panningModel = this._panningModel;
  57040. }
  57041. };
  57042. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  57043. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  57044. if (this._isOutputConnected) {
  57045. this._ouputAudioNode.disconnect();
  57046. }
  57047. this._ouputAudioNode.connect(soundTrackAudioNode);
  57048. this._isOutputConnected = true;
  57049. }
  57050. };
  57051. /**
  57052. * Transform this sound into a directional source
  57053. * @param coneInnerAngle Size of the inner cone in degree
  57054. * @param coneOuterAngle Size of the outer cone in degree
  57055. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  57056. */
  57057. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  57058. if (coneOuterAngle < coneInnerAngle) {
  57059. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  57060. return;
  57061. }
  57062. this._coneInnerAngle = coneInnerAngle;
  57063. this._coneOuterAngle = coneOuterAngle;
  57064. this._coneOuterGain = coneOuterGain;
  57065. this._isDirectional = true;
  57066. if (this.isPlaying && this.loop) {
  57067. this.stop();
  57068. this.play();
  57069. }
  57070. };
  57071. Sound.prototype.setPosition = function (newPosition) {
  57072. this._position = newPosition;
  57073. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  57074. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  57075. }
  57076. };
  57077. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  57078. this._localDirection = newLocalDirection;
  57079. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  57080. this._updateDirection();
  57081. }
  57082. };
  57083. Sound.prototype._updateDirection = function () {
  57084. if (!this._connectedMesh || !this._soundPanner) {
  57085. return;
  57086. }
  57087. var mat = this._connectedMesh.getWorldMatrix();
  57088. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  57089. direction.normalize();
  57090. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  57091. };
  57092. Sound.prototype.updateDistanceFromListener = function () {
  57093. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  57094. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  57095. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  57096. }
  57097. };
  57098. Sound.prototype.setAttenuationFunction = function (callback) {
  57099. this._customAttenuationFunction = callback;
  57100. };
  57101. /**
  57102. * Play the sound
  57103. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  57104. * @param offset (optional) Start the sound setting it at a specific time
  57105. */
  57106. Sound.prototype.play = function (time, offset) {
  57107. var _this = this;
  57108. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  57109. try {
  57110. if (this._startOffset < 0) {
  57111. time = -this._startOffset;
  57112. this._startOffset = 0;
  57113. }
  57114. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  57115. if (!this._soundSource || !this._streamingSource) {
  57116. if (this.spatialSound && this._soundPanner) {
  57117. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  57118. if (this._isDirectional) {
  57119. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  57120. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  57121. this._soundPanner.coneOuterGain = this._coneOuterGain;
  57122. if (this._connectedMesh) {
  57123. this._updateDirection();
  57124. }
  57125. else {
  57126. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  57127. }
  57128. }
  57129. }
  57130. }
  57131. if (this._streaming) {
  57132. if (!this._streamingSource) {
  57133. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  57134. this._htmlAudioElement.onended = function () { _this._onended(); };
  57135. this._htmlAudioElement.playbackRate = this._playbackRate;
  57136. }
  57137. this._streamingSource.disconnect();
  57138. this._streamingSource.connect(this._inputAudioNode);
  57139. this._htmlAudioElement.play();
  57140. }
  57141. else {
  57142. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  57143. this._soundSource.buffer = this._audioBuffer;
  57144. this._soundSource.connect(this._inputAudioNode);
  57145. this._soundSource.loop = this.loop;
  57146. this._soundSource.playbackRate.value = this._playbackRate;
  57147. this._soundSource.onended = function () { _this._onended(); };
  57148. if (this._soundSource.buffer) {
  57149. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  57150. }
  57151. }
  57152. this._startTime = startTime;
  57153. this.isPlaying = true;
  57154. this.isPaused = false;
  57155. }
  57156. catch (ex) {
  57157. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  57158. }
  57159. }
  57160. };
  57161. Sound.prototype._onended = function () {
  57162. this.isPlaying = false;
  57163. if (this.onended) {
  57164. this.onended();
  57165. }
  57166. };
  57167. /**
  57168. * Stop the sound
  57169. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  57170. */
  57171. Sound.prototype.stop = function (time) {
  57172. if (this.isPlaying) {
  57173. if (this._streaming) {
  57174. this._htmlAudioElement.pause();
  57175. // Test needed for Firefox or it will generate an Invalid State Error
  57176. if (this._htmlAudioElement.currentTime > 0) {
  57177. this._htmlAudioElement.currentTime = 0;
  57178. }
  57179. }
  57180. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  57181. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  57182. this._soundSource.stop(stopTime);
  57183. this._soundSource.onended = function () { };
  57184. if (!this.isPaused) {
  57185. this._startOffset = 0;
  57186. }
  57187. }
  57188. this.isPlaying = false;
  57189. }
  57190. };
  57191. Sound.prototype.pause = function () {
  57192. if (this.isPlaying) {
  57193. this.isPaused = true;
  57194. if (this._streaming) {
  57195. this._htmlAudioElement.pause();
  57196. }
  57197. else if (BABYLON.Engine.audioEngine.audioContext) {
  57198. this.stop(0);
  57199. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  57200. }
  57201. }
  57202. };
  57203. Sound.prototype.setVolume = function (newVolume, time) {
  57204. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  57205. if (time && BABYLON.Engine.audioEngine.audioContext) {
  57206. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  57207. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  57208. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  57209. }
  57210. else {
  57211. this._soundGain.gain.value = newVolume;
  57212. }
  57213. }
  57214. this._volume = newVolume;
  57215. };
  57216. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  57217. this._playbackRate = newPlaybackRate;
  57218. if (this.isPlaying) {
  57219. if (this._streaming) {
  57220. this._htmlAudioElement.playbackRate = this._playbackRate;
  57221. }
  57222. else if (this._soundSource) {
  57223. this._soundSource.playbackRate.value = this._playbackRate;
  57224. }
  57225. }
  57226. };
  57227. Sound.prototype.getVolume = function () {
  57228. return this._volume;
  57229. };
  57230. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  57231. var _this = this;
  57232. if (this._connectedMesh && this._registerFunc) {
  57233. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  57234. this._registerFunc = null;
  57235. }
  57236. this._connectedMesh = meshToConnectTo;
  57237. if (!this.spatialSound) {
  57238. this.spatialSound = true;
  57239. this._createSpatialParameters();
  57240. if (this.isPlaying && this.loop) {
  57241. this.stop();
  57242. this.play();
  57243. }
  57244. }
  57245. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  57246. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  57247. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  57248. };
  57249. Sound.prototype.detachFromMesh = function () {
  57250. if (this._connectedMesh && this._registerFunc) {
  57251. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  57252. this._registerFunc = null;
  57253. this._connectedMesh = null;
  57254. }
  57255. };
  57256. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  57257. if (!node.getBoundingInfo) {
  57258. return;
  57259. }
  57260. var mesh = node;
  57261. var boundingInfo = mesh.getBoundingInfo();
  57262. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  57263. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  57264. this._updateDirection();
  57265. }
  57266. };
  57267. Sound.prototype.clone = function () {
  57268. var _this = this;
  57269. if (!this._streaming) {
  57270. var setBufferAndRun = function () {
  57271. if (_this._isReadyToPlay) {
  57272. clonedSound._audioBuffer = _this.getAudioBuffer();
  57273. clonedSound._isReadyToPlay = true;
  57274. if (clonedSound.autoplay) {
  57275. clonedSound.play();
  57276. }
  57277. }
  57278. else {
  57279. window.setTimeout(setBufferAndRun, 300);
  57280. }
  57281. };
  57282. var currentOptions = {
  57283. autoplay: this.autoplay, loop: this.loop,
  57284. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  57285. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  57286. refDistance: this.refDistance, distanceModel: this.distanceModel
  57287. };
  57288. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  57289. if (this.useCustomAttenuation) {
  57290. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  57291. }
  57292. clonedSound.setPosition(this._position);
  57293. clonedSound.setPlaybackRate(this._playbackRate);
  57294. setBufferAndRun();
  57295. return clonedSound;
  57296. }
  57297. else {
  57298. return null;
  57299. }
  57300. };
  57301. Sound.prototype.getAudioBuffer = function () {
  57302. return this._audioBuffer;
  57303. };
  57304. Sound.prototype.serialize = function () {
  57305. var serializationObject = {
  57306. name: this.name,
  57307. url: this.name,
  57308. autoplay: this.autoplay,
  57309. loop: this.loop,
  57310. volume: this._volume,
  57311. spatialSound: this.spatialSound,
  57312. maxDistance: this.maxDistance,
  57313. rolloffFactor: this.rolloffFactor,
  57314. refDistance: this.refDistance,
  57315. distanceModel: this.distanceModel,
  57316. playbackRate: this._playbackRate,
  57317. panningModel: this._panningModel,
  57318. soundTrackId: this.soundTrackId
  57319. };
  57320. if (this.spatialSound) {
  57321. if (this._connectedMesh)
  57322. serializationObject.connectedMeshId = this._connectedMesh.id;
  57323. serializationObject.position = this._position.asArray();
  57324. serializationObject.refDistance = this.refDistance;
  57325. serializationObject.distanceModel = this.distanceModel;
  57326. serializationObject.isDirectional = this._isDirectional;
  57327. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  57328. serializationObject.coneInnerAngle = this._coneInnerAngle;
  57329. serializationObject.coneOuterAngle = this._coneOuterAngle;
  57330. serializationObject.coneOuterGain = this._coneOuterGain;
  57331. }
  57332. return serializationObject;
  57333. };
  57334. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  57335. var soundName = parsedSound.name;
  57336. var soundUrl;
  57337. if (parsedSound.url) {
  57338. soundUrl = rootUrl + parsedSound.url;
  57339. }
  57340. else {
  57341. soundUrl = rootUrl + soundName;
  57342. }
  57343. var options = {
  57344. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  57345. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  57346. rolloffFactor: parsedSound.rolloffFactor,
  57347. refDistance: parsedSound.refDistance,
  57348. distanceModel: parsedSound.distanceModel,
  57349. playbackRate: parsedSound.playbackRate
  57350. };
  57351. var newSound;
  57352. if (!sourceSound) {
  57353. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  57354. scene._addPendingData(newSound);
  57355. }
  57356. else {
  57357. var setBufferAndRun = function () {
  57358. if (sourceSound._isReadyToPlay) {
  57359. newSound._audioBuffer = sourceSound.getAudioBuffer();
  57360. newSound._isReadyToPlay = true;
  57361. if (newSound.autoplay) {
  57362. newSound.play();
  57363. }
  57364. }
  57365. else {
  57366. window.setTimeout(setBufferAndRun, 300);
  57367. }
  57368. };
  57369. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  57370. setBufferAndRun();
  57371. }
  57372. if (parsedSound.position) {
  57373. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  57374. newSound.setPosition(soundPosition);
  57375. }
  57376. if (parsedSound.isDirectional) {
  57377. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  57378. if (parsedSound.localDirectionToMesh) {
  57379. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  57380. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  57381. }
  57382. }
  57383. if (parsedSound.connectedMeshId) {
  57384. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  57385. if (connectedMesh) {
  57386. newSound.attachToMesh(connectedMesh);
  57387. }
  57388. }
  57389. return newSound;
  57390. };
  57391. return Sound;
  57392. }());
  57393. BABYLON.Sound = Sound;
  57394. })(BABYLON || (BABYLON = {}));
  57395. //# sourceMappingURL=babylon.sound.js.map
  57396. var BABYLON;
  57397. (function (BABYLON) {
  57398. var SoundTrack = /** @class */ (function () {
  57399. function SoundTrack(scene, options) {
  57400. this.id = -1;
  57401. this._isMainTrack = false;
  57402. this._isInitialized = false;
  57403. this._scene = scene;
  57404. this.soundCollection = new Array();
  57405. this._options = options;
  57406. if (!this._isMainTrack) {
  57407. this._scene.soundTracks.push(this);
  57408. this.id = this._scene.soundTracks.length - 1;
  57409. }
  57410. }
  57411. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  57412. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  57413. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  57414. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  57415. if (this._options) {
  57416. if (this._options.volume) {
  57417. this._outputAudioNode.gain.value = this._options.volume;
  57418. }
  57419. if (this._options.mainTrack) {
  57420. this._isMainTrack = this._options.mainTrack;
  57421. }
  57422. }
  57423. this._isInitialized = true;
  57424. }
  57425. };
  57426. SoundTrack.prototype.dispose = function () {
  57427. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  57428. if (this._connectedAnalyser) {
  57429. this._connectedAnalyser.stopDebugCanvas();
  57430. }
  57431. while (this.soundCollection.length) {
  57432. this.soundCollection[0].dispose();
  57433. }
  57434. if (this._outputAudioNode) {
  57435. this._outputAudioNode.disconnect();
  57436. }
  57437. this._outputAudioNode = null;
  57438. }
  57439. };
  57440. SoundTrack.prototype.AddSound = function (sound) {
  57441. if (!this._isInitialized) {
  57442. this._initializeSoundTrackAudioGraph();
  57443. }
  57444. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  57445. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  57446. }
  57447. if (sound.soundTrackId) {
  57448. if (sound.soundTrackId === -1) {
  57449. this._scene.mainSoundTrack.RemoveSound(sound);
  57450. }
  57451. else {
  57452. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  57453. }
  57454. }
  57455. this.soundCollection.push(sound);
  57456. sound.soundTrackId = this.id;
  57457. };
  57458. SoundTrack.prototype.RemoveSound = function (sound) {
  57459. var index = this.soundCollection.indexOf(sound);
  57460. if (index !== -1) {
  57461. this.soundCollection.splice(index, 1);
  57462. }
  57463. };
  57464. SoundTrack.prototype.setVolume = function (newVolume) {
  57465. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  57466. this._outputAudioNode.gain.value = newVolume;
  57467. }
  57468. };
  57469. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  57470. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  57471. for (var i = 0; i < this.soundCollection.length; i++) {
  57472. this.soundCollection[i].switchPanningModelToHRTF();
  57473. }
  57474. }
  57475. };
  57476. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  57477. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  57478. for (var i = 0; i < this.soundCollection.length; i++) {
  57479. this.soundCollection[i].switchPanningModelToEqualPower();
  57480. }
  57481. }
  57482. };
  57483. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  57484. if (this._connectedAnalyser) {
  57485. this._connectedAnalyser.stopDebugCanvas();
  57486. }
  57487. this._connectedAnalyser = analyser;
  57488. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  57489. this._outputAudioNode.disconnect();
  57490. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  57491. }
  57492. };
  57493. return SoundTrack;
  57494. }());
  57495. BABYLON.SoundTrack = SoundTrack;
  57496. })(BABYLON || (BABYLON = {}));
  57497. //# sourceMappingURL=babylon.soundtrack.js.map
  57498. var BABYLON;
  57499. (function (BABYLON) {
  57500. var Analyser = /** @class */ (function () {
  57501. function Analyser(scene) {
  57502. this.SMOOTHING = 0.75;
  57503. this.FFT_SIZE = 512;
  57504. this.BARGRAPHAMPLITUDE = 256;
  57505. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  57506. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  57507. this._scene = scene;
  57508. this._audioEngine = BABYLON.Engine.audioEngine;
  57509. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  57510. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  57511. this._webAudioAnalyser.minDecibels = -140;
  57512. this._webAudioAnalyser.maxDecibels = 0;
  57513. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  57514. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  57515. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  57516. }
  57517. }
  57518. Analyser.prototype.getFrequencyBinCount = function () {
  57519. if (this._audioEngine.canUseWebAudio) {
  57520. return this._webAudioAnalyser.frequencyBinCount;
  57521. }
  57522. else {
  57523. return 0;
  57524. }
  57525. };
  57526. Analyser.prototype.getByteFrequencyData = function () {
  57527. if (this._audioEngine.canUseWebAudio) {
  57528. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  57529. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  57530. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  57531. }
  57532. return this._byteFreqs;
  57533. };
  57534. Analyser.prototype.getByteTimeDomainData = function () {
  57535. if (this._audioEngine.canUseWebAudio) {
  57536. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  57537. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  57538. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  57539. }
  57540. return this._byteTime;
  57541. };
  57542. Analyser.prototype.getFloatFrequencyData = function () {
  57543. if (this._audioEngine.canUseWebAudio) {
  57544. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  57545. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  57546. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  57547. }
  57548. return this._floatFreqs;
  57549. };
  57550. Analyser.prototype.drawDebugCanvas = function () {
  57551. var _this = this;
  57552. if (this._audioEngine.canUseWebAudio) {
  57553. if (!this._debugCanvas) {
  57554. this._debugCanvas = document.createElement("canvas");
  57555. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  57556. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  57557. this._debugCanvas.style.position = "absolute";
  57558. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  57559. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  57560. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  57561. document.body.appendChild(this._debugCanvas);
  57562. this._registerFunc = function () {
  57563. _this.drawDebugCanvas();
  57564. };
  57565. this._scene.registerBeforeRender(this._registerFunc);
  57566. }
  57567. if (this._registerFunc && this._debugCanvasContext) {
  57568. var workingArray = this.getByteFrequencyData();
  57569. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  57570. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  57571. // Draw the frequency domain chart.
  57572. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  57573. var value = workingArray[i];
  57574. var percent = value / this.BARGRAPHAMPLITUDE;
  57575. var height = this.DEBUGCANVASSIZE.height * percent;
  57576. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  57577. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  57578. var hue = i / this.getFrequencyBinCount() * 360;
  57579. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  57580. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  57581. }
  57582. }
  57583. }
  57584. };
  57585. Analyser.prototype.stopDebugCanvas = function () {
  57586. if (this._debugCanvas) {
  57587. if (this._registerFunc) {
  57588. this._scene.unregisterBeforeRender(this._registerFunc);
  57589. this._registerFunc = null;
  57590. }
  57591. document.body.removeChild(this._debugCanvas);
  57592. this._debugCanvas = null;
  57593. this._debugCanvasContext = null;
  57594. }
  57595. };
  57596. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  57597. if (this._audioEngine.canUseWebAudio) {
  57598. inputAudioNode.connect(this._webAudioAnalyser);
  57599. this._webAudioAnalyser.connect(outputAudioNode);
  57600. }
  57601. };
  57602. Analyser.prototype.dispose = function () {
  57603. if (this._audioEngine.canUseWebAudio) {
  57604. this._webAudioAnalyser.disconnect();
  57605. }
  57606. };
  57607. return Analyser;
  57608. }());
  57609. BABYLON.Analyser = Analyser;
  57610. })(BABYLON || (BABYLON = {}));
  57611. //# sourceMappingURL=babylon.analyser.js.map
  57612. var BABYLON;
  57613. (function (BABYLON) {
  57614. var CubeTexture = /** @class */ (function (_super) {
  57615. __extends(CubeTexture, _super);
  57616. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  57617. if (extensions === void 0) { extensions = null; }
  57618. if (noMipmap === void 0) { noMipmap = false; }
  57619. if (files === void 0) { files = null; }
  57620. if (onLoad === void 0) { onLoad = null; }
  57621. if (onError === void 0) { onError = null; }
  57622. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  57623. if (prefiltered === void 0) { prefiltered = false; }
  57624. if (forcedExtension === void 0) { forcedExtension = null; }
  57625. var _this = _super.call(this, scene) || this;
  57626. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  57627. /**
  57628. * Gets or sets the center of the bounding box associated with the cube texture
  57629. * It must define where the camera used to render the texture was set
  57630. */
  57631. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  57632. _this.name = rootUrl;
  57633. _this.url = rootUrl;
  57634. _this._noMipmap = noMipmap;
  57635. _this.hasAlpha = false;
  57636. _this._format = format;
  57637. _this._prefiltered = prefiltered;
  57638. _this.isCube = true;
  57639. _this._textureMatrix = BABYLON.Matrix.Identity();
  57640. if (prefiltered) {
  57641. _this.gammaSpace = false;
  57642. }
  57643. if (!rootUrl && !files) {
  57644. return _this;
  57645. }
  57646. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  57647. var lastDot = rootUrl.lastIndexOf(".");
  57648. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  57649. var isDDS = (extension === ".dds");
  57650. if (!files) {
  57651. if (!isDDS && !extensions) {
  57652. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  57653. }
  57654. files = [];
  57655. if (extensions) {
  57656. for (var index = 0; index < extensions.length; index++) {
  57657. files.push(rootUrl + extensions[index]);
  57658. }
  57659. }
  57660. }
  57661. _this._files = files;
  57662. if (!_this._texture) {
  57663. if (!scene.useDelayedTextureLoading) {
  57664. if (prefiltered) {
  57665. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  57666. }
  57667. else {
  57668. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  57669. }
  57670. }
  57671. else {
  57672. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  57673. }
  57674. }
  57675. else if (onLoad) {
  57676. if (_this._texture.isReady) {
  57677. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  57678. }
  57679. else {
  57680. _this._texture.onLoadedObservable.add(onLoad);
  57681. }
  57682. }
  57683. return _this;
  57684. }
  57685. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  57686. get: function () {
  57687. return this._boundingBoxSize;
  57688. },
  57689. /**
  57690. * Gets or sets the size of the bounding box associated with the cube texture
  57691. * When defined, the cubemap will switch to local mode
  57692. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  57693. * @example https://www.babylonjs-playground.com/#RNASML
  57694. */
  57695. set: function (value) {
  57696. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  57697. return;
  57698. }
  57699. this._boundingBoxSize = value;
  57700. var scene = this.getScene();
  57701. if (scene) {
  57702. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  57703. }
  57704. },
  57705. enumerable: true,
  57706. configurable: true
  57707. });
  57708. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  57709. var rootUrlKey = "";
  57710. files.forEach(function (url) { return rootUrlKey += url; });
  57711. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  57712. };
  57713. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  57714. if (forcedExtension === void 0) { forcedExtension = null; }
  57715. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  57716. };
  57717. // Methods
  57718. CubeTexture.prototype.delayLoad = function () {
  57719. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  57720. return;
  57721. }
  57722. var scene = this.getScene();
  57723. if (!scene) {
  57724. return;
  57725. }
  57726. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  57727. this._texture = this._getFromCache(this.url, this._noMipmap);
  57728. if (!this._texture) {
  57729. if (this._prefiltered) {
  57730. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  57731. }
  57732. else {
  57733. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  57734. }
  57735. }
  57736. };
  57737. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  57738. return this._textureMatrix;
  57739. };
  57740. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  57741. this._textureMatrix = value;
  57742. };
  57743. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  57744. var texture = BABYLON.SerializationHelper.Parse(function () {
  57745. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  57746. }, parsedTexture, scene);
  57747. // Local Cubemaps
  57748. if (parsedTexture.boundingBoxPosition) {
  57749. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  57750. }
  57751. if (parsedTexture.boundingBoxSize) {
  57752. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  57753. }
  57754. // Animations
  57755. if (parsedTexture.animations) {
  57756. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  57757. var parsedAnimation = parsedTexture.animations[animationIndex];
  57758. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  57759. }
  57760. }
  57761. return texture;
  57762. };
  57763. CubeTexture.prototype.clone = function () {
  57764. var _this = this;
  57765. return BABYLON.SerializationHelper.Clone(function () {
  57766. var scene = _this.getScene();
  57767. if (!scene) {
  57768. return _this;
  57769. }
  57770. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  57771. }, this);
  57772. };
  57773. return CubeTexture;
  57774. }(BABYLON.BaseTexture));
  57775. BABYLON.CubeTexture = CubeTexture;
  57776. })(BABYLON || (BABYLON = {}));
  57777. //# sourceMappingURL=babylon.cubeTexture.js.map
  57778. var BABYLON;
  57779. (function (BABYLON) {
  57780. var RenderTargetTexture = /** @class */ (function (_super) {
  57781. __extends(RenderTargetTexture, _super);
  57782. /**
  57783. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  57784. * or used a shadow, depth texture...
  57785. * @param name The friendly name of the texture
  57786. * @param size The size of the RTT (number if square, or {with: number, height:number} or {ratio:} to define a ratio from the main scene)
  57787. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  57788. * @param generateMipMaps True if mip maps need to be generated after render.
  57789. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  57790. * @param type The type of the buffer in the RTT (int, half float, float...)
  57791. * @param isCube True if a cube texture needs to be created
  57792. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  57793. * @param generateDepthBuffer True to generate a depth buffer
  57794. * @param generateStencilBuffer True to generate a stencil buffer
  57795. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  57796. */
  57797. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  57798. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  57799. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  57800. if (isCube === void 0) { isCube = false; }
  57801. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  57802. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  57803. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  57804. if (isMulti === void 0) { isMulti = false; }
  57805. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  57806. _this.isCube = isCube;
  57807. /**
  57808. * Use this list to define the list of mesh you want to render.
  57809. */
  57810. _this.renderList = new Array();
  57811. _this.renderParticles = true;
  57812. _this.renderSprites = false;
  57813. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  57814. _this.ignoreCameraViewport = false;
  57815. // Events
  57816. /**
  57817. * An event triggered when the texture is unbind.
  57818. * @type {BABYLON.Observable}
  57819. */
  57820. _this.onBeforeBindObservable = new BABYLON.Observable();
  57821. /**
  57822. * An event triggered when the texture is unbind.
  57823. * @type {BABYLON.Observable}
  57824. */
  57825. _this.onAfterUnbindObservable = new BABYLON.Observable();
  57826. /**
  57827. * An event triggered before rendering the texture
  57828. * @type {BABYLON.Observable}
  57829. */
  57830. _this.onBeforeRenderObservable = new BABYLON.Observable();
  57831. /**
  57832. * An event triggered after rendering the texture
  57833. * @type {BABYLON.Observable}
  57834. */
  57835. _this.onAfterRenderObservable = new BABYLON.Observable();
  57836. /**
  57837. * An event triggered after the texture clear
  57838. * @type {BABYLON.Observable}
  57839. */
  57840. _this.onClearObservable = new BABYLON.Observable();
  57841. _this._currentRefreshId = -1;
  57842. _this._refreshRate = 1;
  57843. _this._samples = 1;
  57844. /**
  57845. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  57846. * It must define where the camera used to render the texture is set
  57847. */
  57848. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  57849. scene = _this.getScene();
  57850. if (!scene) {
  57851. return _this;
  57852. }
  57853. _this._engine = scene.getEngine();
  57854. _this.name = name;
  57855. _this.isRenderTarget = true;
  57856. _this._initialSizeParameter = size;
  57857. _this._processSizeParameter(size);
  57858. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  57859. });
  57860. _this._generateMipMaps = generateMipMaps ? true : false;
  57861. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  57862. // Rendering groups
  57863. _this._renderingManager = new BABYLON.RenderingManager(scene);
  57864. if (isMulti) {
  57865. return _this;
  57866. }
  57867. _this._renderTargetOptions = {
  57868. generateMipMaps: generateMipMaps,
  57869. type: type,
  57870. samplingMode: samplingMode,
  57871. generateDepthBuffer: generateDepthBuffer,
  57872. generateStencilBuffer: generateStencilBuffer
  57873. };
  57874. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  57875. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57876. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57877. }
  57878. if (isCube) {
  57879. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  57880. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  57881. _this._textureMatrix = BABYLON.Matrix.Identity();
  57882. }
  57883. else {
  57884. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  57885. }
  57886. return _this;
  57887. }
  57888. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  57889. get: function () {
  57890. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  57891. },
  57892. enumerable: true,
  57893. configurable: true
  57894. });
  57895. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  57896. get: function () {
  57897. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  57898. },
  57899. enumerable: true,
  57900. configurable: true
  57901. });
  57902. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  57903. get: function () {
  57904. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  57905. },
  57906. enumerable: true,
  57907. configurable: true
  57908. });
  57909. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  57910. set: function (callback) {
  57911. if (this._onAfterUnbindObserver) {
  57912. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  57913. }
  57914. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  57915. },
  57916. enumerable: true,
  57917. configurable: true
  57918. });
  57919. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  57920. set: function (callback) {
  57921. if (this._onBeforeRenderObserver) {
  57922. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  57923. }
  57924. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  57925. },
  57926. enumerable: true,
  57927. configurable: true
  57928. });
  57929. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  57930. set: function (callback) {
  57931. if (this._onAfterRenderObserver) {
  57932. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  57933. }
  57934. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  57935. },
  57936. enumerable: true,
  57937. configurable: true
  57938. });
  57939. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  57940. set: function (callback) {
  57941. if (this._onClearObserver) {
  57942. this.onClearObservable.remove(this._onClearObserver);
  57943. }
  57944. this._onClearObserver = this.onClearObservable.add(callback);
  57945. },
  57946. enumerable: true,
  57947. configurable: true
  57948. });
  57949. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  57950. get: function () {
  57951. return this._renderTargetOptions;
  57952. },
  57953. enumerable: true,
  57954. configurable: true
  57955. });
  57956. RenderTargetTexture.prototype._onRatioRescale = function () {
  57957. if (this._sizeRatio) {
  57958. this.resize(this._initialSizeParameter);
  57959. }
  57960. };
  57961. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  57962. get: function () {
  57963. return this._boundingBoxSize;
  57964. },
  57965. /**
  57966. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  57967. * When defined, the cubemap will switch to local mode
  57968. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  57969. * @example https://www.babylonjs-playground.com/#RNASML
  57970. */
  57971. set: function (value) {
  57972. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  57973. return;
  57974. }
  57975. this._boundingBoxSize = value;
  57976. var scene = this.getScene();
  57977. if (scene) {
  57978. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  57979. }
  57980. },
  57981. enumerable: true,
  57982. configurable: true
  57983. });
  57984. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  57985. if (size.ratio) {
  57986. this._sizeRatio = size.ratio;
  57987. this._size = {
  57988. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  57989. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  57990. };
  57991. }
  57992. else {
  57993. this._size = size;
  57994. }
  57995. };
  57996. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  57997. get: function () {
  57998. return this._samples;
  57999. },
  58000. set: function (value) {
  58001. if (this._samples === value) {
  58002. return;
  58003. }
  58004. var scene = this.getScene();
  58005. if (!scene) {
  58006. return;
  58007. }
  58008. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  58009. },
  58010. enumerable: true,
  58011. configurable: true
  58012. });
  58013. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  58014. this._currentRefreshId = -1;
  58015. };
  58016. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  58017. get: function () {
  58018. return this._refreshRate;
  58019. },
  58020. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  58021. set: function (value) {
  58022. this._refreshRate = value;
  58023. this.resetRefreshCounter();
  58024. },
  58025. enumerable: true,
  58026. configurable: true
  58027. });
  58028. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  58029. if (!this._postProcessManager) {
  58030. var scene = this.getScene();
  58031. if (!scene) {
  58032. return;
  58033. }
  58034. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  58035. this._postProcesses = new Array();
  58036. }
  58037. this._postProcesses.push(postProcess);
  58038. this._postProcesses[0].autoClear = false;
  58039. };
  58040. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  58041. if (!this._postProcesses) {
  58042. return;
  58043. }
  58044. if (dispose) {
  58045. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  58046. var postProcess = _a[_i];
  58047. postProcess.dispose();
  58048. }
  58049. }
  58050. this._postProcesses = [];
  58051. };
  58052. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  58053. if (!this._postProcesses) {
  58054. return;
  58055. }
  58056. var index = this._postProcesses.indexOf(postProcess);
  58057. if (index === -1) {
  58058. return;
  58059. }
  58060. this._postProcesses.splice(index, 1);
  58061. if (this._postProcesses.length > 0) {
  58062. this._postProcesses[0].autoClear = false;
  58063. }
  58064. };
  58065. RenderTargetTexture.prototype._shouldRender = function () {
  58066. if (this._currentRefreshId === -1) {
  58067. this._currentRefreshId = 1;
  58068. return true;
  58069. }
  58070. if (this.refreshRate === this._currentRefreshId) {
  58071. this._currentRefreshId = 1;
  58072. return true;
  58073. }
  58074. this._currentRefreshId++;
  58075. return false;
  58076. };
  58077. RenderTargetTexture.prototype.getRenderSize = function () {
  58078. if (this._size.width) {
  58079. return this._size.width;
  58080. }
  58081. return this._size;
  58082. };
  58083. RenderTargetTexture.prototype.getRenderWidth = function () {
  58084. if (this._size.width) {
  58085. return this._size.width;
  58086. }
  58087. return this._size;
  58088. };
  58089. RenderTargetTexture.prototype.getRenderHeight = function () {
  58090. if (this._size.width) {
  58091. return this._size.height;
  58092. }
  58093. return this._size;
  58094. };
  58095. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  58096. get: function () {
  58097. return true;
  58098. },
  58099. enumerable: true,
  58100. configurable: true
  58101. });
  58102. RenderTargetTexture.prototype.scale = function (ratio) {
  58103. var newSize = this.getRenderSize() * ratio;
  58104. this.resize(newSize);
  58105. };
  58106. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  58107. if (this.isCube) {
  58108. return this._textureMatrix;
  58109. }
  58110. return _super.prototype.getReflectionTextureMatrix.call(this);
  58111. };
  58112. RenderTargetTexture.prototype.resize = function (size) {
  58113. this.releaseInternalTexture();
  58114. var scene = this.getScene();
  58115. if (!scene) {
  58116. return;
  58117. }
  58118. this._processSizeParameter(size);
  58119. if (this.isCube) {
  58120. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  58121. }
  58122. else {
  58123. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  58124. }
  58125. };
  58126. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  58127. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  58128. if (dumpForDebug === void 0) { dumpForDebug = false; }
  58129. var scene = this.getScene();
  58130. if (!scene) {
  58131. return;
  58132. }
  58133. var engine = scene.getEngine();
  58134. if (this.useCameraPostProcesses !== undefined) {
  58135. useCameraPostProcess = this.useCameraPostProcesses;
  58136. }
  58137. if (this._waitingRenderList) {
  58138. this.renderList = [];
  58139. for (var index = 0; index < this._waitingRenderList.length; index++) {
  58140. var id = this._waitingRenderList[index];
  58141. var mesh_1 = scene.getMeshByID(id);
  58142. if (mesh_1) {
  58143. this.renderList.push(mesh_1);
  58144. }
  58145. }
  58146. delete this._waitingRenderList;
  58147. }
  58148. // Is predicate defined?
  58149. if (this.renderListPredicate) {
  58150. if (this.renderList) {
  58151. this.renderList.splice(0); // Clear previous renderList
  58152. }
  58153. else {
  58154. this.renderList = [];
  58155. }
  58156. var scene = this.getScene();
  58157. if (!scene) {
  58158. return;
  58159. }
  58160. var sceneMeshes = scene.meshes;
  58161. for (var index = 0; index < sceneMeshes.length; index++) {
  58162. var mesh = sceneMeshes[index];
  58163. if (this.renderListPredicate(mesh)) {
  58164. this.renderList.push(mesh);
  58165. }
  58166. }
  58167. }
  58168. this.onBeforeBindObservable.notifyObservers(this);
  58169. // Set custom projection.
  58170. // Needs to be before binding to prevent changing the aspect ratio.
  58171. var camera;
  58172. if (this.activeCamera) {
  58173. camera = this.activeCamera;
  58174. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  58175. if (this.activeCamera !== scene.activeCamera) {
  58176. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  58177. }
  58178. }
  58179. else {
  58180. camera = scene.activeCamera;
  58181. if (camera) {
  58182. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  58183. }
  58184. }
  58185. // Prepare renderingManager
  58186. this._renderingManager.reset();
  58187. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  58188. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  58189. var sceneRenderId = scene.getRenderId();
  58190. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  58191. var mesh = currentRenderList[meshIndex];
  58192. if (mesh) {
  58193. if (!mesh.isReady()) {
  58194. // Reset _currentRefreshId
  58195. this.resetRefreshCounter();
  58196. continue;
  58197. }
  58198. mesh._preActivateForIntermediateRendering(sceneRenderId);
  58199. var isMasked = void 0;
  58200. if (!this.renderList && camera) {
  58201. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  58202. }
  58203. else {
  58204. isMasked = false;
  58205. }
  58206. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  58207. mesh._activate(sceneRenderId);
  58208. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  58209. var subMesh = mesh.subMeshes[subIndex];
  58210. scene._activeIndices.addCount(subMesh.indexCount, false);
  58211. this._renderingManager.dispatch(subMesh, mesh);
  58212. }
  58213. }
  58214. }
  58215. }
  58216. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  58217. var particleSystem = scene.particleSystems[particleIndex];
  58218. var emitter = particleSystem.emitter;
  58219. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  58220. continue;
  58221. }
  58222. if (currentRenderList.indexOf(emitter) >= 0) {
  58223. this._renderingManager.dispatchParticles(particleSystem);
  58224. }
  58225. }
  58226. if (this.isCube) {
  58227. for (var face = 0; face < 6; face++) {
  58228. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  58229. scene.incrementRenderId();
  58230. scene.resetCachedMaterial();
  58231. }
  58232. }
  58233. else {
  58234. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  58235. }
  58236. this.onAfterUnbindObservable.notifyObservers(this);
  58237. if (scene.activeCamera) {
  58238. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  58239. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  58240. }
  58241. engine.setViewport(scene.activeCamera.viewport);
  58242. }
  58243. scene.resetCachedMaterial();
  58244. };
  58245. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  58246. var minimum = 128;
  58247. var x = renderDimension * scale;
  58248. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  58249. // Ensure we don't exceed the render dimension (while staying POT)
  58250. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  58251. };
  58252. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  58253. var _this = this;
  58254. if (!this._texture) {
  58255. return;
  58256. }
  58257. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  58258. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  58259. });
  58260. };
  58261. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  58262. var scene = this.getScene();
  58263. if (!scene) {
  58264. return;
  58265. }
  58266. var engine = scene.getEngine();
  58267. if (!this._texture) {
  58268. return;
  58269. }
  58270. // Bind
  58271. if (this._postProcessManager) {
  58272. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  58273. }
  58274. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  58275. if (this._texture) {
  58276. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  58277. }
  58278. }
  58279. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  58280. // Clear
  58281. if (this.onClearObservable.hasObservers()) {
  58282. this.onClearObservable.notifyObservers(engine);
  58283. }
  58284. else {
  58285. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  58286. }
  58287. if (!this._doNotChangeAspectRatio) {
  58288. scene.updateTransformMatrix(true);
  58289. }
  58290. // Render
  58291. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  58292. if (this._postProcessManager) {
  58293. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  58294. }
  58295. else if (useCameraPostProcess) {
  58296. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  58297. }
  58298. if (!this._doNotChangeAspectRatio) {
  58299. scene.updateTransformMatrix(true);
  58300. }
  58301. // Dump ?
  58302. if (dumpForDebug) {
  58303. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  58304. }
  58305. // Unbind
  58306. if (!this.isCube || faceIndex === 5) {
  58307. if (this.isCube) {
  58308. if (faceIndex === 5) {
  58309. engine.generateMipMapsForCubemap(this._texture);
  58310. }
  58311. }
  58312. this.unbindFrameBuffer(engine, faceIndex);
  58313. }
  58314. else {
  58315. this.onAfterRenderObservable.notifyObservers(faceIndex);
  58316. }
  58317. };
  58318. /**
  58319. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  58320. * This allowed control for front to back rendering or reversly depending of the special needs.
  58321. *
  58322. * @param renderingGroupId The rendering group id corresponding to its index
  58323. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  58324. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  58325. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  58326. */
  58327. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  58328. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  58329. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  58330. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  58331. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  58332. };
  58333. /**
  58334. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  58335. *
  58336. * @param renderingGroupId The rendering group id corresponding to its index
  58337. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  58338. */
  58339. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  58340. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  58341. };
  58342. RenderTargetTexture.prototype.clone = function () {
  58343. var textureSize = this.getSize();
  58344. 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);
  58345. // Base texture
  58346. newTexture.hasAlpha = this.hasAlpha;
  58347. newTexture.level = this.level;
  58348. // RenderTarget Texture
  58349. newTexture.coordinatesMode = this.coordinatesMode;
  58350. if (this.renderList) {
  58351. newTexture.renderList = this.renderList.slice(0);
  58352. }
  58353. return newTexture;
  58354. };
  58355. RenderTargetTexture.prototype.serialize = function () {
  58356. if (!this.name) {
  58357. return null;
  58358. }
  58359. var serializationObject = _super.prototype.serialize.call(this);
  58360. serializationObject.renderTargetSize = this.getRenderSize();
  58361. serializationObject.renderList = [];
  58362. if (this.renderList) {
  58363. for (var index = 0; index < this.renderList.length; index++) {
  58364. serializationObject.renderList.push(this.renderList[index].id);
  58365. }
  58366. }
  58367. return serializationObject;
  58368. };
  58369. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  58370. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  58371. var objBuffer = this.getInternalTexture();
  58372. var scene = this.getScene();
  58373. if (objBuffer && scene) {
  58374. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  58375. }
  58376. };
  58377. RenderTargetTexture.prototype.dispose = function () {
  58378. if (this._postProcessManager) {
  58379. this._postProcessManager.dispose();
  58380. this._postProcessManager = null;
  58381. }
  58382. this.clearPostProcesses(true);
  58383. if (this._resizeObserver) {
  58384. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  58385. this._resizeObserver = null;
  58386. }
  58387. this.renderList = null;
  58388. // Remove from custom render targets
  58389. var scene = this.getScene();
  58390. if (!scene) {
  58391. return;
  58392. }
  58393. var index = scene.customRenderTargets.indexOf(this);
  58394. if (index >= 0) {
  58395. scene.customRenderTargets.splice(index, 1);
  58396. }
  58397. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  58398. var camera = _a[_i];
  58399. index = camera.customRenderTargets.indexOf(this);
  58400. if (index >= 0) {
  58401. camera.customRenderTargets.splice(index, 1);
  58402. }
  58403. }
  58404. _super.prototype.dispose.call(this);
  58405. };
  58406. RenderTargetTexture.prototype._rebuild = function () {
  58407. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  58408. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  58409. }
  58410. if (this._postProcessManager) {
  58411. this._postProcessManager._rebuild();
  58412. }
  58413. };
  58414. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  58415. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  58416. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  58417. return RenderTargetTexture;
  58418. }(BABYLON.Texture));
  58419. BABYLON.RenderTargetTexture = RenderTargetTexture;
  58420. })(BABYLON || (BABYLON = {}));
  58421. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  58422. var BABYLON;
  58423. (function (BABYLON) {
  58424. ;
  58425. var MultiRenderTarget = /** @class */ (function (_super) {
  58426. __extends(MultiRenderTarget, _super);
  58427. function MultiRenderTarget(name, size, count, scene, options) {
  58428. var _this = this;
  58429. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  58430. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  58431. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  58432. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  58433. _this._engine = scene.getEngine();
  58434. if (!_this.isSupported) {
  58435. _this.dispose();
  58436. return;
  58437. }
  58438. var types = [];
  58439. var samplingModes = [];
  58440. for (var i = 0; i < count; i++) {
  58441. if (options && options.types && options.types[i] !== undefined) {
  58442. types.push(options.types[i]);
  58443. }
  58444. else {
  58445. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  58446. }
  58447. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  58448. samplingModes.push(options.samplingModes[i]);
  58449. }
  58450. else {
  58451. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  58452. }
  58453. }
  58454. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  58455. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  58456. _this._size = size;
  58457. _this._multiRenderTargetOptions = {
  58458. samplingModes: samplingModes,
  58459. generateMipMaps: generateMipMaps,
  58460. generateDepthBuffer: generateDepthBuffer,
  58461. generateStencilBuffer: generateStencilBuffer,
  58462. generateDepthTexture: generateDepthTexture,
  58463. types: types,
  58464. textureCount: count
  58465. };
  58466. _this._createInternalTextures();
  58467. _this._createTextures();
  58468. return _this;
  58469. }
  58470. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  58471. get: function () {
  58472. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  58473. },
  58474. enumerable: true,
  58475. configurable: true
  58476. });
  58477. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  58478. get: function () {
  58479. return this._textures;
  58480. },
  58481. enumerable: true,
  58482. configurable: true
  58483. });
  58484. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  58485. get: function () {
  58486. return this._textures[this._textures.length - 1];
  58487. },
  58488. enumerable: true,
  58489. configurable: true
  58490. });
  58491. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  58492. set: function (wrap) {
  58493. if (this._textures) {
  58494. for (var i = 0; i < this._textures.length; i++) {
  58495. this._textures[i].wrapU = wrap;
  58496. }
  58497. }
  58498. },
  58499. enumerable: true,
  58500. configurable: true
  58501. });
  58502. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  58503. set: function (wrap) {
  58504. if (this._textures) {
  58505. for (var i = 0; i < this._textures.length; i++) {
  58506. this._textures[i].wrapV = wrap;
  58507. }
  58508. }
  58509. },
  58510. enumerable: true,
  58511. configurable: true
  58512. });
  58513. MultiRenderTarget.prototype._rebuild = function () {
  58514. this.releaseInternalTextures();
  58515. this._createInternalTextures();
  58516. for (var i = 0; i < this._internalTextures.length; i++) {
  58517. var texture = this._textures[i];
  58518. texture._texture = this._internalTextures[i];
  58519. }
  58520. // Keeps references to frame buffer and stencil/depth buffer
  58521. this._texture = this._internalTextures[0];
  58522. };
  58523. MultiRenderTarget.prototype._createInternalTextures = function () {
  58524. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  58525. };
  58526. MultiRenderTarget.prototype._createTextures = function () {
  58527. this._textures = [];
  58528. for (var i = 0; i < this._internalTextures.length; i++) {
  58529. var texture = new BABYLON.Texture(null, this.getScene());
  58530. texture._texture = this._internalTextures[i];
  58531. this._textures.push(texture);
  58532. }
  58533. // Keeps references to frame buffer and stencil/depth buffer
  58534. this._texture = this._internalTextures[0];
  58535. };
  58536. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  58537. get: function () {
  58538. return this._samples;
  58539. },
  58540. set: function (value) {
  58541. if (this._samples === value) {
  58542. return;
  58543. }
  58544. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  58545. },
  58546. enumerable: true,
  58547. configurable: true
  58548. });
  58549. MultiRenderTarget.prototype.resize = function (size) {
  58550. this.releaseInternalTextures();
  58551. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  58552. this._createInternalTextures();
  58553. };
  58554. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  58555. var _this = this;
  58556. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  58557. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  58558. });
  58559. };
  58560. MultiRenderTarget.prototype.dispose = function () {
  58561. this.releaseInternalTextures();
  58562. _super.prototype.dispose.call(this);
  58563. };
  58564. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  58565. if (!this._internalTextures) {
  58566. return;
  58567. }
  58568. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  58569. if (this._internalTextures[i] !== undefined) {
  58570. this._internalTextures[i].dispose();
  58571. this._internalTextures.splice(i, 1);
  58572. }
  58573. }
  58574. };
  58575. return MultiRenderTarget;
  58576. }(BABYLON.RenderTargetTexture));
  58577. BABYLON.MultiRenderTarget = MultiRenderTarget;
  58578. })(BABYLON || (BABYLON = {}));
  58579. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  58580. var BABYLON;
  58581. (function (BABYLON) {
  58582. var MirrorTexture = /** @class */ (function (_super) {
  58583. __extends(MirrorTexture, _super);
  58584. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  58585. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  58586. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  58587. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  58588. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  58589. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  58590. _this._transformMatrix = BABYLON.Matrix.Zero();
  58591. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  58592. _this._adaptiveBlurKernel = 0;
  58593. _this._blurKernelX = 0;
  58594. _this._blurKernelY = 0;
  58595. _this._blurRatio = 1.0;
  58596. _this.ignoreCameraViewport = true;
  58597. _this.onBeforeRenderObservable.add(function () {
  58598. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  58599. _this._savedViewMatrix = scene.getViewMatrix();
  58600. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  58601. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  58602. scene.clipPlane = _this.mirrorPlane;
  58603. scene.getEngine().cullBackFaces = false;
  58604. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  58605. });
  58606. _this.onAfterRenderObservable.add(function () {
  58607. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  58608. scene.getEngine().cullBackFaces = true;
  58609. scene._mirroredCameraPosition = null;
  58610. delete scene.clipPlane;
  58611. });
  58612. return _this;
  58613. }
  58614. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  58615. get: function () {
  58616. return this._blurRatio;
  58617. },
  58618. set: function (value) {
  58619. if (this._blurRatio === value) {
  58620. return;
  58621. }
  58622. this._blurRatio = value;
  58623. this._preparePostProcesses();
  58624. },
  58625. enumerable: true,
  58626. configurable: true
  58627. });
  58628. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  58629. set: function (value) {
  58630. this._adaptiveBlurKernel = value;
  58631. this._autoComputeBlurKernel();
  58632. },
  58633. enumerable: true,
  58634. configurable: true
  58635. });
  58636. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  58637. set: function (value) {
  58638. this.blurKernelX = value;
  58639. this.blurKernelY = value;
  58640. },
  58641. enumerable: true,
  58642. configurable: true
  58643. });
  58644. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  58645. get: function () {
  58646. return this._blurKernelX;
  58647. },
  58648. set: function (value) {
  58649. if (this._blurKernelX === value) {
  58650. return;
  58651. }
  58652. this._blurKernelX = value;
  58653. this._preparePostProcesses();
  58654. },
  58655. enumerable: true,
  58656. configurable: true
  58657. });
  58658. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  58659. get: function () {
  58660. return this._blurKernelY;
  58661. },
  58662. set: function (value) {
  58663. if (this._blurKernelY === value) {
  58664. return;
  58665. }
  58666. this._blurKernelY = value;
  58667. this._preparePostProcesses();
  58668. },
  58669. enumerable: true,
  58670. configurable: true
  58671. });
  58672. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  58673. var engine = this.getScene().getEngine();
  58674. var dw = this.getRenderWidth() / engine.getRenderWidth();
  58675. var dh = this.getRenderHeight() / engine.getRenderHeight();
  58676. this.blurKernelX = this._adaptiveBlurKernel * dw;
  58677. this.blurKernelY = this._adaptiveBlurKernel * dh;
  58678. };
  58679. MirrorTexture.prototype._onRatioRescale = function () {
  58680. if (this._sizeRatio) {
  58681. this.resize(this._initialSizeParameter);
  58682. if (!this._adaptiveBlurKernel) {
  58683. this._preparePostProcesses();
  58684. }
  58685. }
  58686. if (this._adaptiveBlurKernel) {
  58687. this._autoComputeBlurKernel();
  58688. }
  58689. };
  58690. MirrorTexture.prototype._preparePostProcesses = function () {
  58691. this.clearPostProcesses(true);
  58692. if (this._blurKernelX && this._blurKernelY) {
  58693. var engine = this.getScene().getEngine();
  58694. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  58695. 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);
  58696. this._blurX.autoClear = false;
  58697. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  58698. this._blurX.inputTexture = this._texture;
  58699. }
  58700. else {
  58701. this._blurX.alwaysForcePOT = true;
  58702. }
  58703. 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);
  58704. this._blurY.autoClear = false;
  58705. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  58706. this.addPostProcess(this._blurX);
  58707. this.addPostProcess(this._blurY);
  58708. }
  58709. else {
  58710. if (this._blurY) {
  58711. this.removePostProcess(this._blurY);
  58712. this._blurY.dispose();
  58713. this._blurY = null;
  58714. }
  58715. if (this._blurX) {
  58716. this.removePostProcess(this._blurX);
  58717. this._blurX.dispose();
  58718. this._blurX = null;
  58719. }
  58720. }
  58721. };
  58722. MirrorTexture.prototype.clone = function () {
  58723. var scene = this.getScene();
  58724. if (!scene) {
  58725. return this;
  58726. }
  58727. var textureSize = this.getSize();
  58728. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  58729. // Base texture
  58730. newTexture.hasAlpha = this.hasAlpha;
  58731. newTexture.level = this.level;
  58732. // Mirror Texture
  58733. newTexture.mirrorPlane = this.mirrorPlane.clone();
  58734. if (this.renderList) {
  58735. newTexture.renderList = this.renderList.slice(0);
  58736. }
  58737. return newTexture;
  58738. };
  58739. MirrorTexture.prototype.serialize = function () {
  58740. if (!this.name) {
  58741. return null;
  58742. }
  58743. var serializationObject = _super.prototype.serialize.call(this);
  58744. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  58745. return serializationObject;
  58746. };
  58747. return MirrorTexture;
  58748. }(BABYLON.RenderTargetTexture));
  58749. BABYLON.MirrorTexture = MirrorTexture;
  58750. })(BABYLON || (BABYLON = {}));
  58751. //# sourceMappingURL=babylon.mirrorTexture.js.map
  58752. var BABYLON;
  58753. (function (BABYLON) {
  58754. /**
  58755. * Creates a refraction texture used by refraction channel of the standard material.
  58756. * @param name the texture name
  58757. * @param size size of the underlying texture
  58758. * @param scene root scene
  58759. */
  58760. var RefractionTexture = /** @class */ (function (_super) {
  58761. __extends(RefractionTexture, _super);
  58762. function RefractionTexture(name, size, scene, generateMipMaps) {
  58763. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  58764. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  58765. _this.depth = 2.0;
  58766. _this.onBeforeRenderObservable.add(function () {
  58767. scene.clipPlane = _this.refractionPlane;
  58768. });
  58769. _this.onAfterRenderObservable.add(function () {
  58770. delete scene.clipPlane;
  58771. });
  58772. return _this;
  58773. }
  58774. RefractionTexture.prototype.clone = function () {
  58775. var scene = this.getScene();
  58776. if (!scene) {
  58777. return this;
  58778. }
  58779. var textureSize = this.getSize();
  58780. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  58781. // Base texture
  58782. newTexture.hasAlpha = this.hasAlpha;
  58783. newTexture.level = this.level;
  58784. // Refraction Texture
  58785. newTexture.refractionPlane = this.refractionPlane.clone();
  58786. if (this.renderList) {
  58787. newTexture.renderList = this.renderList.slice(0);
  58788. }
  58789. newTexture.depth = this.depth;
  58790. return newTexture;
  58791. };
  58792. RefractionTexture.prototype.serialize = function () {
  58793. if (!this.name) {
  58794. return null;
  58795. }
  58796. var serializationObject = _super.prototype.serialize.call(this);
  58797. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  58798. serializationObject.depth = this.depth;
  58799. return serializationObject;
  58800. };
  58801. return RefractionTexture;
  58802. }(BABYLON.RenderTargetTexture));
  58803. BABYLON.RefractionTexture = RefractionTexture;
  58804. })(BABYLON || (BABYLON = {}));
  58805. //# sourceMappingURL=babylon.refractionTexture.js.map
  58806. var BABYLON;
  58807. (function (BABYLON) {
  58808. var DynamicTexture = /** @class */ (function (_super) {
  58809. __extends(DynamicTexture, _super);
  58810. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  58811. if (scene === void 0) { scene = null; }
  58812. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  58813. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  58814. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  58815. _this.name = name;
  58816. _this._engine = _this.getScene().getEngine();
  58817. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58818. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58819. _this._generateMipMaps = generateMipMaps;
  58820. if (options.getContext) {
  58821. _this._canvas = options;
  58822. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  58823. }
  58824. else {
  58825. _this._canvas = document.createElement("canvas");
  58826. if (options.width) {
  58827. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  58828. }
  58829. else {
  58830. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  58831. }
  58832. }
  58833. var textureSize = _this.getSize();
  58834. _this._canvas.width = textureSize.width;
  58835. _this._canvas.height = textureSize.height;
  58836. _this._context = _this._canvas.getContext("2d");
  58837. return _this;
  58838. }
  58839. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  58840. get: function () {
  58841. return true;
  58842. },
  58843. enumerable: true,
  58844. configurable: true
  58845. });
  58846. DynamicTexture.prototype._recreate = function (textureSize) {
  58847. this._canvas.width = textureSize.width;
  58848. this._canvas.height = textureSize.height;
  58849. this.releaseInternalTexture();
  58850. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  58851. };
  58852. DynamicTexture.prototype.scale = function (ratio) {
  58853. var textureSize = this.getSize();
  58854. textureSize.width *= ratio;
  58855. textureSize.height *= ratio;
  58856. this._recreate(textureSize);
  58857. };
  58858. DynamicTexture.prototype.scaleTo = function (width, height) {
  58859. var textureSize = this.getSize();
  58860. textureSize.width = width;
  58861. textureSize.height = height;
  58862. this._recreate(textureSize);
  58863. };
  58864. DynamicTexture.prototype.getContext = function () {
  58865. return this._context;
  58866. };
  58867. DynamicTexture.prototype.clear = function () {
  58868. var size = this.getSize();
  58869. this._context.fillRect(0, 0, size.width, size.height);
  58870. };
  58871. DynamicTexture.prototype.update = function (invertY) {
  58872. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format || undefined);
  58873. };
  58874. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  58875. if (update === void 0) { update = true; }
  58876. var size = this.getSize();
  58877. if (clearColor) {
  58878. this._context.fillStyle = clearColor;
  58879. this._context.fillRect(0, 0, size.width, size.height);
  58880. }
  58881. this._context.font = font;
  58882. if (x === null || x === undefined) {
  58883. var textSize = this._context.measureText(text);
  58884. x = (size.width - textSize.width) / 2;
  58885. }
  58886. if (y === null || y === undefined) {
  58887. var fontSize = parseInt((font.replace(/\D/g, '')));
  58888. ;
  58889. y = (size.height / 2) + (fontSize / 3.65);
  58890. }
  58891. this._context.fillStyle = color;
  58892. this._context.fillText(text, x, y);
  58893. if (update) {
  58894. this.update(invertY);
  58895. }
  58896. };
  58897. DynamicTexture.prototype.clone = function () {
  58898. var scene = this.getScene();
  58899. if (!scene) {
  58900. return this;
  58901. }
  58902. var textureSize = this.getSize();
  58903. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  58904. // Base texture
  58905. newTexture.hasAlpha = this.hasAlpha;
  58906. newTexture.level = this.level;
  58907. // Dynamic Texture
  58908. newTexture.wrapU = this.wrapU;
  58909. newTexture.wrapV = this.wrapV;
  58910. return newTexture;
  58911. };
  58912. DynamicTexture.prototype._rebuild = function () {
  58913. this.update();
  58914. };
  58915. return DynamicTexture;
  58916. }(BABYLON.Texture));
  58917. BABYLON.DynamicTexture = DynamicTexture;
  58918. })(BABYLON || (BABYLON = {}));
  58919. //# sourceMappingURL=babylon.dynamicTexture.js.map
  58920. var BABYLON;
  58921. (function (BABYLON) {
  58922. var VideoTexture = /** @class */ (function (_super) {
  58923. __extends(VideoTexture, _super);
  58924. /**
  58925. * Creates a video texture.
  58926. * Sample : https://doc.babylonjs.com/how_to/video_texture
  58927. * @param {string | null} name optional name, will detect from video source, if not defined
  58928. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  58929. * @param {BABYLON.Scene} scene is obviously the current scene.
  58930. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  58931. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  58932. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  58933. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  58934. */
  58935. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  58936. if (generateMipMaps === void 0) { generateMipMaps = false; }
  58937. if (invertY === void 0) { invertY = false; }
  58938. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  58939. if (settings === void 0) { settings = {
  58940. autoPlay: true,
  58941. loop: true,
  58942. autoUpdateTexture: true,
  58943. }; }
  58944. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  58945. _this._createInternalTexture = function () {
  58946. if (_this._texture != null) {
  58947. return;
  58948. }
  58949. if (!_this._engine.needPOTTextures ||
  58950. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  58951. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  58952. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  58953. }
  58954. else {
  58955. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58956. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58957. _this._generateMipMaps = false;
  58958. }
  58959. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  58960. _this._texture.isReady = true;
  58961. _this._updateInternalTexture();
  58962. };
  58963. _this.reset = function () {
  58964. if (_this._texture == null) {
  58965. return;
  58966. }
  58967. _this._texture.dispose();
  58968. _this._texture = null;
  58969. };
  58970. _this._updateInternalTexture = function (e) {
  58971. if (_this._texture == null || !_this._texture.isReady) {
  58972. return;
  58973. }
  58974. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  58975. return;
  58976. }
  58977. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  58978. };
  58979. _this._engine = _this.getScene().getEngine();
  58980. _this._generateMipMaps = generateMipMaps;
  58981. _this._samplingMode = samplingMode;
  58982. _this.autoUpdateTexture = settings.autoUpdateTexture;
  58983. _this.name = name || _this._getName(src);
  58984. _this.video = _this._getVideo(src);
  58985. if (settings.autoPlay !== undefined) {
  58986. _this.video.autoplay = settings.autoPlay;
  58987. }
  58988. if (settings.loop !== undefined) {
  58989. _this.video.loop = settings.loop;
  58990. }
  58991. _this.video.addEventListener("canplay", _this._createInternalTexture);
  58992. _this.video.addEventListener("paused", _this._updateInternalTexture);
  58993. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  58994. _this.video.addEventListener("emptied", _this.reset);
  58995. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  58996. _this._createInternalTexture();
  58997. }
  58998. return _this;
  58999. }
  59000. VideoTexture.prototype._getName = function (src) {
  59001. if (src instanceof HTMLVideoElement) {
  59002. return src.currentSrc;
  59003. }
  59004. if (typeof src === "object") {
  59005. return src.toString();
  59006. }
  59007. return src;
  59008. };
  59009. ;
  59010. VideoTexture.prototype._getVideo = function (src) {
  59011. if (src instanceof HTMLVideoElement) {
  59012. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  59013. return src;
  59014. }
  59015. var video = document.createElement("video");
  59016. if (typeof src === "string") {
  59017. BABYLON.Tools.SetCorsBehavior(src, video);
  59018. video.src = src;
  59019. }
  59020. else {
  59021. BABYLON.Tools.SetCorsBehavior(src[0], video);
  59022. src.forEach(function (url) {
  59023. var source = document.createElement("source");
  59024. source.src = url;
  59025. video.appendChild(source);
  59026. });
  59027. }
  59028. return video;
  59029. };
  59030. ;
  59031. /**
  59032. * Internal method to initiate `update`.
  59033. */
  59034. VideoTexture.prototype._rebuild = function () {
  59035. this.update();
  59036. };
  59037. /**
  59038. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  59039. */
  59040. VideoTexture.prototype.update = function () {
  59041. if (!this.autoUpdateTexture) {
  59042. // Expecting user to call `updateTexture` manually
  59043. return;
  59044. }
  59045. this.updateTexture(true);
  59046. };
  59047. /**
  59048. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  59049. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  59050. */
  59051. VideoTexture.prototype.updateTexture = function (isVisible) {
  59052. if (!isVisible) {
  59053. return;
  59054. }
  59055. if (this.video.paused) {
  59056. return;
  59057. }
  59058. this._updateInternalTexture();
  59059. };
  59060. /**
  59061. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  59062. * @param url New url.
  59063. */
  59064. VideoTexture.prototype.updateURL = function (url) {
  59065. this.video.src = url;
  59066. };
  59067. VideoTexture.prototype.dispose = function () {
  59068. _super.prototype.dispose.call(this);
  59069. this.video.removeEventListener("canplay", this._createInternalTexture);
  59070. this.video.removeEventListener("paused", this._updateInternalTexture);
  59071. this.video.removeEventListener("seeked", this._updateInternalTexture);
  59072. this.video.removeEventListener("emptied", this.reset);
  59073. this.video.pause();
  59074. };
  59075. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  59076. var video = document.createElement("video");
  59077. var constraintsDeviceId;
  59078. if (constraints && constraints.deviceId) {
  59079. constraintsDeviceId = {
  59080. exact: constraints.deviceId,
  59081. };
  59082. }
  59083. navigator.getUserMedia =
  59084. navigator.getUserMedia ||
  59085. navigator.webkitGetUserMedia ||
  59086. navigator.mozGetUserMedia ||
  59087. navigator.msGetUserMedia;
  59088. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  59089. if (navigator.getUserMedia) {
  59090. navigator.getUserMedia({
  59091. video: {
  59092. deviceId: constraintsDeviceId,
  59093. width: {
  59094. min: (constraints && constraints.minWidth) || 256,
  59095. max: (constraints && constraints.maxWidth) || 640,
  59096. },
  59097. height: {
  59098. min: (constraints && constraints.minHeight) || 256,
  59099. max: (constraints && constraints.maxHeight) || 480,
  59100. },
  59101. },
  59102. }, function (stream) {
  59103. if (video.mozSrcObject !== undefined) {
  59104. // hack for Firefox < 19
  59105. video.mozSrcObject = stream;
  59106. }
  59107. else {
  59108. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  59109. }
  59110. video.play();
  59111. if (onReady) {
  59112. onReady(new VideoTexture("video", video, scene, true, true));
  59113. }
  59114. }, function (e) {
  59115. BABYLON.Tools.Error(e.name);
  59116. });
  59117. }
  59118. };
  59119. return VideoTexture;
  59120. }(BABYLON.Texture));
  59121. BABYLON.VideoTexture = VideoTexture;
  59122. })(BABYLON || (BABYLON = {}));
  59123. //# sourceMappingURL=babylon.videoTexture.js.map
  59124. var BABYLON;
  59125. (function (BABYLON) {
  59126. var RawTexture = /** @class */ (function (_super) {
  59127. __extends(RawTexture, _super);
  59128. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  59129. if (generateMipMaps === void 0) { generateMipMaps = true; }
  59130. if (invertY === void 0) { invertY = false; }
  59131. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  59132. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59133. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  59134. _this.format = format;
  59135. _this._engine = scene.getEngine();
  59136. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  59137. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59138. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59139. return _this;
  59140. }
  59141. RawTexture.prototype.update = function (data) {
  59142. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  59143. };
  59144. // Statics
  59145. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  59146. if (generateMipMaps === void 0) { generateMipMaps = true; }
  59147. if (invertY === void 0) { invertY = false; }
  59148. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  59149. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  59150. };
  59151. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  59152. if (generateMipMaps === void 0) { generateMipMaps = true; }
  59153. if (invertY === void 0) { invertY = false; }
  59154. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  59155. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  59156. };
  59157. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  59158. if (generateMipMaps === void 0) { generateMipMaps = true; }
  59159. if (invertY === void 0) { invertY = false; }
  59160. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  59161. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  59162. };
  59163. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  59164. if (generateMipMaps === void 0) { generateMipMaps = true; }
  59165. if (invertY === void 0) { invertY = false; }
  59166. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  59167. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59168. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  59169. };
  59170. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  59171. if (generateMipMaps === void 0) { generateMipMaps = true; }
  59172. if (invertY === void 0) { invertY = false; }
  59173. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  59174. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59175. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  59176. };
  59177. return RawTexture;
  59178. }(BABYLON.Texture));
  59179. BABYLON.RawTexture = RawTexture;
  59180. })(BABYLON || (BABYLON = {}));
  59181. //# sourceMappingURL=babylon.rawTexture.js.map
  59182. var BABYLON;
  59183. (function (BABYLON) {
  59184. /**
  59185. * PostProcess can be used to apply a shader to a texture after it has been rendered
  59186. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  59187. */
  59188. var PostProcess = /** @class */ (function () {
  59189. /**
  59190. * Creates a new instance of @see PostProcess
  59191. * @param name The name of the PostProcess.
  59192. * @param fragmentUrl The url of the fragment shader to be used.
  59193. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  59194. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  59195. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  59196. * @param camera The camera to apply the render pass to.
  59197. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  59198. * @param engine The engine which the post process will be applied. (default: current engine)
  59199. * @param reusable If the post process can be reused on the same frame. (default: false)
  59200. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  59201. * @param textureType Type of textures used when performing the post process. (default: 0)
  59202. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  59203. * @param indexParameters The index parameters to be used for babylons include syntax "#include<kernelBlurVaryingDeclaration>[0..varyingCount]". (default: undefined) See usage in babylon.blurPostProcess.ts and kernelBlur.vertex.fx
  59204. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  59205. */
  59206. function PostProcess(/** Name of the PostProcess. */ name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  59207. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  59208. if (defines === void 0) { defines = null; }
  59209. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59210. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  59211. if (blockCompilation === void 0) { blockCompilation = false; }
  59212. this.name = name;
  59213. /**
  59214. * Width of the texture to apply the post process on
  59215. */
  59216. this.width = -1;
  59217. /**
  59218. * Height of the texture to apply the post process on
  59219. */
  59220. this.height = -1;
  59221. /**
  59222. * If the buffer needs to be cleared before applying the post process. (default: true)
  59223. * Should be set to false if shader will overwrite all previous pixels.
  59224. */
  59225. this.autoClear = true;
  59226. /**
  59227. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  59228. */
  59229. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  59230. /**
  59231. * Animations to be used for the post processing
  59232. */
  59233. this.animations = new Array();
  59234. /**
  59235. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  59236. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  59237. */
  59238. this.enablePixelPerfectMode = false;
  59239. /**
  59240. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  59241. */
  59242. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  59243. /**
  59244. * Force textures to be a power of two (default: false)
  59245. */
  59246. this.alwaysForcePOT = false;
  59247. /**
  59248. * Number of sample textures (default: 1)
  59249. */
  59250. this.samples = 1;
  59251. /**
  59252. * Modify the scale of the post process to be the same as the viewport (default: false)
  59253. */
  59254. this.adaptScaleToCurrentViewport = false;
  59255. this._reusable = false;
  59256. /**
  59257. * Smart array of input and output textures for the post process.
  59258. */
  59259. this._textures = new BABYLON.SmartArray(2);
  59260. /**
  59261. * The index in _textures that corresponds to the output texture.
  59262. */
  59263. this._currentRenderTextureInd = 0;
  59264. this._scaleRatio = new BABYLON.Vector2(1, 1);
  59265. this._texelSize = BABYLON.Vector2.Zero();
  59266. // Events
  59267. /**
  59268. * An event triggered when the postprocess is activated.
  59269. * @type {BABYLON.Observable}
  59270. */
  59271. this.onActivateObservable = new BABYLON.Observable();
  59272. /**
  59273. * An event triggered when the postprocess changes its size.
  59274. * @type {BABYLON.Observable}
  59275. */
  59276. this.onSizeChangedObservable = new BABYLON.Observable();
  59277. /**
  59278. * An event triggered when the postprocess applies its effect.
  59279. * @type {BABYLON.Observable}
  59280. */
  59281. this.onApplyObservable = new BABYLON.Observable();
  59282. /**
  59283. * An event triggered before rendering the postprocess
  59284. * @type {BABYLON.Observable}
  59285. */
  59286. this.onBeforeRenderObservable = new BABYLON.Observable();
  59287. /**
  59288. * An event triggered after rendering the postprocess
  59289. * @type {BABYLON.Observable}
  59290. */
  59291. this.onAfterRenderObservable = new BABYLON.Observable();
  59292. if (camera != null) {
  59293. this._camera = camera;
  59294. this._scene = camera.getScene();
  59295. camera.attachPostProcess(this);
  59296. this._engine = this._scene.getEngine();
  59297. this._scene.postProcesses.push(this);
  59298. }
  59299. else if (engine) {
  59300. this._engine = engine;
  59301. this._engine.postProcesses.push(this);
  59302. }
  59303. this._options = options;
  59304. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  59305. this._reusable = reusable || false;
  59306. this._textureType = textureType;
  59307. this._samplers = samplers || [];
  59308. this._samplers.push("textureSampler");
  59309. this._fragmentUrl = fragmentUrl;
  59310. this._vertexUrl = vertexUrl;
  59311. this._parameters = parameters || [];
  59312. this._parameters.push("scale");
  59313. this._indexParameters = indexParameters;
  59314. if (!blockCompilation) {
  59315. this.updateEffect(defines);
  59316. }
  59317. }
  59318. Object.defineProperty(PostProcess.prototype, "onActivate", {
  59319. /**
  59320. * A function that is added to the onActivateObservable
  59321. */
  59322. set: function (callback) {
  59323. if (this._onActivateObserver) {
  59324. this.onActivateObservable.remove(this._onActivateObserver);
  59325. }
  59326. if (callback) {
  59327. this._onActivateObserver = this.onActivateObservable.add(callback);
  59328. }
  59329. },
  59330. enumerable: true,
  59331. configurable: true
  59332. });
  59333. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  59334. /**
  59335. * A function that is added to the onSizeChangedObservable
  59336. */
  59337. set: function (callback) {
  59338. if (this._onSizeChangedObserver) {
  59339. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  59340. }
  59341. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  59342. },
  59343. enumerable: true,
  59344. configurable: true
  59345. });
  59346. Object.defineProperty(PostProcess.prototype, "onApply", {
  59347. /**
  59348. * A function that is added to the onApplyObservable
  59349. */
  59350. set: function (callback) {
  59351. if (this._onApplyObserver) {
  59352. this.onApplyObservable.remove(this._onApplyObserver);
  59353. }
  59354. this._onApplyObserver = this.onApplyObservable.add(callback);
  59355. },
  59356. enumerable: true,
  59357. configurable: true
  59358. });
  59359. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  59360. /**
  59361. * A function that is added to the onBeforeRenderObservable
  59362. */
  59363. set: function (callback) {
  59364. if (this._onBeforeRenderObserver) {
  59365. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  59366. }
  59367. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  59368. },
  59369. enumerable: true,
  59370. configurable: true
  59371. });
  59372. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  59373. /**
  59374. * A function that is added to the onAfterRenderObservable
  59375. */
  59376. set: function (callback) {
  59377. if (this._onAfterRenderObserver) {
  59378. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  59379. }
  59380. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  59381. },
  59382. enumerable: true,
  59383. configurable: true
  59384. });
  59385. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  59386. /**
  59387. * The input texture for this post process and the output texture of the previous post process. When added to a pipeline the previous post process will
  59388. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  59389. */
  59390. get: function () {
  59391. return this._textures.data[this._currentRenderTextureInd];
  59392. },
  59393. set: function (value) {
  59394. this._forcedOutputTexture = value;
  59395. },
  59396. enumerable: true,
  59397. configurable: true
  59398. });
  59399. /**
  59400. * Gets the camera which post process is applied to.
  59401. * @returns The camera the post process is applied to.
  59402. */
  59403. PostProcess.prototype.getCamera = function () {
  59404. return this._camera;
  59405. };
  59406. Object.defineProperty(PostProcess.prototype, "texelSize", {
  59407. /**
  59408. * Gets the texel size of the postprocess.
  59409. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  59410. */
  59411. get: function () {
  59412. if (this._shareOutputWithPostProcess) {
  59413. return this._shareOutputWithPostProcess.texelSize;
  59414. }
  59415. if (this._forcedOutputTexture) {
  59416. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  59417. }
  59418. return this._texelSize;
  59419. },
  59420. enumerable: true,
  59421. configurable: true
  59422. });
  59423. /**
  59424. * Gets the engine which this post process belongs to.
  59425. * @returns The engine the post process was enabled with.
  59426. */
  59427. PostProcess.prototype.getEngine = function () {
  59428. return this._engine;
  59429. };
  59430. /**
  59431. * The effect that is created when initializing the post process.
  59432. * @returns The created effect corrisponding the the postprocess.
  59433. */
  59434. PostProcess.prototype.getEffect = function () {
  59435. return this._effect;
  59436. };
  59437. /**
  59438. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  59439. * @param postProcess The post process to share the output with.
  59440. * @returns This post process.
  59441. */
  59442. PostProcess.prototype.shareOutputWith = function (postProcess) {
  59443. this._disposeTextures();
  59444. this._shareOutputWithPostProcess = postProcess;
  59445. return this;
  59446. };
  59447. /**
  59448. * Updates the effect with the current post process compile time values and recompiles the shader.
  59449. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  59450. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  59451. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  59452. * @param indexParameters The index parameters to be used for babylons include syntax "#include<kernelBlurVaryingDeclaration>[0..varyingCount]". (default: undefined) See usage in babylon.blurPostProcess.ts and kernelBlur.vertex.fx
  59453. * @param onCompiled Called when the shader has been compiled.
  59454. * @param onError Called if there is an error when compiling a shader.
  59455. */
  59456. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  59457. if (defines === void 0) { defines = null; }
  59458. if (uniforms === void 0) { uniforms = null; }
  59459. if (samplers === void 0) { samplers = null; }
  59460. 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);
  59461. };
  59462. /**
  59463. * The post process is reusable if it can be used multiple times within one frame.
  59464. * @returns If the post process is reusable
  59465. */
  59466. PostProcess.prototype.isReusable = function () {
  59467. return this._reusable;
  59468. };
  59469. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  59470. PostProcess.prototype.markTextureDirty = function () {
  59471. this.width = -1;
  59472. };
  59473. /**
  59474. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  59475. * When this post process is used in a pipeline, this is call will bind the input texture of this post process to the output of the previous.
  59476. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  59477. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  59478. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  59479. */
  59480. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  59481. var _this = this;
  59482. if (sourceTexture === void 0) { sourceTexture = null; }
  59483. camera = camera || this._camera;
  59484. var scene = camera.getScene();
  59485. var engine = scene.getEngine();
  59486. var maxSize = engine.getCaps().maxTextureSize;
  59487. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  59488. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  59489. var desiredWidth = (this._options.width || requiredWidth);
  59490. var desiredHeight = this._options.height || requiredHeight;
  59491. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  59492. if (this.adaptScaleToCurrentViewport) {
  59493. var currentViewport = engine.currentViewport;
  59494. if (currentViewport) {
  59495. desiredWidth *= currentViewport.width;
  59496. desiredHeight *= currentViewport.height;
  59497. }
  59498. }
  59499. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  59500. if (!this._options.width) {
  59501. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  59502. }
  59503. if (!this._options.height) {
  59504. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  59505. }
  59506. }
  59507. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  59508. if (this._textures.length > 0) {
  59509. for (var i = 0; i < this._textures.length; i++) {
  59510. this._engine._releaseTexture(this._textures.data[i]);
  59511. }
  59512. this._textures.reset();
  59513. }
  59514. this.width = desiredWidth;
  59515. this.height = desiredHeight;
  59516. var textureSize = { width: this.width, height: this.height };
  59517. var textureOptions = {
  59518. generateMipMaps: false,
  59519. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  59520. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  59521. samplingMode: this.renderTargetSamplingMode,
  59522. type: this._textureType
  59523. };
  59524. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  59525. if (this._reusable) {
  59526. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  59527. }
  59528. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  59529. this.onSizeChangedObservable.notifyObservers(this);
  59530. }
  59531. this._textures.forEach(function (texture) {
  59532. if (texture.samples !== _this.samples) {
  59533. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  59534. }
  59535. });
  59536. }
  59537. var target;
  59538. if (this._shareOutputWithPostProcess) {
  59539. target = this._shareOutputWithPostProcess.inputTexture;
  59540. }
  59541. else if (this._forcedOutputTexture) {
  59542. target = this._forcedOutputTexture;
  59543. this.width = this._forcedOutputTexture.width;
  59544. this.height = this._forcedOutputTexture.height;
  59545. }
  59546. else {
  59547. target = this.inputTexture;
  59548. }
  59549. // Bind the input of this post process to be used as the output of the previous post process.
  59550. if (this.enablePixelPerfectMode) {
  59551. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  59552. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  59553. }
  59554. else {
  59555. this._scaleRatio.copyFromFloats(1, 1);
  59556. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  59557. }
  59558. this.onActivateObservable.notifyObservers(camera);
  59559. // Clear
  59560. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  59561. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  59562. }
  59563. if (this._reusable) {
  59564. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  59565. }
  59566. };
  59567. Object.defineProperty(PostProcess.prototype, "isSupported", {
  59568. /**
  59569. * If the post process is supported.
  59570. */
  59571. get: function () {
  59572. return this._effect.isSupported;
  59573. },
  59574. enumerable: true,
  59575. configurable: true
  59576. });
  59577. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  59578. /**
  59579. * The aspect ratio of the output texture.
  59580. */
  59581. get: function () {
  59582. if (this._shareOutputWithPostProcess) {
  59583. return this._shareOutputWithPostProcess.aspectRatio;
  59584. }
  59585. if (this._forcedOutputTexture) {
  59586. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  59587. }
  59588. return this.width / this.height;
  59589. },
  59590. enumerable: true,
  59591. configurable: true
  59592. });
  59593. /**
  59594. * Get a value indicating if the post-process is ready to be used
  59595. * @returns true if the post-process is ready (shader is compiled)
  59596. */
  59597. PostProcess.prototype.isReady = function () {
  59598. return this._effect && this._effect.isReady();
  59599. };
  59600. /**
  59601. * Binds all textures and uniforms to the shader, this will be run on every pass.
  59602. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  59603. */
  59604. PostProcess.prototype.apply = function () {
  59605. // Check
  59606. if (!this._effect || !this._effect.isReady())
  59607. return null;
  59608. // States
  59609. this._engine.enableEffect(this._effect);
  59610. this._engine.setState(false);
  59611. this._engine.setDepthBuffer(false);
  59612. this._engine.setDepthWrite(false);
  59613. // Alpha
  59614. this._engine.setAlphaMode(this.alphaMode);
  59615. if (this.alphaConstants) {
  59616. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  59617. }
  59618. // Bind the output texture of the preivous post process as the input to this post process.
  59619. var source;
  59620. if (this._shareOutputWithPostProcess) {
  59621. source = this._shareOutputWithPostProcess.inputTexture;
  59622. }
  59623. else if (this._forcedOutputTexture) {
  59624. source = this._forcedOutputTexture;
  59625. }
  59626. else {
  59627. source = this.inputTexture;
  59628. }
  59629. this._effect._bindTexture("textureSampler", source);
  59630. // Parameters
  59631. this._effect.setVector2("scale", this._scaleRatio);
  59632. this.onApplyObservable.notifyObservers(this._effect);
  59633. return this._effect;
  59634. };
  59635. PostProcess.prototype._disposeTextures = function () {
  59636. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  59637. return;
  59638. }
  59639. if (this._textures.length > 0) {
  59640. for (var i = 0; i < this._textures.length; i++) {
  59641. this._engine._releaseTexture(this._textures.data[i]);
  59642. }
  59643. }
  59644. this._textures.dispose();
  59645. };
  59646. /**
  59647. * Disposes the post process.
  59648. * @param camera The camera to dispose the post process on.
  59649. */
  59650. PostProcess.prototype.dispose = function (camera) {
  59651. camera = camera || this._camera;
  59652. this._disposeTextures();
  59653. if (this._scene) {
  59654. var index_1 = this._scene.postProcesses.indexOf(this);
  59655. if (index_1 !== -1) {
  59656. this._scene.postProcesses.splice(index_1, 1);
  59657. }
  59658. }
  59659. else {
  59660. var index_2 = this._engine.postProcesses.indexOf(this);
  59661. if (index_2 !== -1) {
  59662. this._engine.postProcesses.splice(index_2, 1);
  59663. }
  59664. }
  59665. if (!camera) {
  59666. return;
  59667. }
  59668. camera.detachPostProcess(this);
  59669. var index = camera._postProcesses.indexOf(this);
  59670. if (index === 0 && camera._postProcesses.length > 0) {
  59671. this._camera._postProcesses[0].markTextureDirty();
  59672. }
  59673. this.onActivateObservable.clear();
  59674. this.onAfterRenderObservable.clear();
  59675. this.onApplyObservable.clear();
  59676. this.onBeforeRenderObservable.clear();
  59677. this.onSizeChangedObservable.clear();
  59678. };
  59679. return PostProcess;
  59680. }());
  59681. BABYLON.PostProcess = PostProcess;
  59682. })(BABYLON || (BABYLON = {}));
  59683. //# sourceMappingURL=babylon.postProcess.js.map
  59684. var BABYLON;
  59685. (function (BABYLON) {
  59686. var PassPostProcess = /** @class */ (function (_super) {
  59687. __extends(PassPostProcess, _super);
  59688. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  59689. if (camera === void 0) { camera = null; }
  59690. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59691. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType) || this;
  59692. }
  59693. return PassPostProcess;
  59694. }(BABYLON.PostProcess));
  59695. BABYLON.PassPostProcess = PassPostProcess;
  59696. })(BABYLON || (BABYLON = {}));
  59697. //# sourceMappingURL=babylon.passPostProcess.js.map
  59698. var __assign = (this && this.__assign) || Object.assign || function(t) {
  59699. for (var s, i = 1, n = arguments.length; i < n; i++) {
  59700. s = arguments[i];
  59701. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  59702. t[p] = s[p];
  59703. }
  59704. return t;
  59705. };
  59706. var BABYLON;
  59707. (function (BABYLON) {
  59708. /**
  59709. * Default implementation of @see IShadowGenerator.
  59710. * This is the main object responsible of generating shadows in the framework.
  59711. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  59712. */
  59713. var ShadowGenerator = /** @class */ (function () {
  59714. /**
  59715. * Creates a ShadowGenerator object.
  59716. * A ShadowGenerator is the required tool to use the shadows.
  59717. * Each light casting shadows needs to use its own ShadowGenerator.
  59718. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  59719. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  59720. * @param light The light object generating the shadows.
  59721. * @param useFullFloatFirst By default the generator will try to use half float textures but if you need precision (for self shadowing for instance), you can use this option to enforce full float texture.
  59722. */
  59723. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  59724. this._bias = 0.00005;
  59725. this._blurBoxOffset = 1;
  59726. this._blurScale = 2;
  59727. this._blurKernel = 1;
  59728. this._useKernelBlur = false;
  59729. this._filter = ShadowGenerator.FILTER_NONE;
  59730. this._darkness = 0;
  59731. this._transparencyShadow = false;
  59732. /**
  59733. * Controls the extent to which the shadows fade out at the edge of the frustum
  59734. * Used only by directionals and spots
  59735. */
  59736. this.frustumEdgeFalloff = 0;
  59737. /**
  59738. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  59739. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  59740. * It might on the other hand introduce peter panning.
  59741. */
  59742. this.forceBackFacesOnly = false;
  59743. this._lightDirection = BABYLON.Vector3.Zero();
  59744. this._viewMatrix = BABYLON.Matrix.Zero();
  59745. this._projectionMatrix = BABYLON.Matrix.Zero();
  59746. this._transformMatrix = BABYLON.Matrix.Zero();
  59747. this._currentFaceIndex = 0;
  59748. this._currentFaceIndexCache = 0;
  59749. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  59750. this._mapSize = mapSize;
  59751. this._light = light;
  59752. this._scene = light.getScene();
  59753. light._shadowGenerator = this;
  59754. // Texture type fallback from float to int if not supported.
  59755. var caps = this._scene.getEngine().getCaps();
  59756. if (!useFullFloatFirst) {
  59757. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  59758. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  59759. }
  59760. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  59761. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  59762. }
  59763. else {
  59764. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  59765. }
  59766. }
  59767. else {
  59768. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  59769. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  59770. }
  59771. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  59772. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  59773. }
  59774. else {
  59775. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  59776. }
  59777. }
  59778. this._initializeGenerator();
  59779. }
  59780. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  59781. /**
  59782. * Shadow generator mode None: no filtering applied.
  59783. */
  59784. get: function () {
  59785. return ShadowGenerator._FILTER_NONE;
  59786. },
  59787. enumerable: true,
  59788. configurable: true
  59789. });
  59790. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  59791. /**
  59792. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  59793. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  59794. */
  59795. get: function () {
  59796. return ShadowGenerator._FILTER_POISSONSAMPLING;
  59797. },
  59798. enumerable: true,
  59799. configurable: true
  59800. });
  59801. Object.defineProperty(ShadowGenerator, "FILTER_EXPONENTIALSHADOWMAP", {
  59802. /**
  59803. * Shadow generator mode ESM: Exponential Shadow Mapping.
  59804. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  59805. */
  59806. get: function () {
  59807. return ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP;
  59808. },
  59809. enumerable: true,
  59810. configurable: true
  59811. });
  59812. Object.defineProperty(ShadowGenerator, "FILTER_BLUREXPONENTIALSHADOWMAP", {
  59813. /**
  59814. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  59815. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  59816. */
  59817. get: function () {
  59818. return ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP;
  59819. },
  59820. enumerable: true,
  59821. configurable: true
  59822. });
  59823. Object.defineProperty(ShadowGenerator, "FILTER_CLOSEEXPONENTIALSHADOWMAP", {
  59824. /**
  59825. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  59826. * edge artifacts on steep falloff.
  59827. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  59828. */
  59829. get: function () {
  59830. return ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP;
  59831. },
  59832. enumerable: true,
  59833. configurable: true
  59834. });
  59835. Object.defineProperty(ShadowGenerator, "FILTER_BLURCLOSEEXPONENTIALSHADOWMAP", {
  59836. /**
  59837. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  59838. * edge artifacts on steep falloff.
  59839. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  59840. */
  59841. get: function () {
  59842. return ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  59843. },
  59844. enumerable: true,
  59845. configurable: true
  59846. });
  59847. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  59848. /**
  59849. * Gets the bias: offset applied on the depth preventing acnea.
  59850. */
  59851. get: function () {
  59852. return this._bias;
  59853. },
  59854. /**
  59855. * Sets the bias: offset applied on the depth preventing acnea.
  59856. */
  59857. set: function (bias) {
  59858. this._bias = bias;
  59859. },
  59860. enumerable: true,
  59861. configurable: true
  59862. });
  59863. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  59864. /**
  59865. * Gets the blur box offset: offset applied during the blur pass.
  59866. * Only usefull if useKernelBlur = false
  59867. */
  59868. get: function () {
  59869. return this._blurBoxOffset;
  59870. },
  59871. /**
  59872. * Sets the blur box offset: offset applied during the blur pass.
  59873. * Only usefull if useKernelBlur = false
  59874. */
  59875. set: function (value) {
  59876. if (this._blurBoxOffset === value) {
  59877. return;
  59878. }
  59879. this._blurBoxOffset = value;
  59880. this._disposeBlurPostProcesses();
  59881. },
  59882. enumerable: true,
  59883. configurable: true
  59884. });
  59885. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  59886. /**
  59887. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  59888. * 2 means half of the size.
  59889. */
  59890. get: function () {
  59891. return this._blurScale;
  59892. },
  59893. /**
  59894. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  59895. * 2 means half of the size.
  59896. */
  59897. set: function (value) {
  59898. if (this._blurScale === value) {
  59899. return;
  59900. }
  59901. this._blurScale = value;
  59902. this._disposeBlurPostProcesses();
  59903. },
  59904. enumerable: true,
  59905. configurable: true
  59906. });
  59907. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  59908. /**
  59909. * Gets the blur kernel: kernel size of the blur pass.
  59910. * Only usefull if useKernelBlur = true
  59911. */
  59912. get: function () {
  59913. return this._blurKernel;
  59914. },
  59915. /**
  59916. * Sets the blur kernel: kernel size of the blur pass.
  59917. * Only usefull if useKernelBlur = true
  59918. */
  59919. set: function (value) {
  59920. if (this._blurKernel === value) {
  59921. return;
  59922. }
  59923. this._blurKernel = value;
  59924. this._disposeBlurPostProcesses();
  59925. },
  59926. enumerable: true,
  59927. configurable: true
  59928. });
  59929. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  59930. /**
  59931. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  59932. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  59933. */
  59934. get: function () {
  59935. return this._useKernelBlur;
  59936. },
  59937. /**
  59938. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  59939. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  59940. */
  59941. set: function (value) {
  59942. if (this._useKernelBlur === value) {
  59943. return;
  59944. }
  59945. this._useKernelBlur = value;
  59946. this._disposeBlurPostProcesses();
  59947. },
  59948. enumerable: true,
  59949. configurable: true
  59950. });
  59951. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  59952. /**
  59953. * Gets the depth scale used in ESM mode.
  59954. */
  59955. get: function () {
  59956. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  59957. },
  59958. /**
  59959. * Sets the depth scale used in ESM mode.
  59960. * This can override the scale stored on the light.
  59961. */
  59962. set: function (value) {
  59963. this._depthScale = value;
  59964. },
  59965. enumerable: true,
  59966. configurable: true
  59967. });
  59968. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  59969. /**
  59970. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  59971. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  59972. */
  59973. get: function () {
  59974. return this._filter;
  59975. },
  59976. /**
  59977. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  59978. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  59979. */
  59980. set: function (value) {
  59981. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  59982. if (this._light.needCube()) {
  59983. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  59984. this.useExponentialShadowMap = true;
  59985. return;
  59986. }
  59987. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  59988. this.useCloseExponentialShadowMap = true;
  59989. return;
  59990. }
  59991. }
  59992. if (this._filter === value) {
  59993. return;
  59994. }
  59995. this._filter = value;
  59996. this._disposeBlurPostProcesses();
  59997. this._applyFilterValues();
  59998. this._light._markMeshesAsLightDirty();
  59999. },
  60000. enumerable: true,
  60001. configurable: true
  60002. });
  60003. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  60004. /**
  60005. * Gets if the current filter is set to Poisson Sampling aka PCF.
  60006. */
  60007. get: function () {
  60008. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  60009. },
  60010. /**
  60011. * Sets the current filter to Poisson Sampling aka PCF.
  60012. */
  60013. set: function (value) {
  60014. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  60015. return;
  60016. }
  60017. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  60018. },
  60019. enumerable: true,
  60020. configurable: true
  60021. });
  60022. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  60023. /**
  60024. * Gets if the current filter is set to VSM.
  60025. * DEPRECATED. Should use useExponentialShadowMap instead.
  60026. */
  60027. get: function () {
  60028. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  60029. return this.useExponentialShadowMap;
  60030. },
  60031. /**
  60032. * Sets the current filter is to VSM.
  60033. * DEPRECATED. Should use useExponentialShadowMap instead.
  60034. */
  60035. set: function (value) {
  60036. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  60037. this.useExponentialShadowMap = value;
  60038. },
  60039. enumerable: true,
  60040. configurable: true
  60041. });
  60042. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  60043. /**
  60044. * Gets if the current filter is set to blurred VSM.
  60045. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  60046. */
  60047. get: function () {
  60048. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  60049. return this.useBlurExponentialShadowMap;
  60050. },
  60051. /**
  60052. * Sets the current filter is to blurred VSM.
  60053. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  60054. */
  60055. set: function (value) {
  60056. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  60057. this.useBlurExponentialShadowMap = value;
  60058. },
  60059. enumerable: true,
  60060. configurable: true
  60061. });
  60062. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  60063. /**
  60064. * Gets if the current filter is set to ESM.
  60065. */
  60066. get: function () {
  60067. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  60068. },
  60069. /**
  60070. * Sets the current filter is to ESM.
  60071. */
  60072. set: function (value) {
  60073. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  60074. return;
  60075. }
  60076. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  60077. },
  60078. enumerable: true,
  60079. configurable: true
  60080. });
  60081. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  60082. /**
  60083. * Gets if the current filter is set to filtered ESM.
  60084. */
  60085. get: function () {
  60086. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  60087. },
  60088. /**
  60089. * Gets if the current filter is set to filtered ESM.
  60090. */
  60091. set: function (value) {
  60092. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  60093. return;
  60094. }
  60095. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  60096. },
  60097. enumerable: true,
  60098. configurable: true
  60099. });
  60100. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  60101. /**
  60102. * Gets if the current filter is set to "close ESM" (using the inverse of the
  60103. * exponential to prevent steep falloff artifacts).
  60104. */
  60105. get: function () {
  60106. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  60107. },
  60108. /**
  60109. * Sets the current filter to "close ESM" (using the inverse of the
  60110. * exponential to prevent steep falloff artifacts).
  60111. */
  60112. set: function (value) {
  60113. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  60114. return;
  60115. }
  60116. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  60117. },
  60118. enumerable: true,
  60119. configurable: true
  60120. });
  60121. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  60122. /**
  60123. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  60124. * exponential to prevent steep falloff artifacts).
  60125. */
  60126. get: function () {
  60127. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  60128. },
  60129. /**
  60130. * Sets the current filter to fileterd "close ESM" (using the inverse of the
  60131. * exponential to prevent steep falloff artifacts).
  60132. */
  60133. set: function (value) {
  60134. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  60135. return;
  60136. }
  60137. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  60138. },
  60139. enumerable: true,
  60140. configurable: true
  60141. });
  60142. /**
  60143. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  60144. * 0 means strongest and 1 would means no shadow.
  60145. * @returns the darkness.
  60146. */
  60147. ShadowGenerator.prototype.getDarkness = function () {
  60148. return this._darkness;
  60149. };
  60150. /**
  60151. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  60152. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  60153. * @returns the shadow generator allowing fluent coding.
  60154. */
  60155. ShadowGenerator.prototype.setDarkness = function (darkness) {
  60156. if (darkness >= 1.0)
  60157. this._darkness = 1.0;
  60158. else if (darkness <= 0.0)
  60159. this._darkness = 0.0;
  60160. else
  60161. this._darkness = darkness;
  60162. return this;
  60163. };
  60164. /**
  60165. * Sets the ability to have transparent shadow (boolean).
  60166. * @param transparent True if transparent else False
  60167. * @returns the shadow generator allowing fluent coding
  60168. */
  60169. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  60170. this._transparencyShadow = transparent;
  60171. return this;
  60172. };
  60173. /**
  60174. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  60175. * @returns The render target texture if present otherwise, null
  60176. */
  60177. ShadowGenerator.prototype.getShadowMap = function () {
  60178. return this._shadowMap;
  60179. };
  60180. /**
  60181. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  60182. * @returns The render target texture if the shadow map is present otherwise, null
  60183. */
  60184. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  60185. if (this._shadowMap2) {
  60186. return this._shadowMap2;
  60187. }
  60188. return this._shadowMap;
  60189. };
  60190. /**
  60191. * Helper function to add a mesh and its descendants to the list of shadow casters.
  60192. * @param mesh Mesh to add
  60193. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  60194. * @returns the Shadow Generator itself
  60195. */
  60196. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  60197. if (includeDescendants === void 0) { includeDescendants = true; }
  60198. if (!this._shadowMap) {
  60199. return this;
  60200. }
  60201. if (!this._shadowMap.renderList) {
  60202. this._shadowMap.renderList = [];
  60203. }
  60204. this._shadowMap.renderList.push(mesh);
  60205. if (includeDescendants) {
  60206. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  60207. }
  60208. return this;
  60209. var _a;
  60210. };
  60211. /**
  60212. * Helper function to remove a mesh and its descendants from the list of shadow casters
  60213. * @param mesh Mesh to remove
  60214. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  60215. * @returns the Shadow Generator itself
  60216. */
  60217. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  60218. if (includeDescendants === void 0) { includeDescendants = true; }
  60219. if (!this._shadowMap || !this._shadowMap.renderList) {
  60220. return this;
  60221. }
  60222. var index = this._shadowMap.renderList.indexOf(mesh);
  60223. if (index !== -1) {
  60224. this._shadowMap.renderList.splice(index, 1);
  60225. }
  60226. if (includeDescendants) {
  60227. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  60228. var child = _a[_i];
  60229. this.removeShadowCaster(child);
  60230. }
  60231. }
  60232. return this;
  60233. };
  60234. /**
  60235. * Returns the associated light object.
  60236. * @returns the light generating the shadow
  60237. */
  60238. ShadowGenerator.prototype.getLight = function () {
  60239. return this._light;
  60240. };
  60241. ShadowGenerator.prototype._initializeGenerator = function () {
  60242. this._light._markMeshesAsLightDirty();
  60243. this._initializeShadowMap();
  60244. };
  60245. ShadowGenerator.prototype._initializeShadowMap = function () {
  60246. var _this = this;
  60247. // Render target
  60248. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  60249. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60250. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60251. this._shadowMap.anisotropicFilteringLevel = 1;
  60252. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  60253. this._shadowMap.renderParticles = false;
  60254. this._shadowMap.ignoreCameraViewport = true;
  60255. // Record Face Index before render.
  60256. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  60257. _this._currentFaceIndex = faceIndex;
  60258. });
  60259. // Custom render function.
  60260. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  60261. // Blur if required afer render.
  60262. this._shadowMap.onAfterUnbindObservable.add(function () {
  60263. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  60264. return;
  60265. }
  60266. var shadowMap = _this.getShadowMapForRendering();
  60267. if (shadowMap) {
  60268. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  60269. }
  60270. });
  60271. // Clear according to the chosen filter.
  60272. this._shadowMap.onClearObservable.add(function (engine) {
  60273. if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  60274. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  60275. }
  60276. else {
  60277. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  60278. }
  60279. });
  60280. };
  60281. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  60282. var _this = this;
  60283. var engine = this._scene.getEngine();
  60284. var targetSize = this._mapSize / this.blurScale;
  60285. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  60286. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  60287. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60288. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60289. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  60290. }
  60291. if (this.useKernelBlur) {
  60292. 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);
  60293. this._kernelBlurXPostprocess.width = targetSize;
  60294. this._kernelBlurXPostprocess.height = targetSize;
  60295. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  60296. effect.setTexture("textureSampler", _this._shadowMap);
  60297. });
  60298. 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);
  60299. this._kernelBlurXPostprocess.autoClear = false;
  60300. this._kernelBlurYPostprocess.autoClear = false;
  60301. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  60302. this._kernelBlurXPostprocess.packedFloat = true;
  60303. this._kernelBlurYPostprocess.packedFloat = true;
  60304. }
  60305. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  60306. }
  60307. else {
  60308. 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);
  60309. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  60310. effect.setFloat2("screenSize", targetSize, targetSize);
  60311. effect.setTexture("textureSampler", _this._shadowMap);
  60312. });
  60313. this._boxBlurPostprocess.autoClear = false;
  60314. this._blurPostProcesses = [this._boxBlurPostprocess];
  60315. }
  60316. };
  60317. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  60318. var index;
  60319. var engine = this._scene.getEngine();
  60320. if (depthOnlySubMeshes.length) {
  60321. engine.setColorWrite(false);
  60322. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  60323. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  60324. }
  60325. engine.setColorWrite(true);
  60326. }
  60327. for (index = 0; index < opaqueSubMeshes.length; index++) {
  60328. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  60329. }
  60330. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  60331. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  60332. }
  60333. if (this._transparencyShadow) {
  60334. for (index = 0; index < transparentSubMeshes.length; index++) {
  60335. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  60336. }
  60337. }
  60338. };
  60339. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  60340. var _this = this;
  60341. var mesh = subMesh.getRenderingMesh();
  60342. var scene = this._scene;
  60343. var engine = scene.getEngine();
  60344. var material = subMesh.getMaterial();
  60345. if (!material) {
  60346. return;
  60347. }
  60348. // Culling
  60349. engine.setState(material.backFaceCulling);
  60350. // Managing instances
  60351. var batch = mesh._getInstancesRenderList(subMesh._id);
  60352. if (batch.mustReturn) {
  60353. return;
  60354. }
  60355. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  60356. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  60357. engine.enableEffect(this._effect);
  60358. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  60359. this._effect.setFloat2("biasAndScale", this.bias, this.depthScale);
  60360. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  60361. this._effect.setVector3("lightPosition", this.getLight().position);
  60362. if (scene.activeCamera) {
  60363. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  60364. }
  60365. // Alpha test
  60366. if (material && material.needAlphaTesting()) {
  60367. var alphaTexture = material.getAlphaTestTexture();
  60368. if (alphaTexture) {
  60369. this._effect.setTexture("diffuseSampler", alphaTexture);
  60370. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  60371. }
  60372. }
  60373. // Bones
  60374. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  60375. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  60376. }
  60377. if (this.forceBackFacesOnly) {
  60378. engine.setState(true, 0, false, true);
  60379. }
  60380. // Draw
  60381. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  60382. if (this.forceBackFacesOnly) {
  60383. engine.setState(true, 0, false, false);
  60384. }
  60385. }
  60386. else {
  60387. // Need to reset refresh rate of the shadowMap
  60388. if (this._shadowMap) {
  60389. this._shadowMap.resetRefreshCounter();
  60390. }
  60391. }
  60392. };
  60393. ShadowGenerator.prototype._applyFilterValues = function () {
  60394. if (!this._shadowMap) {
  60395. return;
  60396. }
  60397. if (this.filter === ShadowGenerator.FILTER_NONE) {
  60398. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  60399. }
  60400. else {
  60401. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  60402. }
  60403. };
  60404. /**
  60405. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  60406. * @param onCompiled Callback triggered at the and of the effects compilation
  60407. * @param options Sets of optional options forcing the compilation with different modes
  60408. */
  60409. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  60410. var _this = this;
  60411. var localOptions = __assign({ useInstances: false }, options);
  60412. var shadowMap = this.getShadowMap();
  60413. if (!shadowMap) {
  60414. if (onCompiled) {
  60415. onCompiled(this);
  60416. }
  60417. return;
  60418. }
  60419. var renderList = shadowMap.renderList;
  60420. if (!renderList) {
  60421. if (onCompiled) {
  60422. onCompiled(this);
  60423. }
  60424. return;
  60425. }
  60426. var subMeshes = new Array();
  60427. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  60428. var mesh = renderList_1[_i];
  60429. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  60430. }
  60431. if (subMeshes.length === 0) {
  60432. if (onCompiled) {
  60433. onCompiled(this);
  60434. }
  60435. return;
  60436. }
  60437. var currentIndex = 0;
  60438. var checkReady = function () {
  60439. if (!_this._scene || !_this._scene.getEngine()) {
  60440. return;
  60441. }
  60442. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  60443. currentIndex++;
  60444. if (currentIndex >= subMeshes.length) {
  60445. if (onCompiled) {
  60446. onCompiled(_this);
  60447. }
  60448. return;
  60449. }
  60450. }
  60451. setTimeout(checkReady, 16);
  60452. };
  60453. checkReady();
  60454. };
  60455. /**
  60456. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  60457. * @param options Sets of optional options forcing the compilation with different modes
  60458. * @returns A promise that resolves when the compilation completes
  60459. */
  60460. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  60461. var _this = this;
  60462. return new Promise(function (resolve) {
  60463. _this.forceCompilation(function () {
  60464. resolve();
  60465. }, options);
  60466. });
  60467. };
  60468. /**
  60469. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  60470. * @param subMesh The submesh we want to render in the shadow map
  60471. * @param useInstances Defines wether will draw in the map using instances
  60472. * @returns true if ready otherwise, false
  60473. */
  60474. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  60475. var defines = [];
  60476. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  60477. defines.push("#define FLOAT");
  60478. }
  60479. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  60480. defines.push("#define ESM");
  60481. }
  60482. var attribs = [BABYLON.VertexBuffer.PositionKind];
  60483. var mesh = subMesh.getMesh();
  60484. var material = subMesh.getMaterial();
  60485. // Alpha test
  60486. if (material && material.needAlphaTesting()) {
  60487. var alphaTexture = material.getAlphaTestTexture();
  60488. if (alphaTexture) {
  60489. defines.push("#define ALPHATEST");
  60490. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  60491. attribs.push(BABYLON.VertexBuffer.UVKind);
  60492. defines.push("#define UV1");
  60493. }
  60494. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  60495. if (alphaTexture.coordinatesIndex === 1) {
  60496. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  60497. defines.push("#define UV2");
  60498. }
  60499. }
  60500. }
  60501. }
  60502. // Bones
  60503. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  60504. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  60505. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  60506. if (mesh.numBoneInfluencers > 4) {
  60507. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  60508. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  60509. }
  60510. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  60511. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  60512. }
  60513. else {
  60514. defines.push("#define NUM_BONE_INFLUENCERS 0");
  60515. }
  60516. // Instances
  60517. if (useInstances) {
  60518. defines.push("#define INSTANCES");
  60519. attribs.push("world0");
  60520. attribs.push("world1");
  60521. attribs.push("world2");
  60522. attribs.push("world3");
  60523. }
  60524. // Get correct effect
  60525. var join = defines.join("\n");
  60526. if (this._cachedDefines !== join) {
  60527. this._cachedDefines = join;
  60528. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues", "biasAndScale"], ["diffuseSampler"], join);
  60529. }
  60530. if (!this._effect.isReady()) {
  60531. return false;
  60532. }
  60533. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  60534. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  60535. this._initializeBlurRTTAndPostProcesses();
  60536. }
  60537. }
  60538. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  60539. return false;
  60540. }
  60541. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  60542. return false;
  60543. }
  60544. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  60545. return false;
  60546. }
  60547. return true;
  60548. };
  60549. /**
  60550. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  60551. * @param defines Defines of the material we want to update
  60552. * @param lightIndex Index of the light in the enabled light list of the material
  60553. */
  60554. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  60555. var scene = this._scene;
  60556. var light = this._light;
  60557. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  60558. return;
  60559. }
  60560. defines["SHADOW" + lightIndex] = true;
  60561. if (this.usePoissonSampling) {
  60562. defines["SHADOWPCF" + lightIndex] = true;
  60563. }
  60564. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  60565. defines["SHADOWESM" + lightIndex] = true;
  60566. }
  60567. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  60568. defines["SHADOWCLOSEESM" + lightIndex] = true;
  60569. }
  60570. if (light.needCube()) {
  60571. defines["SHADOWCUBE" + lightIndex] = true;
  60572. }
  60573. };
  60574. /**
  60575. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  60576. * defined in the generator but impacting the effect).
  60577. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  60578. * @param effect The effect we are binfing the information for
  60579. */
  60580. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  60581. var light = this._light;
  60582. var scene = this._scene;
  60583. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  60584. return;
  60585. }
  60586. var camera = scene.activeCamera;
  60587. if (!camera) {
  60588. return;
  60589. }
  60590. var shadowMap = this.getShadowMap();
  60591. if (!shadowMap) {
  60592. return;
  60593. }
  60594. if (!light.needCube()) {
  60595. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  60596. }
  60597. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  60598. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  60599. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  60600. };
  60601. /**
  60602. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  60603. * (eq to shadow prjection matrix * light transform matrix)
  60604. * @returns The transform matrix used to create the shadow map
  60605. */
  60606. ShadowGenerator.prototype.getTransformMatrix = function () {
  60607. var scene = this._scene;
  60608. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  60609. return this._transformMatrix;
  60610. }
  60611. this._currentRenderID = scene.getRenderId();
  60612. this._currentFaceIndexCache = this._currentFaceIndex;
  60613. var lightPosition = this._light.position;
  60614. if (this._light.computeTransformedInformation()) {
  60615. lightPosition = this._light.transformedPosition;
  60616. }
  60617. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  60618. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  60619. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  60620. }
  60621. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  60622. this._cachedPosition = lightPosition.clone();
  60623. this._cachedDirection = this._lightDirection.clone();
  60624. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  60625. var shadowMap = this.getShadowMap();
  60626. if (shadowMap) {
  60627. var renderList = shadowMap.renderList;
  60628. if (renderList) {
  60629. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  60630. }
  60631. }
  60632. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  60633. }
  60634. return this._transformMatrix;
  60635. };
  60636. /**
  60637. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  60638. * Cube and 2D textures for instance.
  60639. */
  60640. ShadowGenerator.prototype.recreateShadowMap = function () {
  60641. var shadowMap = this._shadowMap;
  60642. if (!shadowMap) {
  60643. return;
  60644. }
  60645. // Track render list.
  60646. var renderList = shadowMap.renderList;
  60647. // Clean up existing data.
  60648. this._disposeRTTandPostProcesses();
  60649. // Reinitializes.
  60650. this._initializeGenerator();
  60651. // Reaffect the filter to ensure a correct fallback if necessary.
  60652. this.filter = this.filter;
  60653. // Reaffect the filter.
  60654. this._applyFilterValues();
  60655. // Reaffect Render List.
  60656. this._shadowMap.renderList = renderList;
  60657. };
  60658. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  60659. if (this._shadowMap2) {
  60660. this._shadowMap2.dispose();
  60661. this._shadowMap2 = null;
  60662. }
  60663. if (this._boxBlurPostprocess) {
  60664. this._boxBlurPostprocess.dispose();
  60665. this._boxBlurPostprocess = null;
  60666. }
  60667. if (this._kernelBlurXPostprocess) {
  60668. this._kernelBlurXPostprocess.dispose();
  60669. this._kernelBlurXPostprocess = null;
  60670. }
  60671. if (this._kernelBlurYPostprocess) {
  60672. this._kernelBlurYPostprocess.dispose();
  60673. this._kernelBlurYPostprocess = null;
  60674. }
  60675. this._blurPostProcesses = [];
  60676. };
  60677. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  60678. if (this._shadowMap) {
  60679. this._shadowMap.dispose();
  60680. this._shadowMap = null;
  60681. }
  60682. this._disposeBlurPostProcesses();
  60683. };
  60684. /**
  60685. * Disposes the ShadowGenerator.
  60686. * Returns nothing.
  60687. */
  60688. ShadowGenerator.prototype.dispose = function () {
  60689. this._disposeRTTandPostProcesses();
  60690. if (this._light) {
  60691. this._light._shadowGenerator = null;
  60692. this._light._markMeshesAsLightDirty();
  60693. }
  60694. };
  60695. /**
  60696. * Serializes the shadow generator setup to a json object.
  60697. * @returns The serialized JSON object
  60698. */
  60699. ShadowGenerator.prototype.serialize = function () {
  60700. var serializationObject = {};
  60701. var shadowMap = this.getShadowMap();
  60702. if (!shadowMap) {
  60703. return serializationObject;
  60704. }
  60705. serializationObject.lightId = this._light.id;
  60706. serializationObject.mapSize = shadowMap.getRenderSize();
  60707. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  60708. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  60709. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  60710. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  60711. serializationObject.usePoissonSampling = this.usePoissonSampling;
  60712. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  60713. serializationObject.depthScale = this.depthScale;
  60714. serializationObject.darkness = this.getDarkness();
  60715. serializationObject.blurBoxOffset = this.blurBoxOffset;
  60716. serializationObject.blurKernel = this.blurKernel;
  60717. serializationObject.blurScale = this.blurScale;
  60718. serializationObject.useKernelBlur = this.useKernelBlur;
  60719. serializationObject.transparencyShadow = this._transparencyShadow;
  60720. serializationObject.renderList = [];
  60721. if (shadowMap.renderList) {
  60722. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  60723. var mesh = shadowMap.renderList[meshIndex];
  60724. serializationObject.renderList.push(mesh.id);
  60725. }
  60726. }
  60727. return serializationObject;
  60728. };
  60729. /**
  60730. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  60731. * @param parsedShadowGenerator The JSON object to parse
  60732. * @param scene The scene to create the shadow map for
  60733. * @returns The parsed shadow generator
  60734. */
  60735. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  60736. //casting to point light, as light is missing the position attr and typescript complains.
  60737. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  60738. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  60739. var shadowMap = shadowGenerator.getShadowMap();
  60740. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  60741. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  60742. meshes.forEach(function (mesh) {
  60743. if (!shadowMap) {
  60744. return;
  60745. }
  60746. if (!shadowMap.renderList) {
  60747. shadowMap.renderList = [];
  60748. }
  60749. shadowMap.renderList.push(mesh);
  60750. });
  60751. }
  60752. if (parsedShadowGenerator.usePoissonSampling) {
  60753. shadowGenerator.usePoissonSampling = true;
  60754. }
  60755. else if (parsedShadowGenerator.useExponentialShadowMap) {
  60756. shadowGenerator.useExponentialShadowMap = true;
  60757. }
  60758. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  60759. shadowGenerator.useBlurExponentialShadowMap = true;
  60760. }
  60761. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  60762. shadowGenerator.useCloseExponentialShadowMap = true;
  60763. }
  60764. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  60765. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  60766. }
  60767. else if (parsedShadowGenerator.useVarianceShadowMap) {
  60768. shadowGenerator.useExponentialShadowMap = true;
  60769. }
  60770. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  60771. shadowGenerator.useBlurExponentialShadowMap = true;
  60772. }
  60773. if (parsedShadowGenerator.depthScale) {
  60774. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  60775. }
  60776. if (parsedShadowGenerator.blurScale) {
  60777. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  60778. }
  60779. if (parsedShadowGenerator.blurBoxOffset) {
  60780. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  60781. }
  60782. if (parsedShadowGenerator.useKernelBlur) {
  60783. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  60784. }
  60785. if (parsedShadowGenerator.blurKernel) {
  60786. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  60787. }
  60788. if (parsedShadowGenerator.bias !== undefined) {
  60789. shadowGenerator.bias = parsedShadowGenerator.bias;
  60790. }
  60791. if (parsedShadowGenerator.darkness) {
  60792. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  60793. }
  60794. if (parsedShadowGenerator.transparencyShadow) {
  60795. shadowGenerator.setTransparencyShadow(true);
  60796. }
  60797. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  60798. return shadowGenerator;
  60799. };
  60800. ShadowGenerator._FILTER_NONE = 0;
  60801. ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP = 1;
  60802. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  60803. ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  60804. ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  60805. ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  60806. return ShadowGenerator;
  60807. }());
  60808. BABYLON.ShadowGenerator = ShadowGenerator;
  60809. })(BABYLON || (BABYLON = {}));
  60810. //# sourceMappingURL=babylon.shadowGenerator.js.map
  60811. var BABYLON;
  60812. (function (BABYLON) {
  60813. var DefaultLoadingScreen = /** @class */ (function () {
  60814. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  60815. if (_loadingText === void 0) { _loadingText = ""; }
  60816. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  60817. var _this = this;
  60818. this._renderingCanvas = _renderingCanvas;
  60819. this._loadingText = _loadingText;
  60820. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  60821. // Resize
  60822. this._resizeLoadingUI = function () {
  60823. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  60824. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  60825. if (!_this._loadingDiv) {
  60826. return;
  60827. }
  60828. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  60829. _this._loadingDiv.style.left = canvasRect.left + "px";
  60830. _this._loadingDiv.style.top = canvasRect.top + "px";
  60831. _this._loadingDiv.style.width = canvasRect.width + "px";
  60832. _this._loadingDiv.style.height = canvasRect.height + "px";
  60833. };
  60834. }
  60835. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  60836. if (this._loadingDiv) {
  60837. // Do not add a loading screen if there is already one
  60838. return;
  60839. }
  60840. this._loadingDiv = document.createElement("div");
  60841. this._loadingDiv.id = "babylonjsLoadingDiv";
  60842. this._loadingDiv.style.opacity = "0";
  60843. this._loadingDiv.style.transition = "opacity 1.5s ease";
  60844. this._loadingDiv.style.pointerEvents = "none";
  60845. // Loading text
  60846. this._loadingTextDiv = document.createElement("div");
  60847. this._loadingTextDiv.style.position = "absolute";
  60848. this._loadingTextDiv.style.left = "0";
  60849. this._loadingTextDiv.style.top = "50%";
  60850. this._loadingTextDiv.style.marginTop = "80px";
  60851. this._loadingTextDiv.style.width = "100%";
  60852. this._loadingTextDiv.style.height = "20px";
  60853. this._loadingTextDiv.style.fontFamily = "Arial";
  60854. this._loadingTextDiv.style.fontSize = "14px";
  60855. this._loadingTextDiv.style.color = "white";
  60856. this._loadingTextDiv.style.textAlign = "center";
  60857. this._loadingTextDiv.innerHTML = "Loading";
  60858. this._loadingDiv.appendChild(this._loadingTextDiv);
  60859. //set the predefined text
  60860. this._loadingTextDiv.innerHTML = this._loadingText;
  60861. // Generating keyframes
  60862. var style = document.createElement('style');
  60863. style.type = 'text/css';
  60864. 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 }";
  60865. style.innerHTML = keyFrames;
  60866. document.getElementsByTagName('head')[0].appendChild(style);
  60867. // Loading img
  60868. var imgBack = new Image();
  60869. 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";
  60870. imgBack.style.position = "absolute";
  60871. imgBack.style.left = "50%";
  60872. imgBack.style.top = "50%";
  60873. imgBack.style.marginLeft = "-60px";
  60874. imgBack.style.marginTop = "-60px";
  60875. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  60876. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  60877. imgBack.style.transformOrigin = "50% 50%";
  60878. imgBack.style.webkitTransformOrigin = "50% 50%";
  60879. this._loadingDiv.appendChild(imgBack);
  60880. this._resizeLoadingUI();
  60881. window.addEventListener("resize", this._resizeLoadingUI);
  60882. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  60883. document.body.appendChild(this._loadingDiv);
  60884. this._loadingDiv.style.opacity = "1";
  60885. };
  60886. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  60887. var _this = this;
  60888. if (!this._loadingDiv) {
  60889. return;
  60890. }
  60891. var onTransitionEnd = function () {
  60892. if (!_this._loadingDiv) {
  60893. return;
  60894. }
  60895. document.body.removeChild(_this._loadingDiv);
  60896. window.removeEventListener("resize", _this._resizeLoadingUI);
  60897. _this._loadingDiv = null;
  60898. };
  60899. this._loadingDiv.style.opacity = "0";
  60900. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  60901. };
  60902. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  60903. set: function (text) {
  60904. this._loadingText = text;
  60905. if (this._loadingTextDiv) {
  60906. this._loadingTextDiv.innerHTML = this._loadingText;
  60907. }
  60908. },
  60909. enumerable: true,
  60910. configurable: true
  60911. });
  60912. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  60913. get: function () {
  60914. return this._loadingDivBackgroundColor;
  60915. },
  60916. set: function (color) {
  60917. this._loadingDivBackgroundColor = color;
  60918. if (!this._loadingDiv) {
  60919. return;
  60920. }
  60921. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  60922. },
  60923. enumerable: true,
  60924. configurable: true
  60925. });
  60926. return DefaultLoadingScreen;
  60927. }());
  60928. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  60929. })(BABYLON || (BABYLON = {}));
  60930. //# sourceMappingURL=babylon.loadingScreen.js.map
  60931. var BABYLON;
  60932. (function (BABYLON) {
  60933. var SceneLoaderProgressEvent = /** @class */ (function () {
  60934. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  60935. this.lengthComputable = lengthComputable;
  60936. this.loaded = loaded;
  60937. this.total = total;
  60938. }
  60939. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  60940. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  60941. };
  60942. return SceneLoaderProgressEvent;
  60943. }());
  60944. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  60945. var SceneLoader = /** @class */ (function () {
  60946. function SceneLoader() {
  60947. }
  60948. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  60949. get: function () {
  60950. return 0;
  60951. },
  60952. enumerable: true,
  60953. configurable: true
  60954. });
  60955. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  60956. get: function () {
  60957. return 1;
  60958. },
  60959. enumerable: true,
  60960. configurable: true
  60961. });
  60962. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  60963. get: function () {
  60964. return 2;
  60965. },
  60966. enumerable: true,
  60967. configurable: true
  60968. });
  60969. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  60970. get: function () {
  60971. return 3;
  60972. },
  60973. enumerable: true,
  60974. configurable: true
  60975. });
  60976. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  60977. get: function () {
  60978. return SceneLoader._ForceFullSceneLoadingForIncremental;
  60979. },
  60980. set: function (value) {
  60981. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  60982. },
  60983. enumerable: true,
  60984. configurable: true
  60985. });
  60986. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  60987. get: function () {
  60988. return SceneLoader._ShowLoadingScreen;
  60989. },
  60990. set: function (value) {
  60991. SceneLoader._ShowLoadingScreen = value;
  60992. },
  60993. enumerable: true,
  60994. configurable: true
  60995. });
  60996. Object.defineProperty(SceneLoader, "loggingLevel", {
  60997. get: function () {
  60998. return SceneLoader._loggingLevel;
  60999. },
  61000. set: function (value) {
  61001. SceneLoader._loggingLevel = value;
  61002. },
  61003. enumerable: true,
  61004. configurable: true
  61005. });
  61006. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  61007. get: function () {
  61008. return SceneLoader._CleanBoneMatrixWeights;
  61009. },
  61010. set: function (value) {
  61011. SceneLoader._CleanBoneMatrixWeights = value;
  61012. },
  61013. enumerable: true,
  61014. configurable: true
  61015. });
  61016. SceneLoader._getDefaultPlugin = function () {
  61017. return SceneLoader._registeredPlugins[".babylon"];
  61018. };
  61019. SceneLoader._getPluginForExtension = function (extension) {
  61020. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  61021. if (registeredPlugin) {
  61022. return registeredPlugin;
  61023. }
  61024. BABYLON.Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin.");
  61025. return SceneLoader._getDefaultPlugin();
  61026. };
  61027. SceneLoader._getPluginForDirectLoad = function (data) {
  61028. for (var extension in SceneLoader._registeredPlugins) {
  61029. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  61030. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  61031. return SceneLoader._registeredPlugins[extension];
  61032. }
  61033. }
  61034. return SceneLoader._getDefaultPlugin();
  61035. };
  61036. SceneLoader._getPluginForFilename = function (sceneFilename) {
  61037. if (sceneFilename.name) {
  61038. sceneFilename = sceneFilename.name;
  61039. }
  61040. var queryStringPosition = sceneFilename.indexOf("?");
  61041. if (queryStringPosition !== -1) {
  61042. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  61043. }
  61044. var dotPosition = sceneFilename.lastIndexOf(".");
  61045. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  61046. return SceneLoader._getPluginForExtension(extension);
  61047. };
  61048. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  61049. SceneLoader._getDirectLoad = function (sceneFilename) {
  61050. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  61051. return sceneFilename.substr(5);
  61052. }
  61053. return null;
  61054. };
  61055. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  61056. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  61057. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  61058. var plugin;
  61059. if (registeredPlugin.plugin.createPlugin) {
  61060. plugin = registeredPlugin.plugin.createPlugin();
  61061. }
  61062. else {
  61063. plugin = registeredPlugin.plugin;
  61064. }
  61065. var useArrayBuffer = registeredPlugin.isBinary;
  61066. var database;
  61067. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  61068. var dataCallback = function (data, responseURL) {
  61069. if (scene.isDisposed) {
  61070. onError("Scene has been disposed");
  61071. return;
  61072. }
  61073. scene.database = database;
  61074. onSuccess(plugin, data, responseURL);
  61075. };
  61076. var request = null;
  61077. var pluginDisposed = false;
  61078. var onDisposeObservable = plugin.onDisposeObservable;
  61079. if (onDisposeObservable) {
  61080. onDisposeObservable.add(function () {
  61081. pluginDisposed = true;
  61082. if (request) {
  61083. request.abort();
  61084. request = null;
  61085. }
  61086. onDispose();
  61087. });
  61088. }
  61089. var manifestChecked = function () {
  61090. if (pluginDisposed) {
  61091. return;
  61092. }
  61093. var url = rootUrl + sceneFilename;
  61094. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  61095. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  61096. } : undefined, database, useArrayBuffer, function (request, exception) {
  61097. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  61098. });
  61099. };
  61100. if (directLoad) {
  61101. dataCallback(directLoad);
  61102. return plugin;
  61103. }
  61104. if (rootUrl.indexOf("file:") === -1) {
  61105. if (scene.getEngine().enableOfflineSupport) {
  61106. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  61107. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  61108. }
  61109. else {
  61110. manifestChecked();
  61111. }
  61112. }
  61113. else {
  61114. var fileOrString = sceneFilename;
  61115. if (fileOrString.name) {
  61116. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  61117. }
  61118. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  61119. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  61120. }
  61121. else {
  61122. onError("Unable to find file named " + sceneFilename);
  61123. }
  61124. }
  61125. return plugin;
  61126. };
  61127. // Public functions
  61128. SceneLoader.GetPluginForExtension = function (extension) {
  61129. return SceneLoader._getPluginForExtension(extension).plugin;
  61130. };
  61131. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  61132. return !!SceneLoader._registeredPlugins[extension];
  61133. };
  61134. SceneLoader.RegisterPlugin = function (plugin) {
  61135. if (typeof plugin.extensions === "string") {
  61136. var extension = plugin.extensions;
  61137. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  61138. plugin: plugin,
  61139. isBinary: false
  61140. };
  61141. }
  61142. else {
  61143. var extensions = plugin.extensions;
  61144. Object.keys(extensions).forEach(function (extension) {
  61145. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  61146. plugin: plugin,
  61147. isBinary: extensions[extension].isBinary
  61148. };
  61149. });
  61150. }
  61151. };
  61152. /**
  61153. * Import meshes into a scene
  61154. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  61155. * @param rootUrl a string that defines the root url for scene and resources
  61156. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  61157. * @param scene the instance of BABYLON.Scene to append to
  61158. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  61159. * @param onProgress a callback with a progress event for each file being loaded
  61160. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  61161. * @param pluginExtension the extension used to determine the plugin
  61162. * @returns The loaded plugin
  61163. */
  61164. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  61165. if (onSuccess === void 0) { onSuccess = null; }
  61166. if (onProgress === void 0) { onProgress = null; }
  61167. if (onError === void 0) { onError = null; }
  61168. if (pluginExtension === void 0) { pluginExtension = null; }
  61169. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  61170. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  61171. return null;
  61172. }
  61173. var loadingToken = {};
  61174. scene._addPendingData(loadingToken);
  61175. var disposeHandler = function () {
  61176. scene._removePendingData(loadingToken);
  61177. };
  61178. var errorHandler = function (message, exception) {
  61179. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  61180. if (onError) {
  61181. onError(scene, errorMessage, exception);
  61182. }
  61183. else {
  61184. BABYLON.Tools.Error(errorMessage);
  61185. // should the exception be thrown?
  61186. }
  61187. disposeHandler();
  61188. };
  61189. var progressHandler = onProgress ? function (event) {
  61190. try {
  61191. onProgress(event);
  61192. }
  61193. catch (e) {
  61194. errorHandler("Error in onProgress callback", e);
  61195. }
  61196. } : undefined;
  61197. var successHandler = function (meshes, particleSystems, skeletons) {
  61198. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  61199. if (onSuccess) {
  61200. try {
  61201. onSuccess(meshes, particleSystems, skeletons);
  61202. }
  61203. catch (e) {
  61204. errorHandler("Error in onSuccess callback", e);
  61205. }
  61206. }
  61207. scene._removePendingData(loadingToken);
  61208. };
  61209. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  61210. if (plugin.rewriteRootURL) {
  61211. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  61212. }
  61213. if (sceneFilename === "") {
  61214. if (sceneFilename === "") {
  61215. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  61216. }
  61217. }
  61218. if (plugin.importMesh) {
  61219. var syncedPlugin = plugin;
  61220. var meshes = new Array();
  61221. var particleSystems = new Array();
  61222. var skeletons = new Array();
  61223. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  61224. return;
  61225. }
  61226. scene.loadingPluginName = plugin.name;
  61227. successHandler(meshes, particleSystems, skeletons);
  61228. }
  61229. else {
  61230. var asyncedPlugin = plugin;
  61231. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(function (result) {
  61232. scene.loadingPluginName = plugin.name;
  61233. successHandler(result.meshes, result.particleSystems, result.skeletons);
  61234. }).catch(function (error) {
  61235. errorHandler(error.message, error);
  61236. });
  61237. }
  61238. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  61239. };
  61240. /**
  61241. * Import meshes into a scene
  61242. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  61243. * @param rootUrl a string that defines the root url for scene and resources
  61244. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  61245. * @param scene the instance of BABYLON.Scene to append to
  61246. * @param onProgress a callback with a progress event for each file being loaded
  61247. * @param pluginExtension the extension used to determine the plugin
  61248. * @returns The loaded list of imported meshes, particleSystems, and skeletons
  61249. */
  61250. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  61251. if (onProgress === void 0) { onProgress = null; }
  61252. if (pluginExtension === void 0) { pluginExtension = null; }
  61253. return new Promise(function (resolve, reject) {
  61254. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  61255. resolve({
  61256. meshes: meshes,
  61257. particleSystems: particleSystems,
  61258. skeletons: skeletons
  61259. });
  61260. }, onProgress, function (scene, message, exception) {
  61261. reject(exception || new Error(message));
  61262. });
  61263. });
  61264. };
  61265. /**
  61266. * Load a scene
  61267. * @param rootUrl a string that defines the root url for scene and resources
  61268. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  61269. * @param engine is the instance of BABYLON.Engine to use to create the scene
  61270. * @param onSuccess a callback with the scene when import succeeds
  61271. * @param onProgress a callback with a progress event for each file being loaded
  61272. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  61273. * @param pluginExtension the extension used to determine the plugin
  61274. * @returns The loaded plugin
  61275. */
  61276. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  61277. if (onSuccess === void 0) { onSuccess = null; }
  61278. if (onProgress === void 0) { onProgress = null; }
  61279. if (onError === void 0) { onError = null; }
  61280. if (pluginExtension === void 0) { pluginExtension = null; }
  61281. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  61282. };
  61283. /**
  61284. * Load a scene
  61285. * @param rootUrl a string that defines the root url for scene and resources
  61286. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  61287. * @param engine is the instance of BABYLON.Engine to use to create the scene
  61288. * @param onProgress a callback with a progress event for each file being loaded
  61289. * @param pluginExtension the extension used to determine the plugin
  61290. * @returns The loaded scene
  61291. */
  61292. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  61293. if (onProgress === void 0) { onProgress = null; }
  61294. if (pluginExtension === void 0) { pluginExtension = null; }
  61295. return new Promise(function (resolve, reject) {
  61296. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  61297. resolve(scene);
  61298. }, onProgress, function (scene, message, exception) {
  61299. reject(exception || new Error(message));
  61300. }, pluginExtension);
  61301. });
  61302. };
  61303. /**
  61304. * Append a scene
  61305. * @param rootUrl a string that defines the root url for scene and resources
  61306. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  61307. * @param scene is the instance of BABYLON.Scene to append to
  61308. * @param onSuccess a callback with the scene when import succeeds
  61309. * @param onProgress a callback with a progress event for each file being loaded
  61310. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  61311. * @param pluginExtension the extension used to determine the plugin
  61312. * @returns The loaded plugin
  61313. */
  61314. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  61315. if (onSuccess === void 0) { onSuccess = null; }
  61316. if (onProgress === void 0) { onProgress = null; }
  61317. if (onError === void 0) { onError = null; }
  61318. if (pluginExtension === void 0) { pluginExtension = null; }
  61319. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  61320. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  61321. return null;
  61322. }
  61323. if (SceneLoader.ShowLoadingScreen) {
  61324. scene.getEngine().displayLoadingUI();
  61325. }
  61326. var loadingToken = {};
  61327. scene._addPendingData(loadingToken);
  61328. var disposeHandler = function () {
  61329. scene._removePendingData(loadingToken);
  61330. scene.getEngine().hideLoadingUI();
  61331. };
  61332. var errorHandler = function (message, exception) {
  61333. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  61334. if (onError) {
  61335. onError(scene, errorMessage, exception);
  61336. }
  61337. else {
  61338. BABYLON.Tools.Error(errorMessage);
  61339. // should the exception be thrown?
  61340. }
  61341. disposeHandler();
  61342. };
  61343. var progressHandler = onProgress ? function (event) {
  61344. try {
  61345. onProgress(event);
  61346. }
  61347. catch (e) {
  61348. errorHandler("Error in onProgress callback", e);
  61349. }
  61350. } : undefined;
  61351. var successHandler = function () {
  61352. if (onSuccess) {
  61353. try {
  61354. onSuccess(scene);
  61355. }
  61356. catch (e) {
  61357. errorHandler("Error in onSuccess callback", e);
  61358. }
  61359. }
  61360. scene._removePendingData(loadingToken);
  61361. };
  61362. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  61363. if (sceneFilename === "") {
  61364. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  61365. }
  61366. if (plugin.load) {
  61367. var syncedPlugin = plugin;
  61368. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  61369. return;
  61370. }
  61371. scene.loadingPluginName = plugin.name;
  61372. successHandler();
  61373. }
  61374. else {
  61375. var asyncedPlugin = plugin;
  61376. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(function () {
  61377. scene.loadingPluginName = plugin.name;
  61378. successHandler();
  61379. }).catch(function (error) {
  61380. errorHandler(error.message, error);
  61381. });
  61382. }
  61383. if (SceneLoader.ShowLoadingScreen) {
  61384. scene.executeWhenReady(function () {
  61385. scene.getEngine().hideLoadingUI();
  61386. });
  61387. }
  61388. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  61389. };
  61390. /**
  61391. * Append a scene
  61392. * @param rootUrl a string that defines the root url for scene and resources
  61393. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  61394. * @param scene is the instance of BABYLON.Scene to append to
  61395. * @param onProgress a callback with a progress event for each file being loaded
  61396. * @param pluginExtension the extension used to determine the plugin
  61397. * @returns The given scene
  61398. */
  61399. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  61400. if (onProgress === void 0) { onProgress = null; }
  61401. if (pluginExtension === void 0) { pluginExtension = null; }
  61402. return new Promise(function (resolve, reject) {
  61403. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  61404. resolve(scene);
  61405. }, onProgress, function (scene, message, exception) {
  61406. reject(exception || new Error(message));
  61407. }, pluginExtension);
  61408. });
  61409. };
  61410. /**
  61411. * Load a scene into an asset container
  61412. * @param rootUrl a string that defines the root url for scene and resources
  61413. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  61414. * @param scene is the instance of BABYLON.Scene to append to
  61415. * @param onSuccess a callback with the scene when import succeeds
  61416. * @param onProgress a callback with a progress event for each file being loaded
  61417. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  61418. * @param pluginExtension the extension used to determine the plugin
  61419. * @returns The loaded plugin
  61420. */
  61421. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  61422. if (onSuccess === void 0) { onSuccess = null; }
  61423. if (onProgress === void 0) { onProgress = null; }
  61424. if (onError === void 0) { onError = null; }
  61425. if (pluginExtension === void 0) { pluginExtension = null; }
  61426. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  61427. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  61428. return null;
  61429. }
  61430. var loadingToken = {};
  61431. scene._addPendingData(loadingToken);
  61432. var disposeHandler = function () {
  61433. scene._removePendingData(loadingToken);
  61434. };
  61435. var errorHandler = function (message, exception) {
  61436. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  61437. if (onError) {
  61438. onError(scene, errorMessage, exception);
  61439. }
  61440. else {
  61441. BABYLON.Tools.Error(errorMessage);
  61442. // should the exception be thrown?
  61443. }
  61444. disposeHandler();
  61445. };
  61446. var progressHandler = onProgress ? function (event) {
  61447. try {
  61448. onProgress(event);
  61449. }
  61450. catch (e) {
  61451. errorHandler("Error in onProgress callback", e);
  61452. }
  61453. } : undefined;
  61454. var successHandler = function (assets) {
  61455. if (onSuccess) {
  61456. try {
  61457. onSuccess(assets);
  61458. }
  61459. catch (e) {
  61460. errorHandler("Error in onSuccess callback", e);
  61461. }
  61462. }
  61463. scene._removePendingData(loadingToken);
  61464. };
  61465. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  61466. if (plugin.loadAssetContainer) {
  61467. var syncedPlugin = plugin;
  61468. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  61469. if (!assetContainer) {
  61470. return;
  61471. }
  61472. scene.loadingPluginName = plugin.name;
  61473. successHandler(assetContainer);
  61474. }
  61475. else if (plugin.loadAssetContainerAsync) {
  61476. var asyncedPlugin = plugin;
  61477. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(function (assetContainer) {
  61478. scene.loadingPluginName = plugin.name;
  61479. successHandler(assetContainer);
  61480. }).catch(function (error) {
  61481. errorHandler(error.message, error);
  61482. });
  61483. }
  61484. else {
  61485. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  61486. }
  61487. if (SceneLoader.ShowLoadingScreen) {
  61488. scene.executeWhenReady(function () {
  61489. scene.getEngine().hideLoadingUI();
  61490. });
  61491. }
  61492. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  61493. };
  61494. /**
  61495. * Load a scene into an asset container
  61496. * @param rootUrl a string that defines the root url for scene and resources
  61497. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  61498. * @param scene is the instance of BABYLON.Scene to append to
  61499. * @param onProgress a callback with a progress event for each file being loaded
  61500. * @param pluginExtension the extension used to determine the plugin
  61501. * @returns The loaded asset container
  61502. */
  61503. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  61504. if (onProgress === void 0) { onProgress = null; }
  61505. if (pluginExtension === void 0) { pluginExtension = null; }
  61506. return new Promise(function (resolve, reject) {
  61507. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  61508. resolve(assetContainer);
  61509. }, onProgress, function (scene, message, exception) {
  61510. reject(exception || new Error(message));
  61511. }, pluginExtension);
  61512. });
  61513. };
  61514. // Flags
  61515. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  61516. SceneLoader._ShowLoadingScreen = true;
  61517. SceneLoader._CleanBoneMatrixWeights = false;
  61518. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  61519. // Members
  61520. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  61521. SceneLoader._registeredPlugins = {};
  61522. return SceneLoader;
  61523. }());
  61524. BABYLON.SceneLoader = SceneLoader;
  61525. ;
  61526. })(BABYLON || (BABYLON = {}));
  61527. //# sourceMappingURL=babylon.sceneLoader.js.map
  61528. var BABYLON;
  61529. (function (BABYLON) {
  61530. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  61531. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  61532. var parsedMaterial = parsedData.materials[index];
  61533. if (parsedMaterial.id === id) {
  61534. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  61535. }
  61536. }
  61537. return null;
  61538. };
  61539. var isDescendantOf = function (mesh, names, hierarchyIds) {
  61540. for (var i in names) {
  61541. if (mesh.name === names[i]) {
  61542. hierarchyIds.push(mesh.id);
  61543. return true;
  61544. }
  61545. }
  61546. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  61547. hierarchyIds.push(mesh.id);
  61548. return true;
  61549. }
  61550. return false;
  61551. };
  61552. var logOperation = function (operation, producer) {
  61553. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  61554. };
  61555. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  61556. if (addToScene === void 0) { addToScene = false; }
  61557. var container = new BABYLON.AssetContainer(scene);
  61558. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  61559. // when SceneLoader.debugLogging = true (default), or exception encountered.
  61560. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  61561. // and avoid problems with multiple concurrent .babylon loads.
  61562. var log = "importScene has failed JSON parse";
  61563. try {
  61564. var parsedData = JSON.parse(data);
  61565. log = "";
  61566. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  61567. var index;
  61568. var cache;
  61569. // Lights
  61570. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  61571. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  61572. var parsedLight = parsedData.lights[index];
  61573. var light = BABYLON.Light.Parse(parsedLight, scene);
  61574. if (light) {
  61575. container.lights.push(light);
  61576. log += (index === 0 ? "\n\tLights:" : "");
  61577. log += "\n\t\t" + light.toString(fullDetails);
  61578. }
  61579. }
  61580. }
  61581. // Animations
  61582. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  61583. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  61584. var parsedAnimation = parsedData.animations[index];
  61585. var animation = BABYLON.Animation.Parse(parsedAnimation);
  61586. scene.animations.push(animation);
  61587. container.animations.push(animation);
  61588. log += (index === 0 ? "\n\tAnimations:" : "");
  61589. log += "\n\t\t" + animation.toString(fullDetails);
  61590. }
  61591. }
  61592. // Materials
  61593. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  61594. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  61595. var parsedMaterial = parsedData.materials[index];
  61596. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  61597. container.materials.push(mat);
  61598. log += (index === 0 ? "\n\tMaterials:" : "");
  61599. log += "\n\t\t" + mat.toString(fullDetails);
  61600. }
  61601. }
  61602. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  61603. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  61604. var parsedMultiMaterial = parsedData.multiMaterials[index];
  61605. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  61606. container.multiMaterials.push(mmat);
  61607. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  61608. log += "\n\t\t" + mmat.toString(fullDetails);
  61609. }
  61610. }
  61611. // Morph targets
  61612. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  61613. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  61614. var managerData = _a[_i];
  61615. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  61616. }
  61617. }
  61618. // Skeletons
  61619. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  61620. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  61621. var parsedSkeleton = parsedData.skeletons[index];
  61622. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  61623. container.skeletons.push(skeleton);
  61624. log += (index === 0 ? "\n\tSkeletons:" : "");
  61625. log += "\n\t\t" + skeleton.toString(fullDetails);
  61626. }
  61627. }
  61628. // Geometries
  61629. var geometries = parsedData.geometries;
  61630. if (geometries !== undefined && geometries !== null) {
  61631. var addedGeometry = new Array();
  61632. // Boxes
  61633. var boxes = geometries.boxes;
  61634. if (boxes !== undefined && boxes !== null) {
  61635. for (index = 0, cache = boxes.length; index < cache; index++) {
  61636. var parsedBox = boxes[index];
  61637. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  61638. }
  61639. }
  61640. // Spheres
  61641. var spheres = geometries.spheres;
  61642. if (spheres !== undefined && spheres !== null) {
  61643. for (index = 0, cache = spheres.length; index < cache; index++) {
  61644. var parsedSphere = spheres[index];
  61645. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  61646. }
  61647. }
  61648. // Cylinders
  61649. var cylinders = geometries.cylinders;
  61650. if (cylinders !== undefined && cylinders !== null) {
  61651. for (index = 0, cache = cylinders.length; index < cache; index++) {
  61652. var parsedCylinder = cylinders[index];
  61653. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  61654. }
  61655. }
  61656. // Toruses
  61657. var toruses = geometries.toruses;
  61658. if (toruses !== undefined && toruses !== null) {
  61659. for (index = 0, cache = toruses.length; index < cache; index++) {
  61660. var parsedTorus = toruses[index];
  61661. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  61662. }
  61663. }
  61664. // Grounds
  61665. var grounds = geometries.grounds;
  61666. if (grounds !== undefined && grounds !== null) {
  61667. for (index = 0, cache = grounds.length; index < cache; index++) {
  61668. var parsedGround = grounds[index];
  61669. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  61670. }
  61671. }
  61672. // Planes
  61673. var planes = geometries.planes;
  61674. if (planes !== undefined && planes !== null) {
  61675. for (index = 0, cache = planes.length; index < cache; index++) {
  61676. var parsedPlane = planes[index];
  61677. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  61678. }
  61679. }
  61680. // TorusKnots
  61681. var torusKnots = geometries.torusKnots;
  61682. if (torusKnots !== undefined && torusKnots !== null) {
  61683. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  61684. var parsedTorusKnot = torusKnots[index];
  61685. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  61686. }
  61687. }
  61688. // VertexData
  61689. var vertexData = geometries.vertexData;
  61690. if (vertexData !== undefined && vertexData !== null) {
  61691. for (index = 0, cache = vertexData.length; index < cache; index++) {
  61692. var parsedVertexData = vertexData[index];
  61693. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  61694. }
  61695. }
  61696. addedGeometry.forEach(function (g) {
  61697. if (g) {
  61698. container.geometries.push(g);
  61699. }
  61700. });
  61701. }
  61702. // Transform nodes
  61703. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  61704. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  61705. var parsedTransformNode = parsedData.transformNodes[index];
  61706. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  61707. container.transformNodes.push(node);
  61708. }
  61709. }
  61710. // Meshes
  61711. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  61712. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  61713. var parsedMesh = parsedData.meshes[index];
  61714. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  61715. container.meshes.push(mesh);
  61716. log += (index === 0 ? "\n\tMeshes:" : "");
  61717. log += "\n\t\t" + mesh.toString(fullDetails);
  61718. }
  61719. }
  61720. // Cameras
  61721. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  61722. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  61723. var parsedCamera = parsedData.cameras[index];
  61724. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  61725. container.cameras.push(camera);
  61726. log += (index === 0 ? "\n\tCameras:" : "");
  61727. log += "\n\t\t" + camera.toString(fullDetails);
  61728. }
  61729. }
  61730. // Browsing all the graph to connect the dots
  61731. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  61732. var camera = scene.cameras[index];
  61733. if (camera._waitingParentId) {
  61734. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  61735. camera._waitingParentId = null;
  61736. }
  61737. }
  61738. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  61739. var light_1 = scene.lights[index];
  61740. if (light_1 && light_1._waitingParentId) {
  61741. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  61742. light_1._waitingParentId = null;
  61743. }
  61744. }
  61745. // Sounds
  61746. // TODO: add sound
  61747. var loadedSounds = [];
  61748. var loadedSound;
  61749. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  61750. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  61751. var parsedSound = parsedData.sounds[index];
  61752. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  61753. if (!parsedSound.url)
  61754. parsedSound.url = parsedSound.name;
  61755. if (!loadedSounds[parsedSound.url]) {
  61756. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  61757. loadedSounds[parsedSound.url] = loadedSound;
  61758. container.sounds.push(loadedSound);
  61759. }
  61760. else {
  61761. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  61762. }
  61763. }
  61764. else {
  61765. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  61766. }
  61767. }
  61768. }
  61769. loadedSounds = [];
  61770. // Connect parents & children and parse actions
  61771. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  61772. var transformNode = scene.transformNodes[index];
  61773. if (transformNode._waitingParentId) {
  61774. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  61775. transformNode._waitingParentId = null;
  61776. }
  61777. }
  61778. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  61779. var mesh = scene.meshes[index];
  61780. if (mesh._waitingParentId) {
  61781. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  61782. mesh._waitingParentId = null;
  61783. }
  61784. if (mesh._waitingActions) {
  61785. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  61786. mesh._waitingActions = null;
  61787. }
  61788. }
  61789. // freeze world matrix application
  61790. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  61791. var currentMesh = scene.meshes[index];
  61792. if (currentMesh._waitingFreezeWorldMatrix) {
  61793. currentMesh.freezeWorldMatrix();
  61794. currentMesh._waitingFreezeWorldMatrix = null;
  61795. }
  61796. else {
  61797. currentMesh.computeWorldMatrix(true);
  61798. }
  61799. }
  61800. // Particles Systems
  61801. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  61802. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  61803. var parsedParticleSystem = parsedData.particleSystems[index];
  61804. if (parsedParticleSystem.activeParticleCount) {
  61805. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  61806. container.particleSystems.push(ps);
  61807. }
  61808. else {
  61809. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  61810. container.particleSystems.push(ps);
  61811. }
  61812. }
  61813. }
  61814. // Lens flares
  61815. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  61816. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  61817. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  61818. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  61819. container.lensFlareSystems.push(lf);
  61820. }
  61821. }
  61822. // Shadows
  61823. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  61824. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  61825. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  61826. var sg = BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  61827. container.shadowGenerators.push(sg);
  61828. }
  61829. }
  61830. // Lights exclusions / inclusions
  61831. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  61832. var light_2 = scene.lights[index];
  61833. // Excluded check
  61834. if (light_2._excludedMeshesIds.length > 0) {
  61835. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  61836. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  61837. if (excludedMesh) {
  61838. light_2.excludedMeshes.push(excludedMesh);
  61839. }
  61840. }
  61841. light_2._excludedMeshesIds = [];
  61842. }
  61843. // Included check
  61844. if (light_2._includedOnlyMeshesIds.length > 0) {
  61845. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  61846. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  61847. if (includedOnlyMesh) {
  61848. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  61849. }
  61850. }
  61851. light_2._includedOnlyMeshesIds = [];
  61852. }
  61853. }
  61854. // Actions (scene)
  61855. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  61856. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  61857. }
  61858. if (!addToScene) {
  61859. container.removeAllFromScene();
  61860. }
  61861. }
  61862. catch (err) {
  61863. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  61864. if (onError) {
  61865. onError(msg, err);
  61866. }
  61867. else {
  61868. BABYLON.Tools.Log(msg);
  61869. throw err;
  61870. }
  61871. }
  61872. finally {
  61873. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  61874. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  61875. }
  61876. }
  61877. return container;
  61878. };
  61879. BABYLON.SceneLoader.RegisterPlugin({
  61880. name: "babylon.js",
  61881. extensions: ".babylon",
  61882. canDirectLoad: function (data) {
  61883. if (data.indexOf("babylon") !== -1) {
  61884. return true;
  61885. }
  61886. return false;
  61887. },
  61888. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  61889. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  61890. // when SceneLoader.debugLogging = true (default), or exception encountered.
  61891. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  61892. // and avoid problems with multiple concurrent .babylon loads.
  61893. var log = "importMesh has failed JSON parse";
  61894. try {
  61895. var parsedData = JSON.parse(data);
  61896. log = "";
  61897. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  61898. if (!meshesNames) {
  61899. meshesNames = null;
  61900. }
  61901. else if (!Array.isArray(meshesNames)) {
  61902. meshesNames = [meshesNames];
  61903. }
  61904. var hierarchyIds = new Array();
  61905. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  61906. var loadedSkeletonsIds = [];
  61907. var loadedMaterialsIds = [];
  61908. var index;
  61909. var cache;
  61910. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  61911. var parsedMesh = parsedData.meshes[index];
  61912. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  61913. if (meshesNames !== null) {
  61914. // Remove found mesh name from list.
  61915. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  61916. }
  61917. //Geometry?
  61918. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  61919. //does the file contain geometries?
  61920. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  61921. //find the correct geometry and add it to the scene
  61922. var found = false;
  61923. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  61924. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  61925. return;
  61926. }
  61927. else {
  61928. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  61929. if (parsedGeometryData.id === parsedMesh.geometryId) {
  61930. switch (geometryType) {
  61931. case "boxes":
  61932. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  61933. break;
  61934. case "spheres":
  61935. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  61936. break;
  61937. case "cylinders":
  61938. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  61939. break;
  61940. case "toruses":
  61941. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  61942. break;
  61943. case "grounds":
  61944. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  61945. break;
  61946. case "planes":
  61947. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  61948. break;
  61949. case "torusKnots":
  61950. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  61951. break;
  61952. case "vertexData":
  61953. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  61954. break;
  61955. }
  61956. found = true;
  61957. }
  61958. });
  61959. }
  61960. });
  61961. if (found === false) {
  61962. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  61963. }
  61964. }
  61965. }
  61966. // Material ?
  61967. if (parsedMesh.materialId) {
  61968. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  61969. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  61970. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  61971. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  61972. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  61973. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  61974. var subMatId = parsedMultiMaterial.materials[matIndex];
  61975. loadedMaterialsIds.push(subMatId);
  61976. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  61977. if (mat) {
  61978. log += "\n\tMaterial " + mat.toString(fullDetails);
  61979. }
  61980. }
  61981. loadedMaterialsIds.push(parsedMultiMaterial.id);
  61982. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  61983. if (mmat) {
  61984. materialFound = true;
  61985. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  61986. }
  61987. break;
  61988. }
  61989. }
  61990. }
  61991. if (materialFound === false) {
  61992. loadedMaterialsIds.push(parsedMesh.materialId);
  61993. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  61994. if (!mat) {
  61995. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  61996. }
  61997. else {
  61998. log += "\n\tMaterial " + mat.toString(fullDetails);
  61999. }
  62000. }
  62001. }
  62002. // Skeleton ?
  62003. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  62004. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  62005. if (skeletonAlreadyLoaded === false) {
  62006. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  62007. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  62008. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  62009. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  62010. skeletons.push(skeleton);
  62011. loadedSkeletonsIds.push(parsedSkeleton.id);
  62012. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  62013. }
  62014. }
  62015. }
  62016. }
  62017. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  62018. meshes.push(mesh);
  62019. log += "\n\tMesh " + mesh.toString(fullDetails);
  62020. }
  62021. }
  62022. // Connecting parents
  62023. var currentMesh;
  62024. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  62025. currentMesh = scene.meshes[index];
  62026. if (currentMesh._waitingParentId) {
  62027. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  62028. currentMesh._waitingParentId = null;
  62029. }
  62030. }
  62031. // freeze and compute world matrix application
  62032. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  62033. currentMesh = scene.meshes[index];
  62034. if (currentMesh._waitingFreezeWorldMatrix) {
  62035. currentMesh.freezeWorldMatrix();
  62036. currentMesh._waitingFreezeWorldMatrix = null;
  62037. }
  62038. else {
  62039. currentMesh.computeWorldMatrix(true);
  62040. }
  62041. }
  62042. }
  62043. // Particles
  62044. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  62045. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  62046. var parsedParticleSystem = parsedData.particleSystems[index];
  62047. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  62048. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  62049. }
  62050. }
  62051. }
  62052. return true;
  62053. }
  62054. catch (err) {
  62055. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  62056. if (onError) {
  62057. onError(msg, err);
  62058. }
  62059. else {
  62060. BABYLON.Tools.Log(msg);
  62061. throw err;
  62062. }
  62063. }
  62064. finally {
  62065. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  62066. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  62067. }
  62068. }
  62069. return false;
  62070. },
  62071. load: function (scene, data, rootUrl, onError) {
  62072. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  62073. // when SceneLoader.debugLogging = true (default), or exception encountered.
  62074. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  62075. // and avoid problems with multiple concurrent .babylon loads.
  62076. var log = "importScene has failed JSON parse";
  62077. try {
  62078. var parsedData = JSON.parse(data);
  62079. log = "";
  62080. // Scene
  62081. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  62082. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  62083. }
  62084. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  62085. scene.autoClear = parsedData.autoClear;
  62086. }
  62087. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  62088. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  62089. }
  62090. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  62091. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  62092. }
  62093. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  62094. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  62095. }
  62096. // Fog
  62097. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  62098. scene.fogMode = parsedData.fogMode;
  62099. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  62100. scene.fogStart = parsedData.fogStart;
  62101. scene.fogEnd = parsedData.fogEnd;
  62102. scene.fogDensity = parsedData.fogDensity;
  62103. log += "\tFog mode for scene: ";
  62104. switch (scene.fogMode) {
  62105. // getters not compiling, so using hardcoded
  62106. case 1:
  62107. log += "exp\n";
  62108. break;
  62109. case 2:
  62110. log += "exp2\n";
  62111. break;
  62112. case 3:
  62113. log += "linear\n";
  62114. break;
  62115. }
  62116. }
  62117. //Physics
  62118. if (parsedData.physicsEnabled) {
  62119. var physicsPlugin;
  62120. if (parsedData.physicsEngine === "cannon") {
  62121. physicsPlugin = new BABYLON.CannonJSPlugin();
  62122. }
  62123. else if (parsedData.physicsEngine === "oimo") {
  62124. physicsPlugin = new BABYLON.OimoJSPlugin();
  62125. }
  62126. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  62127. //else - default engine, which is currently oimo
  62128. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  62129. scene.enablePhysics(physicsGravity, physicsPlugin);
  62130. }
  62131. // Metadata
  62132. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  62133. scene.metadata = parsedData.metadata;
  62134. }
  62135. //collisions, if defined. otherwise, default is true
  62136. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  62137. scene.collisionsEnabled = parsedData.collisionsEnabled;
  62138. }
  62139. scene.workerCollisions = !!parsedData.workerCollisions;
  62140. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  62141. if (!container) {
  62142. return false;
  62143. }
  62144. if (parsedData.autoAnimate) {
  62145. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  62146. }
  62147. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  62148. scene.setActiveCameraByID(parsedData.activeCameraID);
  62149. }
  62150. // Environment texture
  62151. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  62152. scene.environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  62153. if (parsedData.createDefaultSkybox === true) {
  62154. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  62155. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  62156. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  62157. }
  62158. }
  62159. // Finish
  62160. return true;
  62161. }
  62162. catch (err) {
  62163. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  62164. if (onError) {
  62165. onError(msg, err);
  62166. }
  62167. else {
  62168. BABYLON.Tools.Log(msg);
  62169. throw err;
  62170. }
  62171. }
  62172. finally {
  62173. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  62174. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  62175. }
  62176. }
  62177. return false;
  62178. },
  62179. loadAssetContainer: function (scene, data, rootUrl, onError) {
  62180. var container = loadAssetContainer(scene, data, rootUrl, onError);
  62181. return container;
  62182. }
  62183. });
  62184. })(BABYLON || (BABYLON = {}));
  62185. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  62186. var BABYLON;
  62187. (function (BABYLON) {
  62188. var FilesInput = /** @class */ (function () {
  62189. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  62190. this.onProcessFileCallback = function () { return true; };
  62191. this._engine = engine;
  62192. this._currentScene = scene;
  62193. this._sceneLoadedCallback = sceneLoadedCallback;
  62194. this._progressCallback = progressCallback;
  62195. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  62196. this._textureLoadingCallback = textureLoadingCallback;
  62197. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  62198. this._onReloadCallback = onReloadCallback;
  62199. this._errorCallback = errorCallback;
  62200. }
  62201. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  62202. var _this = this;
  62203. if (elementToMonitor) {
  62204. this._elementToMonitor = elementToMonitor;
  62205. this._dragEnterHandler = function (e) { _this.drag(e); };
  62206. this._dragOverHandler = function (e) { _this.drag(e); };
  62207. this._dropHandler = function (e) { _this.drop(e); };
  62208. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  62209. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  62210. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  62211. }
  62212. };
  62213. FilesInput.prototype.dispose = function () {
  62214. if (!this._elementToMonitor) {
  62215. return;
  62216. }
  62217. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  62218. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  62219. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  62220. };
  62221. FilesInput.prototype.renderFunction = function () {
  62222. if (this._additionalRenderLoopLogicCallback) {
  62223. this._additionalRenderLoopLogicCallback();
  62224. }
  62225. if (this._currentScene) {
  62226. if (this._textureLoadingCallback) {
  62227. var remaining = this._currentScene.getWaitingItemsCount();
  62228. if (remaining > 0) {
  62229. this._textureLoadingCallback(remaining);
  62230. }
  62231. }
  62232. this._currentScene.render();
  62233. }
  62234. };
  62235. FilesInput.prototype.drag = function (e) {
  62236. e.stopPropagation();
  62237. e.preventDefault();
  62238. };
  62239. FilesInput.prototype.drop = function (eventDrop) {
  62240. eventDrop.stopPropagation();
  62241. eventDrop.preventDefault();
  62242. this.loadFiles(eventDrop);
  62243. };
  62244. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  62245. var _this = this;
  62246. var reader = folder.createReader();
  62247. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  62248. reader.readEntries(function (entries) {
  62249. remaining.count += entries.length;
  62250. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  62251. var entry = entries_1[_i];
  62252. if (entry.isFile) {
  62253. entry.file(function (file) {
  62254. file.correctName = relativePath + file.name;
  62255. files.push(file);
  62256. if (--remaining.count === 0) {
  62257. callback();
  62258. }
  62259. });
  62260. }
  62261. else if (entry.isDirectory) {
  62262. _this._traverseFolder(entry, files, remaining, callback);
  62263. }
  62264. }
  62265. if (--remaining.count) {
  62266. callback();
  62267. }
  62268. });
  62269. };
  62270. FilesInput.prototype._processFiles = function (files) {
  62271. for (var i = 0; i < files.length; i++) {
  62272. var name = files[i].correctName.toLowerCase();
  62273. var extension = name.split('.').pop();
  62274. if (!this.onProcessFileCallback(files[i], name, extension)) {
  62275. continue;
  62276. }
  62277. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  62278. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  62279. this._sceneFileToLoad = files[i];
  62280. }
  62281. else {
  62282. FilesInput.FilesToLoad[name] = files[i];
  62283. }
  62284. }
  62285. };
  62286. FilesInput.prototype.loadFiles = function (event) {
  62287. var _this = this;
  62288. if (this._startingProcessingFilesCallback)
  62289. this._startingProcessingFilesCallback();
  62290. // Handling data transfer via drag'n'drop
  62291. if (event && event.dataTransfer && event.dataTransfer.files) {
  62292. this._filesToLoad = event.dataTransfer.files;
  62293. }
  62294. // Handling files from input files
  62295. if (event && event.target && event.target.files) {
  62296. this._filesToLoad = event.target.files;
  62297. }
  62298. if (this._filesToLoad && this._filesToLoad.length > 0) {
  62299. var files_1 = new Array();
  62300. var folders = [];
  62301. var items = event.dataTransfer ? event.dataTransfer.items : null;
  62302. for (var i = 0; i < this._filesToLoad.length; i++) {
  62303. var fileToLoad = this._filesToLoad[i];
  62304. var name_1 = fileToLoad.name.toLowerCase();
  62305. var entry = void 0;
  62306. fileToLoad.correctName = name_1;
  62307. if (items) {
  62308. var item = items[i];
  62309. if (item.getAsEntry) {
  62310. entry = item.getAsEntry();
  62311. }
  62312. else if (item.webkitGetAsEntry) {
  62313. entry = item.webkitGetAsEntry();
  62314. }
  62315. }
  62316. if (!entry) {
  62317. files_1.push(fileToLoad);
  62318. }
  62319. else {
  62320. if (entry.isDirectory) {
  62321. folders.push(entry);
  62322. }
  62323. else {
  62324. files_1.push(fileToLoad);
  62325. }
  62326. }
  62327. }
  62328. if (folders.length === 0) {
  62329. this._processFiles(files_1);
  62330. this._processReload();
  62331. }
  62332. else {
  62333. var remaining = { count: folders.length };
  62334. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  62335. var folder = folders_1[_i];
  62336. this._traverseFolder(folder, files_1, remaining, function () {
  62337. _this._processFiles(files_1);
  62338. if (remaining.count === 0) {
  62339. _this._processReload();
  62340. }
  62341. });
  62342. }
  62343. }
  62344. }
  62345. };
  62346. FilesInput.prototype._processReload = function () {
  62347. if (this._onReloadCallback) {
  62348. this._onReloadCallback(this._sceneFileToLoad);
  62349. }
  62350. else {
  62351. this.reload();
  62352. }
  62353. };
  62354. FilesInput.prototype.reload = function () {
  62355. var _this = this;
  62356. // If a scene file has been provided
  62357. if (this._sceneFileToLoad) {
  62358. if (this._currentScene) {
  62359. if (BABYLON.Tools.errorsCount > 0) {
  62360. BABYLON.Tools.ClearLogCache();
  62361. }
  62362. this._engine.stopRenderLoop();
  62363. this._currentScene.dispose();
  62364. }
  62365. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  62366. if (_this._progressCallback) {
  62367. _this._progressCallback(progress);
  62368. }
  62369. }).then(function (scene) {
  62370. _this._currentScene = scene;
  62371. if (_this._sceneLoadedCallback) {
  62372. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  62373. }
  62374. // Wait for textures and shaders to be ready
  62375. _this._currentScene.executeWhenReady(function () {
  62376. _this._engine.runRenderLoop(function () {
  62377. _this.renderFunction();
  62378. });
  62379. });
  62380. }).catch(function (error) {
  62381. if (_this._errorCallback) {
  62382. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  62383. }
  62384. });
  62385. }
  62386. else {
  62387. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  62388. }
  62389. };
  62390. FilesInput.FilesToLoad = {};
  62391. return FilesInput;
  62392. }());
  62393. BABYLON.FilesInput = FilesInput;
  62394. })(BABYLON || (BABYLON = {}));
  62395. //# sourceMappingURL=babylon.filesInput.js.map
  62396. var BABYLON;
  62397. (function (BABYLON) {
  62398. /**
  62399. * This class implement a typical dictionary using a string as key and the generic type T as value.
  62400. * The underlying implementation relies on an associative array to ensure the best performances.
  62401. * The value can be anything including 'null' but except 'undefined'
  62402. */
  62403. var StringDictionary = /** @class */ (function () {
  62404. function StringDictionary() {
  62405. this._count = 0;
  62406. this._data = {};
  62407. }
  62408. /**
  62409. * This will clear this dictionary and copy the content from the 'source' one.
  62410. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  62411. * @param source the dictionary to take the content from and copy to this dictionary
  62412. */
  62413. StringDictionary.prototype.copyFrom = function (source) {
  62414. var _this = this;
  62415. this.clear();
  62416. source.forEach(function (t, v) { return _this.add(t, v); });
  62417. };
  62418. /**
  62419. * Get a value based from its key
  62420. * @param key the given key to get the matching value from
  62421. * @return the value if found, otherwise undefined is returned
  62422. */
  62423. StringDictionary.prototype.get = function (key) {
  62424. var val = this._data[key];
  62425. if (val !== undefined) {
  62426. return val;
  62427. }
  62428. return undefined;
  62429. };
  62430. /**
  62431. * Get a value from its key or add it if it doesn't exist.
  62432. * This method will ensure you that a given key/data will be present in the dictionary.
  62433. * @param key the given key to get the matching value from
  62434. * @param factory the factory that will create the value if the key is not present in the dictionary.
  62435. * The factory will only be invoked if there's no data for the given key.
  62436. * @return the value corresponding to the key.
  62437. */
  62438. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  62439. var val = this.get(key);
  62440. if (val !== undefined) {
  62441. return val;
  62442. }
  62443. val = factory(key);
  62444. if (val) {
  62445. this.add(key, val);
  62446. }
  62447. return val;
  62448. };
  62449. /**
  62450. * Get a value from its key if present in the dictionary otherwise add it
  62451. * @param key the key to get the value from
  62452. * @param val if there's no such key/value pair in the dictionary add it with this value
  62453. * @return the value corresponding to the key
  62454. */
  62455. StringDictionary.prototype.getOrAdd = function (key, val) {
  62456. var curVal = this.get(key);
  62457. if (curVal !== undefined) {
  62458. return curVal;
  62459. }
  62460. this.add(key, val);
  62461. return val;
  62462. };
  62463. /**
  62464. * Check if there's a given key in the dictionary
  62465. * @param key the key to check for
  62466. * @return true if the key is present, false otherwise
  62467. */
  62468. StringDictionary.prototype.contains = function (key) {
  62469. return this._data[key] !== undefined;
  62470. };
  62471. /**
  62472. * Add a new key and its corresponding value
  62473. * @param key the key to add
  62474. * @param value the value corresponding to the key
  62475. * @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
  62476. */
  62477. StringDictionary.prototype.add = function (key, value) {
  62478. if (this._data[key] !== undefined) {
  62479. return false;
  62480. }
  62481. this._data[key] = value;
  62482. ++this._count;
  62483. return true;
  62484. };
  62485. StringDictionary.prototype.set = function (key, value) {
  62486. if (this._data[key] === undefined) {
  62487. return false;
  62488. }
  62489. this._data[key] = value;
  62490. return true;
  62491. };
  62492. /**
  62493. * Get the element of the given key and remove it from the dictionary
  62494. * @param key
  62495. */
  62496. StringDictionary.prototype.getAndRemove = function (key) {
  62497. var val = this.get(key);
  62498. if (val !== undefined) {
  62499. delete this._data[key];
  62500. --this._count;
  62501. return val;
  62502. }
  62503. return null;
  62504. };
  62505. /**
  62506. * Remove a key/value from the dictionary.
  62507. * @param key the key to remove
  62508. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  62509. */
  62510. StringDictionary.prototype.remove = function (key) {
  62511. if (this.contains(key)) {
  62512. delete this._data[key];
  62513. --this._count;
  62514. return true;
  62515. }
  62516. return false;
  62517. };
  62518. /**
  62519. * Clear the whole content of the dictionary
  62520. */
  62521. StringDictionary.prototype.clear = function () {
  62522. this._data = {};
  62523. this._count = 0;
  62524. };
  62525. Object.defineProperty(StringDictionary.prototype, "count", {
  62526. get: function () {
  62527. return this._count;
  62528. },
  62529. enumerable: true,
  62530. configurable: true
  62531. });
  62532. /**
  62533. * Execute a callback on each key/val of the dictionary.
  62534. * Note that you can remove any element in this dictionary in the callback implementation
  62535. * @param callback the callback to execute on a given key/value pair
  62536. */
  62537. StringDictionary.prototype.forEach = function (callback) {
  62538. for (var cur in this._data) {
  62539. var val = this._data[cur];
  62540. callback(cur, val);
  62541. }
  62542. };
  62543. /**
  62544. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  62545. * If the callback returns null or undefined the method will iterate to the next key/value pair
  62546. * Note that you can remove any element in this dictionary in the callback implementation
  62547. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  62548. */
  62549. StringDictionary.prototype.first = function (callback) {
  62550. for (var cur in this._data) {
  62551. var val = this._data[cur];
  62552. var res = callback(cur, val);
  62553. if (res) {
  62554. return res;
  62555. }
  62556. }
  62557. return null;
  62558. };
  62559. return StringDictionary;
  62560. }());
  62561. BABYLON.StringDictionary = StringDictionary;
  62562. })(BABYLON || (BABYLON = {}));
  62563. //# sourceMappingURL=babylon.stringDictionary.js.map
  62564. var BABYLON;
  62565. (function (BABYLON) {
  62566. var Tags = /** @class */ (function () {
  62567. function Tags() {
  62568. }
  62569. Tags.EnableFor = function (obj) {
  62570. obj._tags = obj._tags || {};
  62571. obj.hasTags = function () {
  62572. return Tags.HasTags(obj);
  62573. };
  62574. obj.addTags = function (tagsString) {
  62575. return Tags.AddTagsTo(obj, tagsString);
  62576. };
  62577. obj.removeTags = function (tagsString) {
  62578. return Tags.RemoveTagsFrom(obj, tagsString);
  62579. };
  62580. obj.matchesTagsQuery = function (tagsQuery) {
  62581. return Tags.MatchesQuery(obj, tagsQuery);
  62582. };
  62583. };
  62584. Tags.DisableFor = function (obj) {
  62585. delete obj._tags;
  62586. delete obj.hasTags;
  62587. delete obj.addTags;
  62588. delete obj.removeTags;
  62589. delete obj.matchesTagsQuery;
  62590. };
  62591. Tags.HasTags = function (obj) {
  62592. if (!obj._tags) {
  62593. return false;
  62594. }
  62595. return !BABYLON.Tools.IsEmpty(obj._tags);
  62596. };
  62597. Tags.GetTags = function (obj, asString) {
  62598. if (asString === void 0) { asString = true; }
  62599. if (!obj._tags) {
  62600. return null;
  62601. }
  62602. if (asString) {
  62603. var tagsArray = [];
  62604. for (var tag in obj._tags) {
  62605. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  62606. tagsArray.push(tag);
  62607. }
  62608. }
  62609. return tagsArray.join(" ");
  62610. }
  62611. else {
  62612. return obj._tags;
  62613. }
  62614. };
  62615. // the tags 'true' and 'false' are reserved and cannot be used as tags
  62616. // a tag cannot start with '||', '&&', and '!'
  62617. // it cannot contain whitespaces
  62618. Tags.AddTagsTo = function (obj, tagsString) {
  62619. if (!tagsString) {
  62620. return;
  62621. }
  62622. if (typeof tagsString !== "string") {
  62623. return;
  62624. }
  62625. var tags = tagsString.split(" ");
  62626. tags.forEach(function (tag, index, array) {
  62627. Tags._AddTagTo(obj, tag);
  62628. });
  62629. };
  62630. Tags._AddTagTo = function (obj, tag) {
  62631. tag = tag.trim();
  62632. if (tag === "" || tag === "true" || tag === "false") {
  62633. return;
  62634. }
  62635. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  62636. return;
  62637. }
  62638. Tags.EnableFor(obj);
  62639. obj._tags[tag] = true;
  62640. };
  62641. Tags.RemoveTagsFrom = function (obj, tagsString) {
  62642. if (!Tags.HasTags(obj)) {
  62643. return;
  62644. }
  62645. var tags = tagsString.split(" ");
  62646. for (var t in tags) {
  62647. Tags._RemoveTagFrom(obj, tags[t]);
  62648. }
  62649. };
  62650. Tags._RemoveTagFrom = function (obj, tag) {
  62651. delete obj._tags[tag];
  62652. };
  62653. Tags.MatchesQuery = function (obj, tagsQuery) {
  62654. if (tagsQuery === undefined) {
  62655. return true;
  62656. }
  62657. if (tagsQuery === "") {
  62658. return Tags.HasTags(obj);
  62659. }
  62660. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  62661. };
  62662. return Tags;
  62663. }());
  62664. BABYLON.Tags = Tags;
  62665. })(BABYLON || (BABYLON = {}));
  62666. //# sourceMappingURL=babylon.tags.js.map
  62667. var BABYLON;
  62668. (function (BABYLON) {
  62669. var AndOrNotEvaluator = /** @class */ (function () {
  62670. function AndOrNotEvaluator() {
  62671. }
  62672. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  62673. if (!query.match(/\([^\(\)]*\)/g)) {
  62674. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  62675. }
  62676. else {
  62677. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  62678. // remove parenthesis
  62679. r = r.slice(1, r.length - 1);
  62680. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  62681. });
  62682. }
  62683. if (query === "true") {
  62684. return true;
  62685. }
  62686. if (query === "false") {
  62687. return false;
  62688. }
  62689. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  62690. };
  62691. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  62692. evaluateCallback = evaluateCallback || (function (r) {
  62693. return r === "true" ? true : false;
  62694. });
  62695. var result;
  62696. var or = parenthesisContent.split("||");
  62697. for (var i in or) {
  62698. if (or.hasOwnProperty(i)) {
  62699. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  62700. var and = ori.split("&&");
  62701. if (and.length > 1) {
  62702. for (var j = 0; j < and.length; ++j) {
  62703. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  62704. if (andj !== "true" && andj !== "false") {
  62705. if (andj[0] === "!") {
  62706. result = !evaluateCallback(andj.substring(1));
  62707. }
  62708. else {
  62709. result = evaluateCallback(andj);
  62710. }
  62711. }
  62712. else {
  62713. result = andj === "true" ? true : false;
  62714. }
  62715. if (!result) {
  62716. ori = "false";
  62717. break;
  62718. }
  62719. }
  62720. }
  62721. if (result || ori === "true") {
  62722. result = true;
  62723. break;
  62724. }
  62725. // result equals false (or undefined)
  62726. if (ori !== "true" && ori !== "false") {
  62727. if (ori[0] === "!") {
  62728. result = !evaluateCallback(ori.substring(1));
  62729. }
  62730. else {
  62731. result = evaluateCallback(ori);
  62732. }
  62733. }
  62734. else {
  62735. result = ori === "true" ? true : false;
  62736. }
  62737. }
  62738. }
  62739. // the whole parenthesis scope is replaced by 'true' or 'false'
  62740. return result ? "true" : "false";
  62741. };
  62742. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  62743. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  62744. // remove whitespaces
  62745. r = r.replace(/[\s]/g, function () { return ""; });
  62746. return r.length % 2 ? "!" : "";
  62747. });
  62748. booleanString = booleanString.trim();
  62749. if (booleanString === "!true") {
  62750. booleanString = "false";
  62751. }
  62752. else if (booleanString === "!false") {
  62753. booleanString = "true";
  62754. }
  62755. return booleanString;
  62756. };
  62757. return AndOrNotEvaluator;
  62758. }());
  62759. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  62760. })(BABYLON || (BABYLON = {}));
  62761. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  62762. var BABYLON;
  62763. (function (BABYLON) {
  62764. var Database = /** @class */ (function () {
  62765. function Database(urlToScene, callbackManifestChecked) {
  62766. // Handling various flavors of prefixed version of IndexedDB
  62767. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  62768. this.callbackManifestChecked = callbackManifestChecked;
  62769. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  62770. this.db = null;
  62771. this._enableSceneOffline = false;
  62772. this._enableTexturesOffline = false;
  62773. this.manifestVersionFound = 0;
  62774. this.mustUpdateRessources = false;
  62775. this.hasReachedQuota = false;
  62776. if (!Database.IDBStorageEnabled) {
  62777. this.callbackManifestChecked(true);
  62778. }
  62779. else {
  62780. this.checkManifestFile();
  62781. }
  62782. }
  62783. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  62784. get: function () {
  62785. return this._enableSceneOffline;
  62786. },
  62787. enumerable: true,
  62788. configurable: true
  62789. });
  62790. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  62791. get: function () {
  62792. return this._enableTexturesOffline;
  62793. },
  62794. enumerable: true,
  62795. configurable: true
  62796. });
  62797. Database.prototype.checkManifestFile = function () {
  62798. var _this = this;
  62799. var noManifestFile = function () {
  62800. _this._enableSceneOffline = false;
  62801. _this._enableTexturesOffline = false;
  62802. _this.callbackManifestChecked(false);
  62803. };
  62804. var timeStampUsed = false;
  62805. var manifestURL = this.currentSceneUrl + ".manifest";
  62806. var xhr = new XMLHttpRequest();
  62807. if (navigator.onLine) {
  62808. // Adding a timestamp to by-pass browsers' cache
  62809. timeStampUsed = true;
  62810. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  62811. }
  62812. xhr.open("GET", manifestURL, true);
  62813. xhr.addEventListener("load", function () {
  62814. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  62815. try {
  62816. var manifestFile = JSON.parse(xhr.response);
  62817. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  62818. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  62819. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  62820. _this.manifestVersionFound = manifestFile.version;
  62821. }
  62822. if (_this.callbackManifestChecked) {
  62823. _this.callbackManifestChecked(true);
  62824. }
  62825. }
  62826. catch (ex) {
  62827. noManifestFile();
  62828. }
  62829. }
  62830. else {
  62831. noManifestFile();
  62832. }
  62833. }, false);
  62834. xhr.addEventListener("error", function (event) {
  62835. if (timeStampUsed) {
  62836. timeStampUsed = false;
  62837. // Let's retry without the timeStamp
  62838. // It could fail when coupled with HTML5 Offline API
  62839. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  62840. xhr.open("GET", retryManifestURL, true);
  62841. xhr.send();
  62842. }
  62843. else {
  62844. noManifestFile();
  62845. }
  62846. }, false);
  62847. try {
  62848. xhr.send();
  62849. }
  62850. catch (ex) {
  62851. BABYLON.Tools.Error("Error on XHR send request.");
  62852. this.callbackManifestChecked(false);
  62853. }
  62854. };
  62855. Database.prototype.openAsync = function (successCallback, errorCallback) {
  62856. var _this = this;
  62857. var handleError = function () {
  62858. _this.isSupported = false;
  62859. if (errorCallback)
  62860. errorCallback();
  62861. };
  62862. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  62863. // Your browser doesn't support IndexedDB
  62864. this.isSupported = false;
  62865. if (errorCallback)
  62866. errorCallback();
  62867. }
  62868. else {
  62869. // If the DB hasn't been opened or created yet
  62870. if (!this.db) {
  62871. this.hasReachedQuota = false;
  62872. this.isSupported = true;
  62873. var request = this.idbFactory.open("babylonjs", 1);
  62874. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  62875. request.onerror = function (event) {
  62876. handleError();
  62877. };
  62878. // executes when a version change transaction cannot complete due to other active transactions
  62879. request.onblocked = function (event) {
  62880. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  62881. handleError();
  62882. };
  62883. // DB has been opened successfully
  62884. request.onsuccess = function (event) {
  62885. _this.db = request.result;
  62886. successCallback();
  62887. };
  62888. // Initialization of the DB. Creating Scenes & Textures stores
  62889. request.onupgradeneeded = function (event) {
  62890. _this.db = (event.target).result;
  62891. if (_this.db) {
  62892. try {
  62893. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  62894. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  62895. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  62896. }
  62897. catch (ex) {
  62898. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  62899. handleError();
  62900. }
  62901. }
  62902. };
  62903. }
  62904. else {
  62905. if (successCallback)
  62906. successCallback();
  62907. }
  62908. }
  62909. };
  62910. Database.prototype.loadImageFromDB = function (url, image) {
  62911. var _this = this;
  62912. var completeURL = Database.ReturnFullUrlLocation(url);
  62913. var saveAndLoadImage = function () {
  62914. if (!_this.hasReachedQuota && _this.db !== null) {
  62915. // the texture is not yet in the DB, let's try to save it
  62916. _this._saveImageIntoDBAsync(completeURL, image);
  62917. }
  62918. else {
  62919. image.src = url;
  62920. }
  62921. };
  62922. if (!this.mustUpdateRessources) {
  62923. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  62924. }
  62925. else {
  62926. saveAndLoadImage();
  62927. }
  62928. };
  62929. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  62930. if (this.isSupported && this.db !== null) {
  62931. var texture;
  62932. var transaction = this.db.transaction(["textures"]);
  62933. transaction.onabort = function (event) {
  62934. image.src = url;
  62935. };
  62936. transaction.oncomplete = function (event) {
  62937. var blobTextureURL;
  62938. if (texture) {
  62939. var URL = window.URL || window.webkitURL;
  62940. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  62941. image.onerror = function () {
  62942. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  62943. image.src = url;
  62944. };
  62945. image.src = blobTextureURL;
  62946. }
  62947. else {
  62948. notInDBCallback();
  62949. }
  62950. };
  62951. var getRequest = transaction.objectStore("textures").get(url);
  62952. getRequest.onsuccess = function (event) {
  62953. texture = (event.target).result;
  62954. };
  62955. getRequest.onerror = function (event) {
  62956. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  62957. image.src = url;
  62958. };
  62959. }
  62960. else {
  62961. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  62962. image.src = url;
  62963. }
  62964. };
  62965. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  62966. var _this = this;
  62967. if (this.isSupported) {
  62968. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  62969. var generateBlobUrl = function () {
  62970. var blobTextureURL;
  62971. if (blob) {
  62972. var URL = window.URL || window.webkitURL;
  62973. try {
  62974. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  62975. }
  62976. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  62977. catch (ex) {
  62978. blobTextureURL = URL.createObjectURL(blob);
  62979. }
  62980. }
  62981. if (blobTextureURL) {
  62982. image.src = blobTextureURL;
  62983. }
  62984. };
  62985. if (Database.IsUASupportingBlobStorage) {
  62986. var xhr = new XMLHttpRequest(), blob;
  62987. xhr.open("GET", url, true);
  62988. xhr.responseType = "blob";
  62989. xhr.addEventListener("load", function () {
  62990. if (xhr.status === 200 && _this.db) {
  62991. // Blob as response (XHR2)
  62992. blob = xhr.response;
  62993. var transaction = _this.db.transaction(["textures"], "readwrite");
  62994. // the transaction could abort because of a QuotaExceededError error
  62995. transaction.onabort = function (event) {
  62996. try {
  62997. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  62998. var srcElement = (event.srcElement || event.target);
  62999. var error = srcElement.error;
  63000. if (error && error.name === "QuotaExceededError") {
  63001. _this.hasReachedQuota = true;
  63002. }
  63003. }
  63004. catch (ex) { }
  63005. generateBlobUrl();
  63006. };
  63007. transaction.oncomplete = function (event) {
  63008. generateBlobUrl();
  63009. };
  63010. var newTexture = { textureUrl: url, data: blob };
  63011. try {
  63012. // Put the blob into the dabase
  63013. var addRequest = transaction.objectStore("textures").put(newTexture);
  63014. addRequest.onsuccess = function (event) {
  63015. };
  63016. addRequest.onerror = function (event) {
  63017. generateBlobUrl();
  63018. };
  63019. }
  63020. catch (ex) {
  63021. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  63022. if (ex.code === 25) {
  63023. Database.IsUASupportingBlobStorage = false;
  63024. }
  63025. image.src = url;
  63026. }
  63027. }
  63028. else {
  63029. image.src = url;
  63030. }
  63031. }, false);
  63032. xhr.addEventListener("error", function (event) {
  63033. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  63034. image.src = url;
  63035. }, false);
  63036. xhr.send();
  63037. }
  63038. else {
  63039. image.src = url;
  63040. }
  63041. }
  63042. else {
  63043. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  63044. image.src = url;
  63045. }
  63046. };
  63047. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  63048. var _this = this;
  63049. var updateVersion = function () {
  63050. // the version is not yet in the DB or we need to update it
  63051. _this._saveVersionIntoDBAsync(url, versionLoaded);
  63052. };
  63053. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  63054. };
  63055. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  63056. var _this = this;
  63057. if (this.isSupported && this.db) {
  63058. var version;
  63059. try {
  63060. var transaction = this.db.transaction(["versions"]);
  63061. transaction.oncomplete = function (event) {
  63062. if (version) {
  63063. // If the version in the JSON file is > than the version in DB
  63064. if (_this.manifestVersionFound > version.data) {
  63065. _this.mustUpdateRessources = true;
  63066. updateInDBCallback();
  63067. }
  63068. else {
  63069. callback(version.data);
  63070. }
  63071. }
  63072. else {
  63073. _this.mustUpdateRessources = true;
  63074. updateInDBCallback();
  63075. }
  63076. };
  63077. transaction.onabort = function (event) {
  63078. callback(-1);
  63079. };
  63080. var getRequest = transaction.objectStore("versions").get(url);
  63081. getRequest.onsuccess = function (event) {
  63082. version = (event.target).result;
  63083. };
  63084. getRequest.onerror = function (event) {
  63085. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  63086. callback(-1);
  63087. };
  63088. }
  63089. catch (ex) {
  63090. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  63091. callback(-1);
  63092. }
  63093. }
  63094. else {
  63095. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  63096. callback(-1);
  63097. }
  63098. };
  63099. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  63100. var _this = this;
  63101. if (this.isSupported && !this.hasReachedQuota && this.db) {
  63102. try {
  63103. // Open a transaction to the database
  63104. var transaction = this.db.transaction(["versions"], "readwrite");
  63105. // the transaction could abort because of a QuotaExceededError error
  63106. transaction.onabort = function (event) {
  63107. try {
  63108. var error = event.srcElement['error'];
  63109. if (error && error.name === "QuotaExceededError") {
  63110. _this.hasReachedQuota = true;
  63111. }
  63112. }
  63113. catch (ex) { }
  63114. callback(-1);
  63115. };
  63116. transaction.oncomplete = function (event) {
  63117. callback(_this.manifestVersionFound);
  63118. };
  63119. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  63120. // Put the scene into the database
  63121. var addRequest = transaction.objectStore("versions").put(newVersion);
  63122. addRequest.onsuccess = function (event) {
  63123. };
  63124. addRequest.onerror = function (event) {
  63125. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  63126. };
  63127. }
  63128. catch (ex) {
  63129. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  63130. callback(-1);
  63131. }
  63132. }
  63133. else {
  63134. callback(-1);
  63135. }
  63136. };
  63137. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  63138. var _this = this;
  63139. var completeUrl = Database.ReturnFullUrlLocation(url);
  63140. var saveAndLoadFile = function () {
  63141. // the scene is not yet in the DB, let's try to save it
  63142. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  63143. };
  63144. this._checkVersionFromDB(completeUrl, function (version) {
  63145. if (version !== -1) {
  63146. if (!_this.mustUpdateRessources) {
  63147. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  63148. }
  63149. else {
  63150. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  63151. }
  63152. }
  63153. else {
  63154. if (errorCallback) {
  63155. errorCallback();
  63156. }
  63157. }
  63158. });
  63159. };
  63160. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  63161. if (this.isSupported && this.db) {
  63162. var targetStore;
  63163. if (url.indexOf(".babylon") !== -1) {
  63164. targetStore = "scenes";
  63165. }
  63166. else {
  63167. targetStore = "textures";
  63168. }
  63169. var file;
  63170. var transaction = this.db.transaction([targetStore]);
  63171. transaction.oncomplete = function (event) {
  63172. if (file) {
  63173. callback(file.data);
  63174. }
  63175. else {
  63176. notInDBCallback();
  63177. }
  63178. };
  63179. transaction.onabort = function (event) {
  63180. notInDBCallback();
  63181. };
  63182. var getRequest = transaction.objectStore(targetStore).get(url);
  63183. getRequest.onsuccess = function (event) {
  63184. file = (event.target).result;
  63185. };
  63186. getRequest.onerror = function (event) {
  63187. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  63188. notInDBCallback();
  63189. };
  63190. }
  63191. else {
  63192. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  63193. callback();
  63194. }
  63195. };
  63196. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  63197. var _this = this;
  63198. if (this.isSupported) {
  63199. var targetStore;
  63200. if (url.indexOf(".babylon") !== -1) {
  63201. targetStore = "scenes";
  63202. }
  63203. else {
  63204. targetStore = "textures";
  63205. }
  63206. // Create XHR
  63207. var xhr = new XMLHttpRequest();
  63208. var fileData;
  63209. xhr.open("GET", url, true);
  63210. if (useArrayBuffer) {
  63211. xhr.responseType = "arraybuffer";
  63212. }
  63213. if (progressCallback) {
  63214. xhr.onprogress = progressCallback;
  63215. }
  63216. xhr.addEventListener("load", function () {
  63217. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  63218. // Blob as response (XHR2)
  63219. //fileData = xhr.responseText;
  63220. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  63221. if (!_this.hasReachedQuota && _this.db) {
  63222. // Open a transaction to the database
  63223. var transaction = _this.db.transaction([targetStore], "readwrite");
  63224. // the transaction could abort because of a QuotaExceededError error
  63225. transaction.onabort = function (event) {
  63226. try {
  63227. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  63228. var error = event.srcElement['error'];
  63229. if (error && error.name === "QuotaExceededError") {
  63230. _this.hasReachedQuota = true;
  63231. }
  63232. }
  63233. catch (ex) { }
  63234. callback(fileData);
  63235. };
  63236. transaction.oncomplete = function (event) {
  63237. callback(fileData);
  63238. };
  63239. var newFile;
  63240. if (targetStore === "scenes") {
  63241. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  63242. }
  63243. else {
  63244. newFile = { textureUrl: url, data: fileData };
  63245. }
  63246. try {
  63247. // Put the scene into the database
  63248. var addRequest = transaction.objectStore(targetStore).put(newFile);
  63249. addRequest.onsuccess = function (event) {
  63250. };
  63251. addRequest.onerror = function (event) {
  63252. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  63253. };
  63254. }
  63255. catch (ex) {
  63256. callback(fileData);
  63257. }
  63258. }
  63259. else {
  63260. callback(fileData);
  63261. }
  63262. }
  63263. else {
  63264. callback();
  63265. }
  63266. }, false);
  63267. xhr.addEventListener("error", function (event) {
  63268. BABYLON.Tools.Error("error on XHR request.");
  63269. callback();
  63270. }, false);
  63271. xhr.send();
  63272. }
  63273. else {
  63274. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  63275. callback();
  63276. }
  63277. };
  63278. Database.IsUASupportingBlobStorage = true;
  63279. Database.IDBStorageEnabled = true;
  63280. Database.parseURL = function (url) {
  63281. var a = document.createElement('a');
  63282. a.href = url;
  63283. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  63284. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  63285. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  63286. return absLocation;
  63287. };
  63288. Database.ReturnFullUrlLocation = function (url) {
  63289. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  63290. return (Database.parseURL(window.location.href) + url);
  63291. }
  63292. else {
  63293. return url;
  63294. }
  63295. };
  63296. return Database;
  63297. }());
  63298. BABYLON.Database = Database;
  63299. })(BABYLON || (BABYLON = {}));
  63300. //# sourceMappingURL=babylon.database.js.map
  63301. var BABYLON;
  63302. (function (BABYLON) {
  63303. var FresnelParameters = /** @class */ (function () {
  63304. function FresnelParameters() {
  63305. this._isEnabled = true;
  63306. this.leftColor = BABYLON.Color3.White();
  63307. this.rightColor = BABYLON.Color3.Black();
  63308. this.bias = 0;
  63309. this.power = 1;
  63310. }
  63311. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  63312. get: function () {
  63313. return this._isEnabled;
  63314. },
  63315. set: function (value) {
  63316. if (this._isEnabled === value) {
  63317. return;
  63318. }
  63319. this._isEnabled = value;
  63320. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  63321. },
  63322. enumerable: true,
  63323. configurable: true
  63324. });
  63325. FresnelParameters.prototype.clone = function () {
  63326. var newFresnelParameters = new FresnelParameters();
  63327. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  63328. return newFresnelParameters;
  63329. };
  63330. FresnelParameters.prototype.serialize = function () {
  63331. var serializationObject = {};
  63332. serializationObject.isEnabled = this.isEnabled;
  63333. serializationObject.leftColor = this.leftColor;
  63334. serializationObject.rightColor = this.rightColor;
  63335. serializationObject.bias = this.bias;
  63336. serializationObject.power = this.power;
  63337. return serializationObject;
  63338. };
  63339. FresnelParameters.Parse = function (parsedFresnelParameters) {
  63340. var fresnelParameters = new FresnelParameters();
  63341. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  63342. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  63343. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  63344. fresnelParameters.bias = parsedFresnelParameters.bias;
  63345. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  63346. return fresnelParameters;
  63347. };
  63348. return FresnelParameters;
  63349. }());
  63350. BABYLON.FresnelParameters = FresnelParameters;
  63351. })(BABYLON || (BABYLON = {}));
  63352. //# sourceMappingURL=babylon.fresnelParameters.js.map
  63353. var BABYLON;
  63354. (function (BABYLON) {
  63355. var MultiMaterial = /** @class */ (function (_super) {
  63356. __extends(MultiMaterial, _super);
  63357. function MultiMaterial(name, scene) {
  63358. var _this = _super.call(this, name, scene, true) || this;
  63359. scene.multiMaterials.push(_this);
  63360. _this.subMaterials = new Array();
  63361. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  63362. return _this;
  63363. }
  63364. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  63365. get: function () {
  63366. return this._subMaterials;
  63367. },
  63368. set: function (value) {
  63369. this._subMaterials = value;
  63370. this._hookArray(value);
  63371. },
  63372. enumerable: true,
  63373. configurable: true
  63374. });
  63375. MultiMaterial.prototype._hookArray = function (array) {
  63376. var _this = this;
  63377. var oldPush = array.push;
  63378. array.push = function () {
  63379. var items = [];
  63380. for (var _i = 0; _i < arguments.length; _i++) {
  63381. items[_i] = arguments[_i];
  63382. }
  63383. var result = oldPush.apply(array, items);
  63384. _this._markAllSubMeshesAsTexturesDirty();
  63385. return result;
  63386. };
  63387. var oldSplice = array.splice;
  63388. array.splice = function (index, deleteCount) {
  63389. var deleted = oldSplice.apply(array, [index, deleteCount]);
  63390. _this._markAllSubMeshesAsTexturesDirty();
  63391. return deleted;
  63392. };
  63393. };
  63394. // Properties
  63395. MultiMaterial.prototype.getSubMaterial = function (index) {
  63396. if (index < 0 || index >= this.subMaterials.length) {
  63397. return this.getScene().defaultMaterial;
  63398. }
  63399. return this.subMaterials[index];
  63400. };
  63401. MultiMaterial.prototype.getActiveTextures = function () {
  63402. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  63403. if (subMaterial) {
  63404. return subMaterial.getActiveTextures();
  63405. }
  63406. else {
  63407. return [];
  63408. }
  63409. }));
  63410. var _a;
  63411. };
  63412. // Methods
  63413. MultiMaterial.prototype.getClassName = function () {
  63414. return "MultiMaterial";
  63415. };
  63416. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  63417. for (var index = 0; index < this.subMaterials.length; index++) {
  63418. var subMaterial = this.subMaterials[index];
  63419. if (subMaterial) {
  63420. if (subMaterial.storeEffectOnSubMeshes) {
  63421. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  63422. return false;
  63423. }
  63424. continue;
  63425. }
  63426. if (!subMaterial.isReady(mesh)) {
  63427. return false;
  63428. }
  63429. }
  63430. }
  63431. return true;
  63432. };
  63433. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  63434. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  63435. for (var index = 0; index < this.subMaterials.length; index++) {
  63436. var subMaterial = null;
  63437. var current = this.subMaterials[index];
  63438. if (cloneChildren && current) {
  63439. subMaterial = current.clone(name + "-" + current.name);
  63440. }
  63441. else {
  63442. subMaterial = this.subMaterials[index];
  63443. }
  63444. newMultiMaterial.subMaterials.push(subMaterial);
  63445. }
  63446. return newMultiMaterial;
  63447. };
  63448. MultiMaterial.prototype.serialize = function () {
  63449. var serializationObject = {};
  63450. serializationObject.name = this.name;
  63451. serializationObject.id = this.id;
  63452. if (BABYLON.Tags) {
  63453. serializationObject.tags = BABYLON.Tags.GetTags(this);
  63454. }
  63455. serializationObject.materials = [];
  63456. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  63457. var subMat = this.subMaterials[matIndex];
  63458. if (subMat) {
  63459. serializationObject.materials.push(subMat.id);
  63460. }
  63461. else {
  63462. serializationObject.materials.push(null);
  63463. }
  63464. }
  63465. return serializationObject;
  63466. };
  63467. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  63468. var scene = this.getScene();
  63469. if (!scene) {
  63470. return;
  63471. }
  63472. var index = scene.multiMaterials.indexOf(this);
  63473. if (index >= 0) {
  63474. scene.multiMaterials.splice(index, 1);
  63475. }
  63476. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  63477. };
  63478. return MultiMaterial;
  63479. }(BABYLON.Material));
  63480. BABYLON.MultiMaterial = MultiMaterial;
  63481. })(BABYLON || (BABYLON = {}));
  63482. //# sourceMappingURL=babylon.multiMaterial.js.map
  63483. var BABYLON;
  63484. (function (BABYLON) {
  63485. var FreeCameraTouchInput = /** @class */ (function () {
  63486. function FreeCameraTouchInput() {
  63487. this._offsetX = null;
  63488. this._offsetY = null;
  63489. this._pointerPressed = new Array();
  63490. this.touchAngularSensibility = 200000.0;
  63491. this.touchMoveSensibility = 250.0;
  63492. }
  63493. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  63494. var _this = this;
  63495. var previousPosition = null;
  63496. if (this._pointerInput === undefined) {
  63497. this._onLostFocus = function (evt) {
  63498. _this._offsetX = null;
  63499. _this._offsetY = null;
  63500. };
  63501. this._pointerInput = function (p, s) {
  63502. var evt = p.event;
  63503. if (evt.pointerType === "mouse") {
  63504. return;
  63505. }
  63506. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  63507. if (!noPreventDefault) {
  63508. evt.preventDefault();
  63509. }
  63510. _this._pointerPressed.push(evt.pointerId);
  63511. if (_this._pointerPressed.length !== 1) {
  63512. return;
  63513. }
  63514. previousPosition = {
  63515. x: evt.clientX,
  63516. y: evt.clientY
  63517. };
  63518. }
  63519. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  63520. if (!noPreventDefault) {
  63521. evt.preventDefault();
  63522. }
  63523. var index = _this._pointerPressed.indexOf(evt.pointerId);
  63524. if (index === -1) {
  63525. return;
  63526. }
  63527. _this._pointerPressed.splice(index, 1);
  63528. if (index != 0) {
  63529. return;
  63530. }
  63531. previousPosition = null;
  63532. _this._offsetX = null;
  63533. _this._offsetY = null;
  63534. }
  63535. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  63536. if (!noPreventDefault) {
  63537. evt.preventDefault();
  63538. }
  63539. if (!previousPosition) {
  63540. return;
  63541. }
  63542. var index = _this._pointerPressed.indexOf(evt.pointerId);
  63543. if (index != 0) {
  63544. return;
  63545. }
  63546. _this._offsetX = evt.clientX - previousPosition.x;
  63547. _this._offsetY = -(evt.clientY - previousPosition.y);
  63548. }
  63549. };
  63550. }
  63551. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  63552. if (this._onLostFocus) {
  63553. element.addEventListener("blur", this._onLostFocus);
  63554. }
  63555. };
  63556. FreeCameraTouchInput.prototype.detachControl = function (element) {
  63557. if (this._pointerInput && element) {
  63558. if (this._observer) {
  63559. this.camera.getScene().onPointerObservable.remove(this._observer);
  63560. this._observer = null;
  63561. }
  63562. if (this._onLostFocus) {
  63563. element.removeEventListener("blur", this._onLostFocus);
  63564. this._onLostFocus = null;
  63565. }
  63566. this._pointerPressed = [];
  63567. this._offsetX = null;
  63568. this._offsetY = null;
  63569. }
  63570. };
  63571. FreeCameraTouchInput.prototype.checkInputs = function () {
  63572. if (this._offsetX && this._offsetY) {
  63573. var camera = this.camera;
  63574. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  63575. if (this._pointerPressed.length > 1) {
  63576. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  63577. }
  63578. else {
  63579. var speed = camera._computeLocalCameraSpeed();
  63580. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  63581. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  63582. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  63583. }
  63584. }
  63585. };
  63586. FreeCameraTouchInput.prototype.getClassName = function () {
  63587. return "FreeCameraTouchInput";
  63588. };
  63589. FreeCameraTouchInput.prototype.getSimpleName = function () {
  63590. return "touch";
  63591. };
  63592. __decorate([
  63593. BABYLON.serialize()
  63594. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  63595. __decorate([
  63596. BABYLON.serialize()
  63597. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  63598. return FreeCameraTouchInput;
  63599. }());
  63600. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  63601. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  63602. })(BABYLON || (BABYLON = {}));
  63603. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  63604. var BABYLON;
  63605. (function (BABYLON) {
  63606. // We're mainly based on the logic defined into the FreeCamera code
  63607. var TouchCamera = /** @class */ (function (_super) {
  63608. __extends(TouchCamera, _super);
  63609. //-- end properties for backward compatibility for inputs
  63610. function TouchCamera(name, position, scene) {
  63611. var _this = _super.call(this, name, position, scene) || this;
  63612. _this.inputs.addTouch();
  63613. _this._setupInputs();
  63614. return _this;
  63615. }
  63616. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  63617. //-- Begin properties for backward compatibility for inputs
  63618. get: function () {
  63619. var touch = this.inputs.attached["touch"];
  63620. if (touch)
  63621. return touch.touchAngularSensibility;
  63622. return 0;
  63623. },
  63624. set: function (value) {
  63625. var touch = this.inputs.attached["touch"];
  63626. if (touch)
  63627. touch.touchAngularSensibility = value;
  63628. },
  63629. enumerable: true,
  63630. configurable: true
  63631. });
  63632. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  63633. get: function () {
  63634. var touch = this.inputs.attached["touch"];
  63635. if (touch)
  63636. return touch.touchMoveSensibility;
  63637. return 0;
  63638. },
  63639. set: function (value) {
  63640. var touch = this.inputs.attached["touch"];
  63641. if (touch)
  63642. touch.touchMoveSensibility = value;
  63643. },
  63644. enumerable: true,
  63645. configurable: true
  63646. });
  63647. TouchCamera.prototype.getClassName = function () {
  63648. return "TouchCamera";
  63649. };
  63650. TouchCamera.prototype._setupInputs = function () {
  63651. var mouse = this.inputs.attached["mouse"];
  63652. if (mouse) {
  63653. mouse.touchEnabled = false;
  63654. }
  63655. };
  63656. return TouchCamera;
  63657. }(BABYLON.FreeCamera));
  63658. BABYLON.TouchCamera = TouchCamera;
  63659. })(BABYLON || (BABYLON = {}));
  63660. //# sourceMappingURL=babylon.touchCamera.js.map
  63661. var BABYLON;
  63662. (function (BABYLON) {
  63663. var ProceduralTexture = /** @class */ (function (_super) {
  63664. __extends(ProceduralTexture, _super);
  63665. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  63666. if (fallbackTexture === void 0) { fallbackTexture = null; }
  63667. if (generateMipMaps === void 0) { generateMipMaps = true; }
  63668. if (isCube === void 0) { isCube = false; }
  63669. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  63670. _this.isCube = isCube;
  63671. _this.isEnabled = true;
  63672. _this._currentRefreshId = -1;
  63673. _this._refreshRate = 1;
  63674. _this._vertexBuffers = {};
  63675. _this._uniforms = new Array();
  63676. _this._samplers = new Array();
  63677. _this._textures = {};
  63678. _this._floats = {};
  63679. _this._floatsArrays = {};
  63680. _this._colors3 = {};
  63681. _this._colors4 = {};
  63682. _this._vectors2 = {};
  63683. _this._vectors3 = {};
  63684. _this._matrices = {};
  63685. _this._fallbackTextureUsed = false;
  63686. scene._proceduralTextures.push(_this);
  63687. _this._engine = scene.getEngine();
  63688. _this.name = name;
  63689. _this.isRenderTarget = true;
  63690. _this._size = size;
  63691. _this._generateMipMaps = generateMipMaps;
  63692. _this.setFragment(fragment);
  63693. _this._fallbackTexture = fallbackTexture;
  63694. if (isCube) {
  63695. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  63696. _this.setFloat("face", 0);
  63697. }
  63698. else {
  63699. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  63700. }
  63701. // VBO
  63702. var vertices = [];
  63703. vertices.push(1, 1);
  63704. vertices.push(-1, 1);
  63705. vertices.push(-1, -1);
  63706. vertices.push(1, -1);
  63707. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  63708. _this._createIndexBuffer();
  63709. return _this;
  63710. }
  63711. ProceduralTexture.prototype._createIndexBuffer = function () {
  63712. var engine = this._engine;
  63713. // Indices
  63714. var indices = [];
  63715. indices.push(0);
  63716. indices.push(1);
  63717. indices.push(2);
  63718. indices.push(0);
  63719. indices.push(2);
  63720. indices.push(3);
  63721. this._indexBuffer = engine.createIndexBuffer(indices);
  63722. };
  63723. ProceduralTexture.prototype._rebuild = function () {
  63724. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  63725. if (vb) {
  63726. vb._rebuild();
  63727. }
  63728. this._createIndexBuffer();
  63729. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  63730. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  63731. }
  63732. };
  63733. ProceduralTexture.prototype.reset = function () {
  63734. if (this._effect === undefined) {
  63735. return;
  63736. }
  63737. var engine = this._engine;
  63738. engine._releaseEffect(this._effect);
  63739. };
  63740. ProceduralTexture.prototype.isReady = function () {
  63741. var _this = this;
  63742. var engine = this._engine;
  63743. var shaders;
  63744. if (!this._fragment) {
  63745. return false;
  63746. }
  63747. if (this._fallbackTextureUsed) {
  63748. return true;
  63749. }
  63750. if (this._fragment.fragmentElement !== undefined) {
  63751. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  63752. }
  63753. else {
  63754. shaders = { vertex: "procedural", fragment: this._fragment };
  63755. }
  63756. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  63757. _this.releaseInternalTexture();
  63758. if (_this._fallbackTexture) {
  63759. _this._texture = _this._fallbackTexture._texture;
  63760. if (_this._texture) {
  63761. _this._texture.incrementReferences();
  63762. }
  63763. }
  63764. _this._fallbackTextureUsed = true;
  63765. });
  63766. return this._effect.isReady();
  63767. };
  63768. ProceduralTexture.prototype.resetRefreshCounter = function () {
  63769. this._currentRefreshId = -1;
  63770. };
  63771. ProceduralTexture.prototype.setFragment = function (fragment) {
  63772. this._fragment = fragment;
  63773. };
  63774. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  63775. get: function () {
  63776. return this._refreshRate;
  63777. },
  63778. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  63779. set: function (value) {
  63780. this._refreshRate = value;
  63781. this.resetRefreshCounter();
  63782. },
  63783. enumerable: true,
  63784. configurable: true
  63785. });
  63786. ProceduralTexture.prototype._shouldRender = function () {
  63787. if (!this.isEnabled || !this.isReady() || !this._texture) {
  63788. return false;
  63789. }
  63790. if (this._fallbackTextureUsed) {
  63791. return false;
  63792. }
  63793. if (this._currentRefreshId === -1) {
  63794. this._currentRefreshId = 1;
  63795. return true;
  63796. }
  63797. if (this.refreshRate === this._currentRefreshId) {
  63798. this._currentRefreshId = 1;
  63799. return true;
  63800. }
  63801. this._currentRefreshId++;
  63802. return false;
  63803. };
  63804. ProceduralTexture.prototype.getRenderSize = function () {
  63805. return this._size;
  63806. };
  63807. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  63808. if (this._fallbackTextureUsed) {
  63809. return;
  63810. }
  63811. this.releaseInternalTexture();
  63812. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  63813. };
  63814. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  63815. if (this._uniforms.indexOf(uniformName) === -1) {
  63816. this._uniforms.push(uniformName);
  63817. }
  63818. };
  63819. ProceduralTexture.prototype.setTexture = function (name, texture) {
  63820. if (this._samplers.indexOf(name) === -1) {
  63821. this._samplers.push(name);
  63822. }
  63823. this._textures[name] = texture;
  63824. return this;
  63825. };
  63826. ProceduralTexture.prototype.setFloat = function (name, value) {
  63827. this._checkUniform(name);
  63828. this._floats[name] = value;
  63829. return this;
  63830. };
  63831. ProceduralTexture.prototype.setFloats = function (name, value) {
  63832. this._checkUniform(name);
  63833. this._floatsArrays[name] = value;
  63834. return this;
  63835. };
  63836. ProceduralTexture.prototype.setColor3 = function (name, value) {
  63837. this._checkUniform(name);
  63838. this._colors3[name] = value;
  63839. return this;
  63840. };
  63841. ProceduralTexture.prototype.setColor4 = function (name, value) {
  63842. this._checkUniform(name);
  63843. this._colors4[name] = value;
  63844. return this;
  63845. };
  63846. ProceduralTexture.prototype.setVector2 = function (name, value) {
  63847. this._checkUniform(name);
  63848. this._vectors2[name] = value;
  63849. return this;
  63850. };
  63851. ProceduralTexture.prototype.setVector3 = function (name, value) {
  63852. this._checkUniform(name);
  63853. this._vectors3[name] = value;
  63854. return this;
  63855. };
  63856. ProceduralTexture.prototype.setMatrix = function (name, value) {
  63857. this._checkUniform(name);
  63858. this._matrices[name] = value;
  63859. return this;
  63860. };
  63861. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  63862. var scene = this.getScene();
  63863. if (!scene) {
  63864. return;
  63865. }
  63866. var engine = this._engine;
  63867. // Render
  63868. engine.enableEffect(this._effect);
  63869. engine.setState(false);
  63870. // Texture
  63871. for (var name in this._textures) {
  63872. this._effect.setTexture(name, this._textures[name]);
  63873. }
  63874. // Float
  63875. for (name in this._floats) {
  63876. this._effect.setFloat(name, this._floats[name]);
  63877. }
  63878. // Floats
  63879. for (name in this._floatsArrays) {
  63880. this._effect.setArray(name, this._floatsArrays[name]);
  63881. }
  63882. // Color3
  63883. for (name in this._colors3) {
  63884. this._effect.setColor3(name, this._colors3[name]);
  63885. }
  63886. // Color4
  63887. for (name in this._colors4) {
  63888. var color = this._colors4[name];
  63889. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  63890. }
  63891. // Vector2
  63892. for (name in this._vectors2) {
  63893. this._effect.setVector2(name, this._vectors2[name]);
  63894. }
  63895. // Vector3
  63896. for (name in this._vectors3) {
  63897. this._effect.setVector3(name, this._vectors3[name]);
  63898. }
  63899. // Matrix
  63900. for (name in this._matrices) {
  63901. this._effect.setMatrix(name, this._matrices[name]);
  63902. }
  63903. if (!this._texture) {
  63904. return;
  63905. }
  63906. if (this.isCube) {
  63907. for (var face = 0; face < 6; face++) {
  63908. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  63909. // VBOs
  63910. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  63911. this._effect.setFloat("face", face);
  63912. // Clear
  63913. engine.clear(scene.clearColor, true, true, true);
  63914. // Draw order
  63915. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  63916. // Mipmaps
  63917. if (face === 5) {
  63918. engine.generateMipMapsForCubemap(this._texture);
  63919. }
  63920. }
  63921. }
  63922. else {
  63923. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  63924. // VBOs
  63925. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  63926. // Clear
  63927. engine.clear(scene.clearColor, true, true, true);
  63928. // Draw order
  63929. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  63930. }
  63931. // Unbind
  63932. engine.unBindFramebuffer(this._texture, this.isCube);
  63933. if (this.onGenerated) {
  63934. this.onGenerated();
  63935. }
  63936. };
  63937. ProceduralTexture.prototype.clone = function () {
  63938. var textureSize = this.getSize();
  63939. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  63940. // Base texture
  63941. newTexture.hasAlpha = this.hasAlpha;
  63942. newTexture.level = this.level;
  63943. // RenderTarget Texture
  63944. newTexture.coordinatesMode = this.coordinatesMode;
  63945. return newTexture;
  63946. };
  63947. ProceduralTexture.prototype.dispose = function () {
  63948. var scene = this.getScene();
  63949. if (!scene) {
  63950. return;
  63951. }
  63952. var index = scene._proceduralTextures.indexOf(this);
  63953. if (index >= 0) {
  63954. scene._proceduralTextures.splice(index, 1);
  63955. }
  63956. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  63957. if (vertexBuffer) {
  63958. vertexBuffer.dispose();
  63959. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  63960. }
  63961. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  63962. this._indexBuffer = null;
  63963. }
  63964. _super.prototype.dispose.call(this);
  63965. };
  63966. return ProceduralTexture;
  63967. }(BABYLON.Texture));
  63968. BABYLON.ProceduralTexture = ProceduralTexture;
  63969. })(BABYLON || (BABYLON = {}));
  63970. //# sourceMappingURL=babylon.proceduralTexture.js.map
  63971. var BABYLON;
  63972. (function (BABYLON) {
  63973. var CustomProceduralTexture = /** @class */ (function (_super) {
  63974. __extends(CustomProceduralTexture, _super);
  63975. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  63976. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  63977. _this._animate = true;
  63978. _this._time = 0;
  63979. _this._texturePath = texturePath;
  63980. //Try to load json
  63981. _this.loadJson(texturePath);
  63982. _this.refreshRate = 1;
  63983. return _this;
  63984. }
  63985. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  63986. var _this = this;
  63987. var noConfigFile = function () {
  63988. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  63989. try {
  63990. _this.setFragment(_this._texturePath);
  63991. }
  63992. catch (ex) {
  63993. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  63994. }
  63995. };
  63996. var configFileUrl = jsonUrl + "/config.json";
  63997. var xhr = new XMLHttpRequest();
  63998. xhr.open("GET", configFileUrl, true);
  63999. xhr.addEventListener("load", function () {
  64000. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  64001. try {
  64002. _this._config = JSON.parse(xhr.response);
  64003. _this.updateShaderUniforms();
  64004. _this.updateTextures();
  64005. _this.setFragment(_this._texturePath + "/custom");
  64006. _this._animate = _this._config.animate;
  64007. _this.refreshRate = _this._config.refreshrate;
  64008. }
  64009. catch (ex) {
  64010. noConfigFile();
  64011. }
  64012. }
  64013. else {
  64014. noConfigFile();
  64015. }
  64016. }, false);
  64017. xhr.addEventListener("error", function () {
  64018. noConfigFile();
  64019. }, false);
  64020. try {
  64021. xhr.send();
  64022. }
  64023. catch (ex) {
  64024. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  64025. }
  64026. };
  64027. CustomProceduralTexture.prototype.isReady = function () {
  64028. if (!_super.prototype.isReady.call(this)) {
  64029. return false;
  64030. }
  64031. for (var name in this._textures) {
  64032. var texture = this._textures[name];
  64033. if (!texture.isReady()) {
  64034. return false;
  64035. }
  64036. }
  64037. return true;
  64038. };
  64039. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  64040. var scene = this.getScene();
  64041. if (this._animate && scene) {
  64042. this._time += scene.getAnimationRatio() * 0.03;
  64043. this.updateShaderUniforms();
  64044. }
  64045. _super.prototype.render.call(this, useCameraPostProcess);
  64046. };
  64047. CustomProceduralTexture.prototype.updateTextures = function () {
  64048. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  64049. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  64050. }
  64051. };
  64052. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  64053. if (this._config) {
  64054. for (var j = 0; j < this._config.uniforms.length; j++) {
  64055. var uniform = this._config.uniforms[j];
  64056. switch (uniform.type) {
  64057. case "float":
  64058. this.setFloat(uniform.name, uniform.value);
  64059. break;
  64060. case "color3":
  64061. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  64062. break;
  64063. case "color4":
  64064. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  64065. break;
  64066. case "vector2":
  64067. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  64068. break;
  64069. case "vector3":
  64070. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  64071. break;
  64072. }
  64073. }
  64074. }
  64075. this.setFloat("time", this._time);
  64076. };
  64077. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  64078. get: function () {
  64079. return this._animate;
  64080. },
  64081. set: function (value) {
  64082. this._animate = value;
  64083. },
  64084. enumerable: true,
  64085. configurable: true
  64086. });
  64087. return CustomProceduralTexture;
  64088. }(BABYLON.ProceduralTexture));
  64089. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  64090. })(BABYLON || (BABYLON = {}));
  64091. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  64092. var BABYLON;
  64093. (function (BABYLON) {
  64094. var FreeCameraGamepadInput = /** @class */ (function () {
  64095. function FreeCameraGamepadInput() {
  64096. this.gamepadAngularSensibility = 200;
  64097. this.gamepadMoveSensibility = 40;
  64098. // private members
  64099. this._cameraTransform = BABYLON.Matrix.Identity();
  64100. this._deltaTransform = BABYLON.Vector3.Zero();
  64101. this._vector3 = BABYLON.Vector3.Zero();
  64102. this._vector2 = BABYLON.Vector2.Zero();
  64103. }
  64104. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  64105. var _this = this;
  64106. var manager = this.camera.getScene().gamepadManager;
  64107. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  64108. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  64109. // prioritize XBOX gamepads.
  64110. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  64111. _this.gamepad = gamepad;
  64112. }
  64113. }
  64114. });
  64115. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  64116. if (_this.gamepad === gamepad) {
  64117. _this.gamepad = null;
  64118. }
  64119. });
  64120. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  64121. };
  64122. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  64123. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  64124. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  64125. this.gamepad = null;
  64126. };
  64127. FreeCameraGamepadInput.prototype.checkInputs = function () {
  64128. if (this.gamepad && this.gamepad.leftStick) {
  64129. var camera = this.camera;
  64130. var LSValues = this.gamepad.leftStick;
  64131. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  64132. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  64133. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  64134. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  64135. var RSValues = this.gamepad.rightStick;
  64136. if (RSValues) {
  64137. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  64138. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  64139. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  64140. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  64141. }
  64142. else {
  64143. RSValues = { x: 0, y: 0 };
  64144. }
  64145. if (!camera.rotationQuaternion) {
  64146. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  64147. }
  64148. else {
  64149. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  64150. }
  64151. var speed = camera._computeLocalCameraSpeed() * 50.0;
  64152. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  64153. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  64154. camera.cameraDirection.addInPlace(this._deltaTransform);
  64155. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  64156. camera.cameraRotation.addInPlace(this._vector2);
  64157. }
  64158. };
  64159. FreeCameraGamepadInput.prototype.getClassName = function () {
  64160. return "FreeCameraGamepadInput";
  64161. };
  64162. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  64163. return "gamepad";
  64164. };
  64165. __decorate([
  64166. BABYLON.serialize()
  64167. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  64168. __decorate([
  64169. BABYLON.serialize()
  64170. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  64171. return FreeCameraGamepadInput;
  64172. }());
  64173. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  64174. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  64175. })(BABYLON || (BABYLON = {}));
  64176. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  64177. var BABYLON;
  64178. (function (BABYLON) {
  64179. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  64180. function ArcRotateCameraGamepadInput() {
  64181. this.gamepadRotationSensibility = 80;
  64182. this.gamepadMoveSensibility = 40;
  64183. }
  64184. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  64185. var _this = this;
  64186. var manager = this.camera.getScene().gamepadManager;
  64187. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  64188. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  64189. // prioritize XBOX gamepads.
  64190. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  64191. _this.gamepad = gamepad;
  64192. }
  64193. }
  64194. });
  64195. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  64196. if (_this.gamepad === gamepad) {
  64197. _this.gamepad = null;
  64198. }
  64199. });
  64200. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  64201. };
  64202. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  64203. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  64204. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  64205. this.gamepad = null;
  64206. };
  64207. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  64208. if (this.gamepad) {
  64209. var camera = this.camera;
  64210. var RSValues = this.gamepad.rightStick;
  64211. if (RSValues) {
  64212. if (RSValues.x != 0) {
  64213. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  64214. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  64215. camera.inertialAlphaOffset += normalizedRX;
  64216. }
  64217. }
  64218. if (RSValues.y != 0) {
  64219. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  64220. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  64221. camera.inertialBetaOffset += normalizedRY;
  64222. }
  64223. }
  64224. }
  64225. var LSValues = this.gamepad.leftStick;
  64226. if (LSValues && LSValues.y != 0) {
  64227. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  64228. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  64229. this.camera.inertialRadiusOffset -= normalizedLY;
  64230. }
  64231. }
  64232. }
  64233. };
  64234. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  64235. return "ArcRotateCameraGamepadInput";
  64236. };
  64237. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  64238. return "gamepad";
  64239. };
  64240. __decorate([
  64241. BABYLON.serialize()
  64242. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  64243. __decorate([
  64244. BABYLON.serialize()
  64245. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  64246. return ArcRotateCameraGamepadInput;
  64247. }());
  64248. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  64249. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  64250. })(BABYLON || (BABYLON = {}));
  64251. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  64252. var BABYLON;
  64253. (function (BABYLON) {
  64254. var GamepadManager = /** @class */ (function () {
  64255. function GamepadManager(_scene) {
  64256. var _this = this;
  64257. this._scene = _scene;
  64258. this._babylonGamepads = [];
  64259. this._oneGamepadConnected = false;
  64260. this._isMonitoring = false;
  64261. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  64262. if (!BABYLON.Tools.IsWindowObjectExist()) {
  64263. this._gamepadEventSupported = false;
  64264. }
  64265. else {
  64266. this._gamepadEventSupported = 'GamepadEvent' in window;
  64267. this._gamepadSupport = (navigator.getGamepads ||
  64268. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  64269. }
  64270. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  64271. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  64272. for (var i in _this._babylonGamepads) {
  64273. var gamepad = _this._babylonGamepads[i];
  64274. if (gamepad && gamepad._isConnected) {
  64275. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  64276. }
  64277. }
  64278. });
  64279. this._onGamepadConnectedEvent = function (evt) {
  64280. var gamepad = evt.gamepad;
  64281. if (gamepad.index in _this._babylonGamepads) {
  64282. if (_this._babylonGamepads[gamepad.index].isConnected) {
  64283. return;
  64284. }
  64285. }
  64286. var newGamepad;
  64287. if (_this._babylonGamepads[gamepad.index]) {
  64288. newGamepad = _this._babylonGamepads[gamepad.index];
  64289. newGamepad.browserGamepad = gamepad;
  64290. newGamepad._isConnected = true;
  64291. }
  64292. else {
  64293. newGamepad = _this._addNewGamepad(gamepad);
  64294. }
  64295. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  64296. _this._startMonitoringGamepads();
  64297. };
  64298. this._onGamepadDisconnectedEvent = function (evt) {
  64299. var gamepad = evt.gamepad;
  64300. // Remove the gamepad from the list of gamepads to monitor.
  64301. for (var i in _this._babylonGamepads) {
  64302. if (_this._babylonGamepads[i].index === gamepad.index) {
  64303. var disconnectedGamepad = _this._babylonGamepads[i];
  64304. disconnectedGamepad._isConnected = false;
  64305. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  64306. break;
  64307. }
  64308. }
  64309. };
  64310. if (this._gamepadSupport) {
  64311. //first add already-connected gamepads
  64312. this._updateGamepadObjects();
  64313. if (this._babylonGamepads.length) {
  64314. this._startMonitoringGamepads();
  64315. }
  64316. // Checking if the gamepad connected event is supported (like in Firefox)
  64317. if (this._gamepadEventSupported) {
  64318. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  64319. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  64320. }
  64321. else {
  64322. this._startMonitoringGamepads();
  64323. }
  64324. }
  64325. }
  64326. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  64327. get: function () {
  64328. return this._babylonGamepads;
  64329. },
  64330. enumerable: true,
  64331. configurable: true
  64332. });
  64333. GamepadManager.prototype.getGamepadByType = function (type) {
  64334. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  64335. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  64336. var gamepad = _a[_i];
  64337. if (gamepad && gamepad.type === type) {
  64338. return gamepad;
  64339. }
  64340. }
  64341. return null;
  64342. };
  64343. GamepadManager.prototype.dispose = function () {
  64344. if (this._gamepadEventSupported) {
  64345. if (this._onGamepadConnectedEvent) {
  64346. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  64347. }
  64348. if (this._onGamepadDisconnectedEvent) {
  64349. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  64350. }
  64351. this._onGamepadConnectedEvent = null;
  64352. this._onGamepadDisconnectedEvent = null;
  64353. }
  64354. this._babylonGamepads.forEach(function (gamepad) {
  64355. gamepad.dispose();
  64356. });
  64357. this.onGamepadConnectedObservable.clear();
  64358. this.onGamepadDisconnectedObservable.clear();
  64359. this._oneGamepadConnected = false;
  64360. this._stopMonitoringGamepads();
  64361. this._babylonGamepads = [];
  64362. };
  64363. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  64364. if (!this._oneGamepadConnected) {
  64365. this._oneGamepadConnected = true;
  64366. }
  64367. var newGamepad;
  64368. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  64369. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  64370. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  64371. }
  64372. else if (gamepad.pose) {
  64373. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  64374. }
  64375. else {
  64376. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  64377. }
  64378. this._babylonGamepads[newGamepad.index] = newGamepad;
  64379. return newGamepad;
  64380. };
  64381. GamepadManager.prototype._startMonitoringGamepads = function () {
  64382. if (!this._isMonitoring) {
  64383. this._isMonitoring = true;
  64384. //back-comp
  64385. if (!this._scene) {
  64386. this._checkGamepadsStatus();
  64387. }
  64388. }
  64389. };
  64390. GamepadManager.prototype._stopMonitoringGamepads = function () {
  64391. this._isMonitoring = false;
  64392. };
  64393. GamepadManager.prototype._checkGamepadsStatus = function () {
  64394. var _this = this;
  64395. // Hack to be compatible Chrome
  64396. this._updateGamepadObjects();
  64397. for (var i in this._babylonGamepads) {
  64398. var gamepad = this._babylonGamepads[i];
  64399. if (!gamepad || !gamepad.isConnected) {
  64400. continue;
  64401. }
  64402. gamepad.update();
  64403. }
  64404. if (this._isMonitoring && !this._scene) {
  64405. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  64406. }
  64407. };
  64408. // This function is called only on Chrome, which does not properly support
  64409. // connection/disconnection events and forces you to recopy again the gamepad object
  64410. GamepadManager.prototype._updateGamepadObjects = function () {
  64411. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  64412. for (var i = 0; i < gamepads.length; i++) {
  64413. if (gamepads[i]) {
  64414. if (!this._babylonGamepads[gamepads[i].index]) {
  64415. var newGamepad = this._addNewGamepad(gamepads[i]);
  64416. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  64417. }
  64418. else {
  64419. // Forced to copy again this object for Chrome for unknown reason
  64420. this._babylonGamepads[i].browserGamepad = gamepads[i];
  64421. if (!this._babylonGamepads[i].isConnected) {
  64422. this._babylonGamepads[i]._isConnected = true;
  64423. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  64424. }
  64425. }
  64426. }
  64427. }
  64428. };
  64429. return GamepadManager;
  64430. }());
  64431. BABYLON.GamepadManager = GamepadManager;
  64432. })(BABYLON || (BABYLON = {}));
  64433. //# sourceMappingURL=babylon.gamepadManager.js.map
  64434. var BABYLON;
  64435. (function (BABYLON) {
  64436. var StickValues = /** @class */ (function () {
  64437. function StickValues(x, y) {
  64438. this.x = x;
  64439. this.y = y;
  64440. }
  64441. return StickValues;
  64442. }());
  64443. BABYLON.StickValues = StickValues;
  64444. var Gamepad = /** @class */ (function () {
  64445. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  64446. if (leftStickX === void 0) { leftStickX = 0; }
  64447. if (leftStickY === void 0) { leftStickY = 1; }
  64448. if (rightStickX === void 0) { rightStickX = 2; }
  64449. if (rightStickY === void 0) { rightStickY = 3; }
  64450. this.id = id;
  64451. this.index = index;
  64452. this.browserGamepad = browserGamepad;
  64453. this._isConnected = true;
  64454. this._invertLeftStickY = false;
  64455. this.type = Gamepad.GAMEPAD;
  64456. this._leftStickAxisX = leftStickX;
  64457. this._leftStickAxisY = leftStickY;
  64458. this._rightStickAxisX = rightStickX;
  64459. this._rightStickAxisY = rightStickY;
  64460. if (this.browserGamepad.axes.length >= 2) {
  64461. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  64462. }
  64463. if (this.browserGamepad.axes.length >= 4) {
  64464. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  64465. }
  64466. }
  64467. Object.defineProperty(Gamepad.prototype, "isConnected", {
  64468. get: function () {
  64469. return this._isConnected;
  64470. },
  64471. enumerable: true,
  64472. configurable: true
  64473. });
  64474. Gamepad.prototype.onleftstickchanged = function (callback) {
  64475. this._onleftstickchanged = callback;
  64476. };
  64477. Gamepad.prototype.onrightstickchanged = function (callback) {
  64478. this._onrightstickchanged = callback;
  64479. };
  64480. Object.defineProperty(Gamepad.prototype, "leftStick", {
  64481. get: function () {
  64482. return this._leftStick;
  64483. },
  64484. set: function (newValues) {
  64485. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  64486. this._onleftstickchanged(newValues);
  64487. }
  64488. this._leftStick = newValues;
  64489. },
  64490. enumerable: true,
  64491. configurable: true
  64492. });
  64493. Object.defineProperty(Gamepad.prototype, "rightStick", {
  64494. get: function () {
  64495. return this._rightStick;
  64496. },
  64497. set: function (newValues) {
  64498. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  64499. this._onrightstickchanged(newValues);
  64500. }
  64501. this._rightStick = newValues;
  64502. },
  64503. enumerable: true,
  64504. configurable: true
  64505. });
  64506. Gamepad.prototype.update = function () {
  64507. if (this._leftStick) {
  64508. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  64509. if (this._invertLeftStickY) {
  64510. this.leftStick.y *= -1;
  64511. }
  64512. }
  64513. if (this._rightStick) {
  64514. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  64515. }
  64516. };
  64517. Gamepad.prototype.dispose = function () {
  64518. };
  64519. Gamepad.GAMEPAD = 0;
  64520. Gamepad.GENERIC = 1;
  64521. Gamepad.XBOX = 2;
  64522. Gamepad.POSE_ENABLED = 3;
  64523. return Gamepad;
  64524. }());
  64525. BABYLON.Gamepad = Gamepad;
  64526. var GenericPad = /** @class */ (function (_super) {
  64527. __extends(GenericPad, _super);
  64528. function GenericPad(id, index, browserGamepad) {
  64529. var _this = _super.call(this, id, index, browserGamepad) || this;
  64530. _this.onButtonDownObservable = new BABYLON.Observable();
  64531. _this.onButtonUpObservable = new BABYLON.Observable();
  64532. _this.type = Gamepad.GENERIC;
  64533. _this._buttons = new Array(browserGamepad.buttons.length);
  64534. return _this;
  64535. }
  64536. GenericPad.prototype.onbuttondown = function (callback) {
  64537. this._onbuttondown = callback;
  64538. };
  64539. GenericPad.prototype.onbuttonup = function (callback) {
  64540. this._onbuttonup = callback;
  64541. };
  64542. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  64543. if (newValue !== currentValue) {
  64544. if (newValue === 1) {
  64545. if (this._onbuttondown) {
  64546. this._onbuttondown(buttonIndex);
  64547. }
  64548. this.onButtonDownObservable.notifyObservers(buttonIndex);
  64549. }
  64550. if (newValue === 0) {
  64551. if (this._onbuttonup) {
  64552. this._onbuttonup(buttonIndex);
  64553. }
  64554. this.onButtonUpObservable.notifyObservers(buttonIndex);
  64555. }
  64556. }
  64557. return newValue;
  64558. };
  64559. GenericPad.prototype.update = function () {
  64560. _super.prototype.update.call(this);
  64561. for (var index = 0; index < this._buttons.length; index++) {
  64562. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  64563. }
  64564. };
  64565. GenericPad.prototype.dispose = function () {
  64566. _super.prototype.dispose.call(this);
  64567. this.onButtonDownObservable.clear();
  64568. this.onButtonUpObservable.clear();
  64569. };
  64570. return GenericPad;
  64571. }(Gamepad));
  64572. BABYLON.GenericPad = GenericPad;
  64573. })(BABYLON || (BABYLON = {}));
  64574. //# sourceMappingURL=babylon.gamepad.js.map
  64575. var BABYLON;
  64576. (function (BABYLON) {
  64577. var Xbox360Button;
  64578. (function (Xbox360Button) {
  64579. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  64580. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  64581. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  64582. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  64583. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  64584. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  64585. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  64586. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  64587. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  64588. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  64589. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  64590. var Xbox360Dpad;
  64591. (function (Xbox360Dpad) {
  64592. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  64593. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  64594. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  64595. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  64596. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  64597. var Xbox360Pad = /** @class */ (function (_super) {
  64598. __extends(Xbox360Pad, _super);
  64599. function Xbox360Pad(id, index, gamepad, xboxOne) {
  64600. if (xboxOne === void 0) { xboxOne = false; }
  64601. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  64602. _this._leftTrigger = 0;
  64603. _this._rightTrigger = 0;
  64604. _this.onButtonDownObservable = new BABYLON.Observable();
  64605. _this.onButtonUpObservable = new BABYLON.Observable();
  64606. _this.onPadDownObservable = new BABYLON.Observable();
  64607. _this.onPadUpObservable = new BABYLON.Observable();
  64608. _this._buttonA = 0;
  64609. _this._buttonB = 0;
  64610. _this._buttonX = 0;
  64611. _this._buttonY = 0;
  64612. _this._buttonBack = 0;
  64613. _this._buttonStart = 0;
  64614. _this._buttonLB = 0;
  64615. _this._buttonRB = 0;
  64616. _this._buttonLeftStick = 0;
  64617. _this._buttonRightStick = 0;
  64618. _this._dPadUp = 0;
  64619. _this._dPadDown = 0;
  64620. _this._dPadLeft = 0;
  64621. _this._dPadRight = 0;
  64622. _this._isXboxOnePad = false;
  64623. _this.type = BABYLON.Gamepad.XBOX;
  64624. _this._isXboxOnePad = xboxOne;
  64625. return _this;
  64626. }
  64627. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  64628. this._onlefttriggerchanged = callback;
  64629. };
  64630. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  64631. this._onrighttriggerchanged = callback;
  64632. };
  64633. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  64634. get: function () {
  64635. return this._leftTrigger;
  64636. },
  64637. set: function (newValue) {
  64638. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  64639. this._onlefttriggerchanged(newValue);
  64640. }
  64641. this._leftTrigger = newValue;
  64642. },
  64643. enumerable: true,
  64644. configurable: true
  64645. });
  64646. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  64647. get: function () {
  64648. return this._rightTrigger;
  64649. },
  64650. set: function (newValue) {
  64651. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  64652. this._onrighttriggerchanged(newValue);
  64653. }
  64654. this._rightTrigger = newValue;
  64655. },
  64656. enumerable: true,
  64657. configurable: true
  64658. });
  64659. Xbox360Pad.prototype.onbuttondown = function (callback) {
  64660. this._onbuttondown = callback;
  64661. };
  64662. Xbox360Pad.prototype.onbuttonup = function (callback) {
  64663. this._onbuttonup = callback;
  64664. };
  64665. Xbox360Pad.prototype.ondpaddown = function (callback) {
  64666. this._ondpaddown = callback;
  64667. };
  64668. Xbox360Pad.prototype.ondpadup = function (callback) {
  64669. this._ondpadup = callback;
  64670. };
  64671. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  64672. if (newValue !== currentValue) {
  64673. if (newValue === 1) {
  64674. if (this._onbuttondown) {
  64675. this._onbuttondown(buttonType);
  64676. }
  64677. this.onButtonDownObservable.notifyObservers(buttonType);
  64678. }
  64679. if (newValue === 0) {
  64680. if (this._onbuttonup) {
  64681. this._onbuttonup(buttonType);
  64682. }
  64683. this.onButtonUpObservable.notifyObservers(buttonType);
  64684. }
  64685. }
  64686. return newValue;
  64687. };
  64688. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  64689. if (newValue !== currentValue) {
  64690. if (newValue === 1) {
  64691. if (this._ondpaddown) {
  64692. this._ondpaddown(buttonType);
  64693. }
  64694. this.onPadDownObservable.notifyObservers(buttonType);
  64695. }
  64696. if (newValue === 0) {
  64697. if (this._ondpadup) {
  64698. this._ondpadup(buttonType);
  64699. }
  64700. this.onPadUpObservable.notifyObservers(buttonType);
  64701. }
  64702. }
  64703. return newValue;
  64704. };
  64705. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  64706. get: function () {
  64707. return this._buttonA;
  64708. },
  64709. set: function (value) {
  64710. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  64711. },
  64712. enumerable: true,
  64713. configurable: true
  64714. });
  64715. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  64716. get: function () {
  64717. return this._buttonB;
  64718. },
  64719. set: function (value) {
  64720. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  64721. },
  64722. enumerable: true,
  64723. configurable: true
  64724. });
  64725. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  64726. get: function () {
  64727. return this._buttonX;
  64728. },
  64729. set: function (value) {
  64730. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  64731. },
  64732. enumerable: true,
  64733. configurable: true
  64734. });
  64735. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  64736. get: function () {
  64737. return this._buttonY;
  64738. },
  64739. set: function (value) {
  64740. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  64741. },
  64742. enumerable: true,
  64743. configurable: true
  64744. });
  64745. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  64746. get: function () {
  64747. return this._buttonStart;
  64748. },
  64749. set: function (value) {
  64750. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  64751. },
  64752. enumerable: true,
  64753. configurable: true
  64754. });
  64755. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  64756. get: function () {
  64757. return this._buttonBack;
  64758. },
  64759. set: function (value) {
  64760. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  64761. },
  64762. enumerable: true,
  64763. configurable: true
  64764. });
  64765. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  64766. get: function () {
  64767. return this._buttonLB;
  64768. },
  64769. set: function (value) {
  64770. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  64771. },
  64772. enumerable: true,
  64773. configurable: true
  64774. });
  64775. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  64776. get: function () {
  64777. return this._buttonRB;
  64778. },
  64779. set: function (value) {
  64780. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  64781. },
  64782. enumerable: true,
  64783. configurable: true
  64784. });
  64785. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  64786. get: function () {
  64787. return this._buttonLeftStick;
  64788. },
  64789. set: function (value) {
  64790. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  64791. },
  64792. enumerable: true,
  64793. configurable: true
  64794. });
  64795. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  64796. get: function () {
  64797. return this._buttonRightStick;
  64798. },
  64799. set: function (value) {
  64800. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  64801. },
  64802. enumerable: true,
  64803. configurable: true
  64804. });
  64805. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  64806. get: function () {
  64807. return this._dPadUp;
  64808. },
  64809. set: function (value) {
  64810. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  64811. },
  64812. enumerable: true,
  64813. configurable: true
  64814. });
  64815. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  64816. get: function () {
  64817. return this._dPadDown;
  64818. },
  64819. set: function (value) {
  64820. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  64821. },
  64822. enumerable: true,
  64823. configurable: true
  64824. });
  64825. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  64826. get: function () {
  64827. return this._dPadLeft;
  64828. },
  64829. set: function (value) {
  64830. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  64831. },
  64832. enumerable: true,
  64833. configurable: true
  64834. });
  64835. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  64836. get: function () {
  64837. return this._dPadRight;
  64838. },
  64839. set: function (value) {
  64840. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  64841. },
  64842. enumerable: true,
  64843. configurable: true
  64844. });
  64845. Xbox360Pad.prototype.update = function () {
  64846. _super.prototype.update.call(this);
  64847. if (this._isXboxOnePad) {
  64848. this.buttonA = this.browserGamepad.buttons[0].value;
  64849. this.buttonB = this.browserGamepad.buttons[1].value;
  64850. this.buttonX = this.browserGamepad.buttons[2].value;
  64851. this.buttonY = this.browserGamepad.buttons[3].value;
  64852. this.buttonLB = this.browserGamepad.buttons[4].value;
  64853. this.buttonRB = this.browserGamepad.buttons[5].value;
  64854. this.leftTrigger = this.browserGamepad.axes[2];
  64855. this.rightTrigger = this.browserGamepad.axes[5];
  64856. this.buttonBack = this.browserGamepad.buttons[9].value;
  64857. this.buttonStart = this.browserGamepad.buttons[8].value;
  64858. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  64859. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  64860. this.dPadUp = this.browserGamepad.buttons[11].value;
  64861. this.dPadDown = this.browserGamepad.buttons[12].value;
  64862. this.dPadLeft = this.browserGamepad.buttons[13].value;
  64863. this.dPadRight = this.browserGamepad.buttons[14].value;
  64864. }
  64865. else {
  64866. this.buttonA = this.browserGamepad.buttons[0].value;
  64867. this.buttonB = this.browserGamepad.buttons[1].value;
  64868. this.buttonX = this.browserGamepad.buttons[2].value;
  64869. this.buttonY = this.browserGamepad.buttons[3].value;
  64870. this.buttonLB = this.browserGamepad.buttons[4].value;
  64871. this.buttonRB = this.browserGamepad.buttons[5].value;
  64872. this.leftTrigger = this.browserGamepad.buttons[6].value;
  64873. this.rightTrigger = this.browserGamepad.buttons[7].value;
  64874. this.buttonBack = this.browserGamepad.buttons[8].value;
  64875. this.buttonStart = this.browserGamepad.buttons[9].value;
  64876. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  64877. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  64878. this.dPadUp = this.browserGamepad.buttons[12].value;
  64879. this.dPadDown = this.browserGamepad.buttons[13].value;
  64880. this.dPadLeft = this.browserGamepad.buttons[14].value;
  64881. this.dPadRight = this.browserGamepad.buttons[15].value;
  64882. }
  64883. };
  64884. Xbox360Pad.prototype.dispose = function () {
  64885. _super.prototype.dispose.call(this);
  64886. this.onButtonDownObservable.clear();
  64887. this.onButtonUpObservable.clear();
  64888. this.onPadDownObservable.clear();
  64889. this.onPadUpObservable.clear();
  64890. };
  64891. return Xbox360Pad;
  64892. }(BABYLON.Gamepad));
  64893. BABYLON.Xbox360Pad = Xbox360Pad;
  64894. })(BABYLON || (BABYLON = {}));
  64895. //# sourceMappingURL=babylon.xboxGamepad.js.map
  64896. var BABYLON;
  64897. (function (BABYLON) {
  64898. var PoseEnabledControllerType;
  64899. (function (PoseEnabledControllerType) {
  64900. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  64901. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  64902. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  64903. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  64904. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 4] = "GENERIC";
  64905. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  64906. var PoseEnabledControllerHelper = /** @class */ (function () {
  64907. function PoseEnabledControllerHelper() {
  64908. }
  64909. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  64910. // Oculus Touch
  64911. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  64912. return new BABYLON.OculusTouchController(vrGamepad);
  64913. }
  64914. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  64915. return new BABYLON.WindowsMotionController(vrGamepad);
  64916. }
  64917. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  64918. return new BABYLON.ViveController(vrGamepad);
  64919. }
  64920. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0) {
  64921. return new BABYLON.GearVRController(vrGamepad);
  64922. }
  64923. else {
  64924. return new BABYLON.GenericController(vrGamepad);
  64925. }
  64926. };
  64927. return PoseEnabledControllerHelper;
  64928. }());
  64929. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  64930. var PoseEnabledController = /** @class */ (function (_super) {
  64931. __extends(PoseEnabledController, _super);
  64932. function PoseEnabledController(browserGamepad) {
  64933. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  64934. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  64935. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  64936. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  64937. // Represents device position and rotation in babylon space
  64938. _this.devicePosition = BABYLON.Vector3.Zero();
  64939. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  64940. _this.deviceScaleFactor = 1;
  64941. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  64942. _this._deviceToWorld = BABYLON.Matrix.Identity();
  64943. _this._workingMatrix = BABYLON.Matrix.Identity();
  64944. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  64945. _this.controllerType = PoseEnabledControllerType.GENERIC;
  64946. _this.position = BABYLON.Vector3.Zero();
  64947. _this.rotationQuaternion = new BABYLON.Quaternion();
  64948. _this._calculatedPosition = BABYLON.Vector3.Zero();
  64949. _this._calculatedRotation = new BABYLON.Quaternion();
  64950. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  64951. return _this;
  64952. }
  64953. PoseEnabledController.prototype.update = function () {
  64954. _super.prototype.update.call(this);
  64955. var pose = this.browserGamepad.pose;
  64956. this.updateFromDevice(pose);
  64957. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  64958. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  64959. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  64960. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  64961. if (this._mesh) {
  64962. this._mesh.position.copyFrom(this.devicePosition);
  64963. if (this._mesh.rotationQuaternion) {
  64964. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  64965. }
  64966. }
  64967. };
  64968. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  64969. if (poseData) {
  64970. this.rawPose = poseData;
  64971. if (poseData.position) {
  64972. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  64973. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  64974. this._deviceRoomPosition.z *= -1;
  64975. }
  64976. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  64977. this._calculatedPosition.addInPlace(this.position);
  64978. }
  64979. var pose = this.rawPose;
  64980. if (poseData.orientation && pose.orientation) {
  64981. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  64982. if (this._mesh) {
  64983. if (this._mesh.getScene().useRightHandedSystem) {
  64984. this._deviceRoomRotationQuaternion.z *= -1;
  64985. this._deviceRoomRotationQuaternion.w *= -1;
  64986. }
  64987. else {
  64988. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  64989. }
  64990. }
  64991. // if the camera is set, rotate to the camera's rotation
  64992. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  64993. }
  64994. }
  64995. };
  64996. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  64997. if (this._mesh) {
  64998. this._mesh.parent = null;
  64999. }
  65000. this._mesh = mesh;
  65001. if (this._poseControlledCamera) {
  65002. this._mesh.parent = this._poseControlledCamera;
  65003. }
  65004. if (!this._mesh.rotationQuaternion) {
  65005. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  65006. }
  65007. };
  65008. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  65009. this._poseControlledCamera = camera;
  65010. if (this._mesh) {
  65011. this._mesh.parent = this._poseControlledCamera;
  65012. }
  65013. };
  65014. PoseEnabledController.prototype.dispose = function () {
  65015. if (this._mesh) {
  65016. this._mesh.dispose();
  65017. }
  65018. this._mesh = null;
  65019. _super.prototype.dispose.call(this);
  65020. };
  65021. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  65022. get: function () {
  65023. return this._mesh;
  65024. },
  65025. enumerable: true,
  65026. configurable: true
  65027. });
  65028. PoseEnabledController.prototype.getForwardRay = function (length) {
  65029. if (length === void 0) { length = 100; }
  65030. if (!this.mesh) {
  65031. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  65032. }
  65033. var m = this.mesh.getWorldMatrix();
  65034. var origin = m.getTranslation();
  65035. var forward = new BABYLON.Vector3(0, 0, -1);
  65036. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  65037. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  65038. return new BABYLON.Ray(origin, direction, length);
  65039. };
  65040. return PoseEnabledController;
  65041. }(BABYLON.Gamepad));
  65042. BABYLON.PoseEnabledController = PoseEnabledController;
  65043. })(BABYLON || (BABYLON = {}));
  65044. //# sourceMappingURL=babylon.poseEnabledController.js.map
  65045. var BABYLON;
  65046. (function (BABYLON) {
  65047. var WebVRController = /** @class */ (function (_super) {
  65048. __extends(WebVRController, _super);
  65049. function WebVRController(vrGamepad) {
  65050. var _this = _super.call(this, vrGamepad) || this;
  65051. // Observables
  65052. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  65053. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  65054. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  65055. _this.onPadStateChangedObservable = new BABYLON.Observable();
  65056. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  65057. _this.pad = { x: 0, y: 0 };
  65058. // avoid GC, store state in a tmp object
  65059. _this._changes = {
  65060. pressChanged: false,
  65061. touchChanged: false,
  65062. valueChanged: false,
  65063. changed: false
  65064. };
  65065. _this._buttons = new Array(vrGamepad.buttons.length);
  65066. _this.hand = vrGamepad.hand;
  65067. return _this;
  65068. }
  65069. WebVRController.prototype.onButtonStateChange = function (callback) {
  65070. this._onButtonStateChange = callback;
  65071. };
  65072. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  65073. get: function () {
  65074. return this._defaultModel;
  65075. },
  65076. enumerable: true,
  65077. configurable: true
  65078. });
  65079. WebVRController.prototype.update = function () {
  65080. _super.prototype.update.call(this);
  65081. for (var index = 0; index < this._buttons.length; index++) {
  65082. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  65083. }
  65084. ;
  65085. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  65086. this.pad.x = this.leftStick.x;
  65087. this.pad.y = this.leftStick.y;
  65088. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  65089. }
  65090. };
  65091. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  65092. if (!newState) {
  65093. newState = {
  65094. pressed: false,
  65095. touched: false,
  65096. value: 0
  65097. };
  65098. }
  65099. if (!currentState) {
  65100. this._buttons[buttonIndex] = {
  65101. pressed: newState.pressed,
  65102. touched: newState.touched,
  65103. value: newState.value
  65104. };
  65105. return;
  65106. }
  65107. this._checkChanges(newState, currentState);
  65108. if (this._changes.changed) {
  65109. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  65110. this.handleButtonChange(buttonIndex, newState, this._changes);
  65111. }
  65112. this._buttons[buttonIndex].pressed = newState.pressed;
  65113. this._buttons[buttonIndex].touched = newState.touched;
  65114. // oculus triggers are never 0, thou not touched.
  65115. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  65116. };
  65117. WebVRController.prototype._checkChanges = function (newState, currentState) {
  65118. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  65119. this._changes.touchChanged = newState.touched !== currentState.touched;
  65120. this._changes.valueChanged = newState.value !== currentState.value;
  65121. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  65122. return this._changes;
  65123. };
  65124. WebVRController.prototype.dispose = function () {
  65125. _super.prototype.dispose.call(this);
  65126. this.onTriggerStateChangedObservable.clear();
  65127. this.onMainButtonStateChangedObservable.clear();
  65128. this.onSecondaryButtonStateChangedObservable.clear();
  65129. this.onPadStateChangedObservable.clear();
  65130. this.onPadValuesChangedObservable.clear();
  65131. };
  65132. return WebVRController;
  65133. }(BABYLON.PoseEnabledController));
  65134. BABYLON.WebVRController = WebVRController;
  65135. })(BABYLON || (BABYLON = {}));
  65136. //# sourceMappingURL=babylon.webVRController.js.map
  65137. var BABYLON;
  65138. (function (BABYLON) {
  65139. var OculusTouchController = /** @class */ (function (_super) {
  65140. __extends(OculusTouchController, _super);
  65141. function OculusTouchController(vrGamepad) {
  65142. var _this = _super.call(this, vrGamepad) || this;
  65143. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  65144. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  65145. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  65146. return _this;
  65147. }
  65148. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  65149. var _this = this;
  65150. var meshName;
  65151. // Hand
  65152. if (this.hand === 'left') {
  65153. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  65154. }
  65155. else {
  65156. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  65157. }
  65158. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  65159. /*
  65160. Parent Mesh name: oculus_touch_left
  65161. - body
  65162. - trigger
  65163. - thumbstick
  65164. - grip
  65165. - button_y
  65166. - button_x
  65167. - button_enter
  65168. */
  65169. _this._defaultModel = newMeshes[1];
  65170. _this.attachToMesh(_this._defaultModel);
  65171. if (meshLoaded) {
  65172. meshLoaded(_this._defaultModel);
  65173. }
  65174. });
  65175. };
  65176. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  65177. // helper getters for left and right hand.
  65178. get: function () {
  65179. if (this.hand === 'right') {
  65180. return this.onMainButtonStateChangedObservable;
  65181. }
  65182. else {
  65183. throw new Error('No A button on left hand');
  65184. }
  65185. },
  65186. enumerable: true,
  65187. configurable: true
  65188. });
  65189. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  65190. get: function () {
  65191. if (this.hand === 'right') {
  65192. return this.onSecondaryButtonStateChangedObservable;
  65193. }
  65194. else {
  65195. throw new Error('No B button on left hand');
  65196. }
  65197. },
  65198. enumerable: true,
  65199. configurable: true
  65200. });
  65201. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  65202. get: function () {
  65203. if (this.hand === 'left') {
  65204. return this.onMainButtonStateChangedObservable;
  65205. }
  65206. else {
  65207. throw new Error('No X button on right hand');
  65208. }
  65209. },
  65210. enumerable: true,
  65211. configurable: true
  65212. });
  65213. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  65214. get: function () {
  65215. if (this.hand === 'left') {
  65216. return this.onSecondaryButtonStateChangedObservable;
  65217. }
  65218. else {
  65219. throw new Error('No Y button on right hand');
  65220. }
  65221. },
  65222. enumerable: true,
  65223. configurable: true
  65224. });
  65225. /*
  65226. 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  65227. 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  65228. 2) secondary trigger (same)
  65229. 3) A (right) X (left), touch, pressed = value
  65230. 4) B / Y
  65231. 5) thumb rest
  65232. */
  65233. OculusTouchController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  65234. var notifyObject = state; //{ state: state, changes: changes };
  65235. var triggerDirection = this.hand === 'right' ? -1 : 1;
  65236. switch (buttonIdx) {
  65237. case 0:
  65238. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  65239. return;
  65240. case 1:// index trigger
  65241. if (this._defaultModel) {
  65242. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  65243. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  65244. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  65245. }
  65246. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  65247. return;
  65248. case 2:// secondary trigger
  65249. if (this._defaultModel) {
  65250. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  65251. }
  65252. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  65253. return;
  65254. case 3:
  65255. if (this._defaultModel) {
  65256. if (notifyObject.pressed) {
  65257. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  65258. }
  65259. else {
  65260. (this._defaultModel.getChildren()[1]).position.y = 0;
  65261. }
  65262. }
  65263. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  65264. return;
  65265. case 4:
  65266. if (this._defaultModel) {
  65267. if (notifyObject.pressed) {
  65268. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  65269. }
  65270. else {
  65271. (this._defaultModel.getChildren()[2]).position.y = 0;
  65272. }
  65273. }
  65274. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  65275. return;
  65276. case 5:
  65277. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  65278. return;
  65279. }
  65280. };
  65281. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  65282. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  65283. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  65284. return OculusTouchController;
  65285. }(BABYLON.WebVRController));
  65286. BABYLON.OculusTouchController = OculusTouchController;
  65287. })(BABYLON || (BABYLON = {}));
  65288. //# sourceMappingURL=babylon.oculusTouchController.js.map
  65289. var BABYLON;
  65290. (function (BABYLON) {
  65291. var ViveController = /** @class */ (function (_super) {
  65292. __extends(ViveController, _super);
  65293. function ViveController(vrGamepad) {
  65294. var _this = _super.call(this, vrGamepad) || this;
  65295. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  65296. _this._invertLeftStickY = true;
  65297. return _this;
  65298. }
  65299. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  65300. var _this = this;
  65301. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  65302. /*
  65303. Parent Mesh name: ViveWand
  65304. - body
  65305. - r_gripper
  65306. - l_gripper
  65307. - menu_button
  65308. - system_button
  65309. - trackpad
  65310. - trigger
  65311. - LED
  65312. */
  65313. _this._defaultModel = newMeshes[1];
  65314. _this.attachToMesh(_this._defaultModel);
  65315. if (meshLoaded) {
  65316. meshLoaded(_this._defaultModel);
  65317. }
  65318. });
  65319. };
  65320. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  65321. get: function () {
  65322. return this.onMainButtonStateChangedObservable;
  65323. },
  65324. enumerable: true,
  65325. configurable: true
  65326. });
  65327. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  65328. get: function () {
  65329. return this.onMainButtonStateChangedObservable;
  65330. },
  65331. enumerable: true,
  65332. configurable: true
  65333. });
  65334. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  65335. get: function () {
  65336. return this.onSecondaryButtonStateChangedObservable;
  65337. },
  65338. enumerable: true,
  65339. configurable: true
  65340. });
  65341. /**
  65342. * Vive mapping:
  65343. * 0: touchpad
  65344. * 1: trigger
  65345. * 2: left AND right buttons
  65346. * 3: menu button
  65347. */
  65348. ViveController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  65349. var notifyObject = state; //{ state: state, changes: changes };
  65350. switch (buttonIdx) {
  65351. case 0:
  65352. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  65353. return;
  65354. case 1:// index trigger
  65355. if (this._defaultModel) {
  65356. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  65357. }
  65358. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  65359. return;
  65360. case 2:// left AND right button
  65361. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  65362. return;
  65363. case 3:
  65364. if (this._defaultModel) {
  65365. if (notifyObject.pressed) {
  65366. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  65367. }
  65368. else {
  65369. (this._defaultModel.getChildren()[2]).position.y = 0;
  65370. }
  65371. }
  65372. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  65373. return;
  65374. }
  65375. };
  65376. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  65377. ViveController.MODEL_FILENAME = 'wand.babylon';
  65378. return ViveController;
  65379. }(BABYLON.WebVRController));
  65380. BABYLON.ViveController = ViveController;
  65381. })(BABYLON || (BABYLON = {}));
  65382. //# sourceMappingURL=babylon.viveController.js.map
  65383. var BABYLON;
  65384. (function (BABYLON) {
  65385. var GenericController = /** @class */ (function (_super) {
  65386. __extends(GenericController, _super);
  65387. function GenericController(vrGamepad) {
  65388. return _super.call(this, vrGamepad) || this;
  65389. }
  65390. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  65391. var _this = this;
  65392. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  65393. _this._defaultModel = newMeshes[1];
  65394. _this.attachToMesh(_this._defaultModel);
  65395. if (meshLoaded) {
  65396. meshLoaded(_this._defaultModel);
  65397. }
  65398. });
  65399. };
  65400. GenericController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  65401. console.log("Button id: " + buttonIdx + "state: ");
  65402. console.dir(state);
  65403. };
  65404. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  65405. GenericController.MODEL_FILENAME = 'generic.babylon';
  65406. return GenericController;
  65407. }(BABYLON.WebVRController));
  65408. BABYLON.GenericController = GenericController;
  65409. })(BABYLON || (BABYLON = {}));
  65410. //# sourceMappingURL=babylon.genericController.js.map
  65411. var BABYLON;
  65412. (function (BABYLON) {
  65413. var LoadedMeshInfo = /** @class */ (function () {
  65414. function LoadedMeshInfo() {
  65415. this.buttonMeshes = {};
  65416. this.axisMeshes = {};
  65417. }
  65418. return LoadedMeshInfo;
  65419. }());
  65420. var WindowsMotionController = /** @class */ (function (_super) {
  65421. __extends(WindowsMotionController, _super);
  65422. function WindowsMotionController(vrGamepad) {
  65423. var _this = _super.call(this, vrGamepad) || this;
  65424. _this._mapping = {
  65425. // Semantic button names
  65426. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  65427. // A mapping of the button name to glTF model node name
  65428. // that should be transformed by button value.
  65429. buttonMeshNames: {
  65430. 'trigger': 'SELECT',
  65431. 'menu': 'MENU',
  65432. 'grip': 'GRASP',
  65433. 'thumbstick': 'THUMBSTICK_PRESS',
  65434. 'trackpad': 'TOUCHPAD_PRESS'
  65435. },
  65436. // This mapping is used to translate from the Motion Controller to Babylon semantics
  65437. buttonObservableNames: {
  65438. 'trigger': 'onTriggerStateChangedObservable',
  65439. 'menu': 'onSecondaryButtonStateChangedObservable',
  65440. 'grip': 'onMainButtonStateChangedObservable',
  65441. 'thumbstick': 'onPadStateChangedObservable',
  65442. 'trackpad': 'onTrackpadChangedObservable'
  65443. },
  65444. // A mapping of the axis name to glTF model node name
  65445. // that should be transformed by axis value.
  65446. // This array mirrors the browserGamepad.axes array, such that
  65447. // the mesh corresponding to axis 0 is in this array index 0.
  65448. axisMeshNames: [
  65449. 'THUMBSTICK_X',
  65450. 'THUMBSTICK_Y',
  65451. 'TOUCHPAD_TOUCH_X',
  65452. 'TOUCHPAD_TOUCH_Y'
  65453. ],
  65454. pointingPoseMeshName: 'POINTING_POSE'
  65455. };
  65456. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  65457. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  65458. _this.trackpad = { x: 0, y: 0 };
  65459. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  65460. _this._loadedMeshInfo = null;
  65461. return _this;
  65462. }
  65463. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  65464. get: function () {
  65465. return this.onTriggerStateChangedObservable;
  65466. },
  65467. enumerable: true,
  65468. configurable: true
  65469. });
  65470. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  65471. get: function () {
  65472. return this.onSecondaryButtonStateChangedObservable;
  65473. },
  65474. enumerable: true,
  65475. configurable: true
  65476. });
  65477. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  65478. get: function () {
  65479. return this.onMainButtonStateChangedObservable;
  65480. },
  65481. enumerable: true,
  65482. configurable: true
  65483. });
  65484. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  65485. get: function () {
  65486. return this.onPadStateChangedObservable;
  65487. },
  65488. enumerable: true,
  65489. configurable: true
  65490. });
  65491. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  65492. get: function () {
  65493. return this.onTrackpadChangedObservable;
  65494. },
  65495. enumerable: true,
  65496. configurable: true
  65497. });
  65498. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  65499. get: function () {
  65500. return this.onTrackpadValuesChangedObservable;
  65501. },
  65502. enumerable: true,
  65503. configurable: true
  65504. });
  65505. /**
  65506. * Called once per frame by the engine.
  65507. */
  65508. WindowsMotionController.prototype.update = function () {
  65509. _super.prototype.update.call(this);
  65510. // Only need to animate axes if there is a loaded mesh
  65511. if (this._loadedMeshInfo) {
  65512. if (this.browserGamepad.axes) {
  65513. if (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y) {
  65514. this.trackpad.x = this.browserGamepad["axes"][2];
  65515. this.trackpad.y = this.browserGamepad["axes"][3];
  65516. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  65517. }
  65518. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  65519. this.lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  65520. }
  65521. }
  65522. }
  65523. };
  65524. /**
  65525. * Called once for each button that changed state since the last frame
  65526. * @param buttonIdx Which button index changed
  65527. * @param state New state of the button
  65528. * @param changes Which properties on the state changed since last frame
  65529. */
  65530. WindowsMotionController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  65531. var buttonName = this._mapping.buttons[buttonIdx];
  65532. if (!buttonName) {
  65533. return;
  65534. }
  65535. // Only emit events for buttons that we know how to map from index to name
  65536. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  65537. if (observable) {
  65538. observable.notifyObservers(state);
  65539. }
  65540. this.lerpButtonTransform(buttonName, state.value);
  65541. };
  65542. WindowsMotionController.prototype.lerpButtonTransform = function (buttonName, buttonValue) {
  65543. // If there is no loaded mesh, there is nothing to transform.
  65544. if (!this._loadedMeshInfo) {
  65545. return;
  65546. }
  65547. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  65548. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  65549. return;
  65550. }
  65551. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  65552. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  65553. };
  65554. WindowsMotionController.prototype.lerpAxisTransform = function (axis, axisValue) {
  65555. if (!this._loadedMeshInfo) {
  65556. return;
  65557. }
  65558. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  65559. if (!meshInfo) {
  65560. return;
  65561. }
  65562. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  65563. return;
  65564. }
  65565. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  65566. var lerpValue = axisValue * 0.5 + 0.5;
  65567. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  65568. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  65569. };
  65570. /**
  65571. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  65572. * @param scene scene in which to add meshes
  65573. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  65574. */
  65575. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  65576. var _this = this;
  65577. if (forceDefault === void 0) { forceDefault = false; }
  65578. var path;
  65579. var filename;
  65580. // Checking if GLB loader is present
  65581. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  65582. // Determine the device specific folder based on the ID suffix
  65583. var device = 'default';
  65584. if (this.id && !forceDefault) {
  65585. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  65586. device = ((match && match[0]) || device);
  65587. }
  65588. // Hand
  65589. if (this.hand === 'left') {
  65590. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  65591. }
  65592. else {
  65593. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  65594. }
  65595. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  65596. }
  65597. else {
  65598. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  65599. path = BABYLON.GenericController.MODEL_BASE_URL;
  65600. filename = BABYLON.GenericController.MODEL_FILENAME;
  65601. }
  65602. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  65603. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  65604. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  65605. if (!_this._loadedMeshInfo) {
  65606. return;
  65607. }
  65608. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  65609. _this.attachToMesh(_this._defaultModel);
  65610. if (meshLoaded) {
  65611. meshLoaded(_this._defaultModel);
  65612. }
  65613. }, null, function (scene, message) {
  65614. BABYLON.Tools.Log(message);
  65615. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  65616. if (!forceDefault) {
  65617. _this.initControllerMesh(scene, meshLoaded, true);
  65618. }
  65619. });
  65620. };
  65621. /**
  65622. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  65623. * can be transformed by button presses and axes values, based on this._mapping.
  65624. *
  65625. * @param scene scene in which the meshes exist
  65626. * @param meshes list of meshes that make up the controller model to process
  65627. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  65628. */
  65629. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  65630. var loadedMeshInfo = null;
  65631. // Create a new mesh to contain the glTF hierarchy
  65632. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  65633. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  65634. var childMesh = null;
  65635. for (var i = 0; i < meshes.length; i++) {
  65636. var mesh = meshes[i];
  65637. if (!mesh.parent) {
  65638. // Exclude controller meshes from picking results
  65639. mesh.isPickable = false;
  65640. // Handle root node, attach to the new parentMesh
  65641. childMesh = mesh;
  65642. break;
  65643. }
  65644. }
  65645. if (childMesh) {
  65646. childMesh.setParent(parentMesh);
  65647. // Create our mesh info. Note that this method will always return non-null.
  65648. loadedMeshInfo = this.createMeshInfo(parentMesh);
  65649. }
  65650. else {
  65651. BABYLON.Tools.Warn('Could not find root node in model file.');
  65652. }
  65653. return loadedMeshInfo;
  65654. };
  65655. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  65656. var loadedMeshInfo = new LoadedMeshInfo();
  65657. var i;
  65658. loadedMeshInfo.rootNode = rootNode;
  65659. // Reset the caches
  65660. loadedMeshInfo.buttonMeshes = {};
  65661. loadedMeshInfo.axisMeshes = {};
  65662. // Button Meshes
  65663. for (i = 0; i < this._mapping.buttons.length; i++) {
  65664. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  65665. if (!buttonMeshName) {
  65666. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  65667. continue;
  65668. }
  65669. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  65670. if (!buttonMesh) {
  65671. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  65672. continue;
  65673. }
  65674. var buttonMeshInfo = {
  65675. index: i,
  65676. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  65677. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  65678. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  65679. };
  65680. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  65681. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  65682. }
  65683. else {
  65684. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  65685. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  65686. '(VALUE: ' + !!buttonMeshInfo.value +
  65687. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  65688. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  65689. ')');
  65690. }
  65691. }
  65692. // Axis Meshes
  65693. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  65694. var axisMeshName = this._mapping.axisMeshNames[i];
  65695. if (!axisMeshName) {
  65696. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  65697. continue;
  65698. }
  65699. var axisMesh = getChildByName(rootNode, axisMeshName);
  65700. if (!axisMesh) {
  65701. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  65702. continue;
  65703. }
  65704. var axisMeshInfo = {
  65705. index: i,
  65706. value: getImmediateChildByName(axisMesh, 'VALUE'),
  65707. min: getImmediateChildByName(axisMesh, 'MIN'),
  65708. max: getImmediateChildByName(axisMesh, 'MAX')
  65709. };
  65710. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  65711. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  65712. }
  65713. else {
  65714. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  65715. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  65716. '(VALUE: ' + !!axisMeshInfo.value +
  65717. ', MIN: ' + !!axisMeshInfo.min +
  65718. ', MAX:' + !!axisMeshInfo.max +
  65719. ')');
  65720. }
  65721. }
  65722. // Pointing Ray
  65723. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  65724. if (!loadedMeshInfo.pointingPoseNode) {
  65725. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  65726. }
  65727. return loadedMeshInfo;
  65728. // Look through all children recursively. This will return null if no mesh exists with the given name.
  65729. function getChildByName(node, name) {
  65730. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  65731. }
  65732. // Look through only immediate children. This will return null if no mesh exists with the given name.
  65733. function getImmediateChildByName(node, name) {
  65734. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  65735. }
  65736. };
  65737. WindowsMotionController.prototype.getForwardRay = function (length) {
  65738. if (length === void 0) { length = 100; }
  65739. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  65740. return _super.prototype.getForwardRay.call(this, length);
  65741. }
  65742. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  65743. var origin = m.getTranslation();
  65744. var forward = new BABYLON.Vector3(0, 0, -1);
  65745. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  65746. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  65747. return new BABYLON.Ray(origin, direction, length);
  65748. };
  65749. WindowsMotionController.prototype.dispose = function () {
  65750. _super.prototype.dispose.call(this);
  65751. this.onTrackpadChangedObservable.clear();
  65752. };
  65753. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  65754. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  65755. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  65756. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  65757. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  65758. return WindowsMotionController;
  65759. }(BABYLON.WebVRController));
  65760. BABYLON.WindowsMotionController = WindowsMotionController;
  65761. })(BABYLON || (BABYLON = {}));
  65762. //# sourceMappingURL=babylon.windowsMotionController.js.map
  65763. var BABYLON;
  65764. (function (BABYLON) {
  65765. var GearVRController = /** @class */ (function (_super) {
  65766. __extends(GearVRController, _super);
  65767. function GearVRController(vrGamepad) {
  65768. var _this = _super.call(this, vrGamepad) || this;
  65769. _this._buttonIndexToObservableNameMap = [
  65770. 'onTrackpadChangedObservable',
  65771. 'onTriggerStateChangedObservable' // Trigger
  65772. ];
  65773. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  65774. return _this;
  65775. }
  65776. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  65777. var _this = this;
  65778. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  65779. _this._defaultModel = newMeshes[1];
  65780. _this.attachToMesh(_this._defaultModel);
  65781. if (meshLoaded) {
  65782. meshLoaded(_this._defaultModel);
  65783. }
  65784. });
  65785. };
  65786. GearVRController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  65787. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  65788. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  65789. // Only emit events for buttons that we know how to map from index to observable
  65790. var observable = this[observableName];
  65791. if (observable) {
  65792. observable.notifyObservers(state);
  65793. }
  65794. }
  65795. };
  65796. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  65797. GearVRController.MODEL_FILENAME = 'generic.babylon';
  65798. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  65799. return GearVRController;
  65800. }(BABYLON.WebVRController));
  65801. BABYLON.GearVRController = GearVRController;
  65802. })(BABYLON || (BABYLON = {}));
  65803. //# sourceMappingURL=babylon.gearVRController.js.map
  65804. var BABYLON;
  65805. (function (BABYLON) {
  65806. var FollowCamera = /** @class */ (function (_super) {
  65807. __extends(FollowCamera, _super);
  65808. function FollowCamera(name, position, scene, lockedTarget) {
  65809. if (lockedTarget === void 0) { lockedTarget = null; }
  65810. var _this = _super.call(this, name, position, scene) || this;
  65811. _this.radius = 12;
  65812. _this.rotationOffset = 0;
  65813. _this.heightOffset = 4;
  65814. _this.cameraAcceleration = 0.05;
  65815. _this.maxCameraSpeed = 20;
  65816. _this.lockedTarget = lockedTarget;
  65817. return _this;
  65818. }
  65819. FollowCamera.prototype.getRadians = function (degrees) {
  65820. return degrees * Math.PI / 180;
  65821. };
  65822. FollowCamera.prototype.follow = function (cameraTarget) {
  65823. if (!cameraTarget)
  65824. return;
  65825. var yRotation;
  65826. if (cameraTarget.rotationQuaternion) {
  65827. var rotMatrix = new BABYLON.Matrix();
  65828. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  65829. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  65830. }
  65831. else {
  65832. yRotation = cameraTarget.rotation.y;
  65833. }
  65834. var radians = this.getRadians(this.rotationOffset) + yRotation;
  65835. var targetPosition = cameraTarget.getAbsolutePosition();
  65836. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  65837. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  65838. var dx = targetX - this.position.x;
  65839. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  65840. var dz = (targetZ) - this.position.z;
  65841. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  65842. var vy = dy * this.cameraAcceleration;
  65843. var vz = dz * this.cameraAcceleration * 2;
  65844. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  65845. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  65846. }
  65847. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  65848. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  65849. }
  65850. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  65851. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  65852. }
  65853. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  65854. this.setTarget(targetPosition);
  65855. };
  65856. FollowCamera.prototype._checkInputs = function () {
  65857. _super.prototype._checkInputs.call(this);
  65858. if (this.lockedTarget) {
  65859. this.follow(this.lockedTarget);
  65860. }
  65861. };
  65862. FollowCamera.prototype.getClassName = function () {
  65863. return "FollowCamera";
  65864. };
  65865. __decorate([
  65866. BABYLON.serialize()
  65867. ], FollowCamera.prototype, "radius", void 0);
  65868. __decorate([
  65869. BABYLON.serialize()
  65870. ], FollowCamera.prototype, "rotationOffset", void 0);
  65871. __decorate([
  65872. BABYLON.serialize()
  65873. ], FollowCamera.prototype, "heightOffset", void 0);
  65874. __decorate([
  65875. BABYLON.serialize()
  65876. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  65877. __decorate([
  65878. BABYLON.serialize()
  65879. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  65880. __decorate([
  65881. BABYLON.serializeAsMeshReference("lockedTargetId")
  65882. ], FollowCamera.prototype, "lockedTarget", void 0);
  65883. return FollowCamera;
  65884. }(BABYLON.TargetCamera));
  65885. BABYLON.FollowCamera = FollowCamera;
  65886. var ArcFollowCamera = /** @class */ (function (_super) {
  65887. __extends(ArcFollowCamera, _super);
  65888. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  65889. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  65890. _this.alpha = alpha;
  65891. _this.beta = beta;
  65892. _this.radius = radius;
  65893. _this.target = target;
  65894. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  65895. _this.follow();
  65896. return _this;
  65897. }
  65898. ArcFollowCamera.prototype.follow = function () {
  65899. if (!this.target) {
  65900. return;
  65901. }
  65902. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  65903. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  65904. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  65905. var targetPosition = this.target.getAbsolutePosition();
  65906. this.position = targetPosition.add(this._cartesianCoordinates);
  65907. this.setTarget(targetPosition);
  65908. };
  65909. ArcFollowCamera.prototype._checkInputs = function () {
  65910. _super.prototype._checkInputs.call(this);
  65911. this.follow();
  65912. };
  65913. ArcFollowCamera.prototype.getClassName = function () {
  65914. return "ArcFollowCamera";
  65915. };
  65916. return ArcFollowCamera;
  65917. }(BABYLON.TargetCamera));
  65918. BABYLON.ArcFollowCamera = ArcFollowCamera;
  65919. })(BABYLON || (BABYLON = {}));
  65920. //# sourceMappingURL=babylon.followCamera.js.map
  65921. var BABYLON;
  65922. (function (BABYLON) {
  65923. // We're mainly based on the logic defined into the FreeCamera code
  65924. var UniversalCamera = /** @class */ (function (_super) {
  65925. __extends(UniversalCamera, _super);
  65926. //-- end properties for backward compatibility for inputs
  65927. function UniversalCamera(name, position, scene) {
  65928. var _this = _super.call(this, name, position, scene) || this;
  65929. _this.inputs.addGamepad();
  65930. return _this;
  65931. }
  65932. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  65933. //-- Begin properties for backward compatibility for inputs
  65934. get: function () {
  65935. var gamepad = this.inputs.attached["gamepad"];
  65936. if (gamepad)
  65937. return gamepad.gamepadAngularSensibility;
  65938. return 0;
  65939. },
  65940. set: function (value) {
  65941. var gamepad = this.inputs.attached["gamepad"];
  65942. if (gamepad)
  65943. gamepad.gamepadAngularSensibility = value;
  65944. },
  65945. enumerable: true,
  65946. configurable: true
  65947. });
  65948. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  65949. get: function () {
  65950. var gamepad = this.inputs.attached["gamepad"];
  65951. if (gamepad)
  65952. return gamepad.gamepadMoveSensibility;
  65953. return 0;
  65954. },
  65955. set: function (value) {
  65956. var gamepad = this.inputs.attached["gamepad"];
  65957. if (gamepad)
  65958. gamepad.gamepadMoveSensibility = value;
  65959. },
  65960. enumerable: true,
  65961. configurable: true
  65962. });
  65963. UniversalCamera.prototype.getClassName = function () {
  65964. return "UniversalCamera";
  65965. };
  65966. return UniversalCamera;
  65967. }(BABYLON.TouchCamera));
  65968. BABYLON.UniversalCamera = UniversalCamera;
  65969. })(BABYLON || (BABYLON = {}));
  65970. //# sourceMappingURL=babylon.universalCamera.js.map
  65971. var BABYLON;
  65972. (function (BABYLON) {
  65973. // We're mainly based on the logic defined into the FreeCamera code
  65974. var GamepadCamera = /** @class */ (function (_super) {
  65975. __extends(GamepadCamera, _super);
  65976. //-- end properties for backward compatibility for inputs
  65977. function GamepadCamera(name, position, scene) {
  65978. return _super.call(this, name, position, scene) || this;
  65979. }
  65980. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  65981. //-- Begin properties for backward compatibility for inputs
  65982. get: function () {
  65983. var gamepad = this.inputs.attached["gamepad"];
  65984. if (gamepad)
  65985. return gamepad.gamepadAngularSensibility;
  65986. return 0;
  65987. },
  65988. set: function (value) {
  65989. var gamepad = this.inputs.attached["gamepad"];
  65990. if (gamepad)
  65991. gamepad.gamepadAngularSensibility = value;
  65992. },
  65993. enumerable: true,
  65994. configurable: true
  65995. });
  65996. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  65997. get: function () {
  65998. var gamepad = this.inputs.attached["gamepad"];
  65999. if (gamepad)
  66000. return gamepad.gamepadMoveSensibility;
  66001. return 0;
  66002. },
  66003. set: function (value) {
  66004. var gamepad = this.inputs.attached["gamepad"];
  66005. if (gamepad)
  66006. gamepad.gamepadMoveSensibility = value;
  66007. },
  66008. enumerable: true,
  66009. configurable: true
  66010. });
  66011. GamepadCamera.prototype.getClassName = function () {
  66012. return "GamepadCamera";
  66013. };
  66014. return GamepadCamera;
  66015. }(BABYLON.UniversalCamera));
  66016. BABYLON.GamepadCamera = GamepadCamera;
  66017. })(BABYLON || (BABYLON = {}));
  66018. //# sourceMappingURL=babylon.gamepadCamera.js.map
  66019. var BABYLON;
  66020. (function (BABYLON) {
  66021. var PostProcessRenderPipelineManager = /** @class */ (function () {
  66022. function PostProcessRenderPipelineManager() {
  66023. this._renderPipelines = {};
  66024. }
  66025. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  66026. this._renderPipelines[renderPipeline._name] = renderPipeline;
  66027. };
  66028. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  66029. if (unique === void 0) { unique = false; }
  66030. var renderPipeline = this._renderPipelines[renderPipelineName];
  66031. if (!renderPipeline) {
  66032. return;
  66033. }
  66034. renderPipeline._attachCameras(cameras, unique);
  66035. };
  66036. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  66037. var renderPipeline = this._renderPipelines[renderPipelineName];
  66038. if (!renderPipeline) {
  66039. return;
  66040. }
  66041. renderPipeline._detachCameras(cameras);
  66042. };
  66043. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  66044. var renderPipeline = this._renderPipelines[renderPipelineName];
  66045. if (!renderPipeline) {
  66046. return;
  66047. }
  66048. renderPipeline._enableEffect(renderEffectName, cameras);
  66049. };
  66050. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  66051. var renderPipeline = this._renderPipelines[renderPipelineName];
  66052. if (!renderPipeline) {
  66053. return;
  66054. }
  66055. renderPipeline._disableEffect(renderEffectName, cameras);
  66056. };
  66057. PostProcessRenderPipelineManager.prototype.update = function () {
  66058. for (var renderPipelineName in this._renderPipelines) {
  66059. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  66060. var pipeline = this._renderPipelines[renderPipelineName];
  66061. if (!pipeline.isSupported) {
  66062. pipeline.dispose();
  66063. delete this._renderPipelines[renderPipelineName];
  66064. }
  66065. else {
  66066. pipeline._update();
  66067. }
  66068. }
  66069. }
  66070. };
  66071. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  66072. for (var renderPipelineName in this._renderPipelines) {
  66073. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  66074. var pipeline = this._renderPipelines[renderPipelineName];
  66075. pipeline._rebuild();
  66076. }
  66077. }
  66078. };
  66079. PostProcessRenderPipelineManager.prototype.dispose = function () {
  66080. for (var renderPipelineName in this._renderPipelines) {
  66081. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  66082. var pipeline = this._renderPipelines[renderPipelineName];
  66083. pipeline.dispose();
  66084. }
  66085. }
  66086. };
  66087. return PostProcessRenderPipelineManager;
  66088. }());
  66089. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  66090. })(BABYLON || (BABYLON = {}));
  66091. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  66092. var BABYLON;
  66093. (function (BABYLON) {
  66094. /**
  66095. * This represents a set of one or more post processes in Babylon.
  66096. * A post process can be used to apply a shader to a texture after it is rendered.
  66097. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  66098. */
  66099. var PostProcessRenderEffect = /** @class */ (function () {
  66100. /**
  66101. * Instantiates a post process render effect.
  66102. * A post process can be used to apply a shader to a texture after it is rendered.
  66103. * @param engine The engine the effect is tied to
  66104. * @param name The name of the effect
  66105. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  66106. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  66107. */
  66108. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  66109. this._name = name;
  66110. this._singleInstance = singleInstance || true;
  66111. this._getPostProcesses = getPostProcesses;
  66112. this._cameras = {};
  66113. this._indicesForCamera = {};
  66114. this._postProcesses = {};
  66115. }
  66116. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  66117. /**
  66118. * Checks if all the post processes in the effect are supported.
  66119. */
  66120. get: function () {
  66121. for (var index in this._postProcesses) {
  66122. for (var ppIndex in this._postProcesses[index]) {
  66123. if (!this._postProcesses[index][ppIndex].isSupported) {
  66124. return false;
  66125. }
  66126. }
  66127. }
  66128. return true;
  66129. },
  66130. enumerable: true,
  66131. configurable: true
  66132. });
  66133. /**
  66134. * Updates the current state of the effect
  66135. */
  66136. PostProcessRenderEffect.prototype._update = function () {
  66137. };
  66138. /**
  66139. * Attaches the effect on cameras
  66140. * @param cameras The camera to attach to.
  66141. */
  66142. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  66143. var _this = this;
  66144. var cameraKey;
  66145. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  66146. if (!cams) {
  66147. return;
  66148. }
  66149. for (var i = 0; i < cams.length; i++) {
  66150. var camera = cams[i];
  66151. var cameraName = camera.name;
  66152. if (this._singleInstance) {
  66153. cameraKey = 0;
  66154. }
  66155. else {
  66156. cameraKey = cameraName;
  66157. }
  66158. if (!this._postProcesses[cameraKey]) {
  66159. var postProcess = this._getPostProcesses();
  66160. if (postProcess) {
  66161. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  66162. }
  66163. }
  66164. if (!this._indicesForCamera[cameraName]) {
  66165. this._indicesForCamera[cameraName] = [];
  66166. }
  66167. this._postProcesses[cameraKey].forEach(function (postProcess) {
  66168. var index = camera.attachPostProcess(postProcess);
  66169. _this._indicesForCamera[cameraName].push(index);
  66170. });
  66171. if (!this._cameras[cameraName]) {
  66172. this._cameras[cameraName] = camera;
  66173. }
  66174. }
  66175. };
  66176. /**
  66177. * Detatches the effect on cameras
  66178. * @param cameras The camera to detatch from.
  66179. */
  66180. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  66181. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  66182. if (!cams) {
  66183. return;
  66184. }
  66185. for (var i = 0; i < cams.length; i++) {
  66186. var camera = cams[i];
  66187. var cameraName = camera.name;
  66188. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  66189. camera.detachPostProcess(postProcess);
  66190. });
  66191. if (this._cameras[cameraName]) {
  66192. //this._indicesForCamera.splice(index, 1);
  66193. this._cameras[cameraName] = null;
  66194. }
  66195. }
  66196. };
  66197. /**
  66198. * Enables the effect on given cameras
  66199. * @param cameras The camera to enable.
  66200. */
  66201. PostProcessRenderEffect.prototype._enable = function (cameras) {
  66202. var _this = this;
  66203. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  66204. if (!cams) {
  66205. return;
  66206. }
  66207. for (var i = 0; i < cams.length; i++) {
  66208. var camera = cams[i];
  66209. var cameraName = camera.name;
  66210. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  66211. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  66212. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  66213. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  66214. });
  66215. }
  66216. }
  66217. }
  66218. };
  66219. /**
  66220. * Disables the effect on the given cameras
  66221. * @param cameras The camera to disable.
  66222. */
  66223. PostProcessRenderEffect.prototype._disable = function (cameras) {
  66224. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  66225. if (!cams) {
  66226. return;
  66227. }
  66228. for (var i = 0; i < cams.length; i++) {
  66229. var camera = cams[i];
  66230. var cameraName = camera.name;
  66231. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  66232. camera.detachPostProcess(postProcess);
  66233. });
  66234. }
  66235. };
  66236. /**
  66237. * Gets a list of the post processes contained in the effect.
  66238. * @param camera The camera to get the post processes on.
  66239. * @returns The list of the post processes in the effect.
  66240. */
  66241. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  66242. if (this._singleInstance) {
  66243. return this._postProcesses[0];
  66244. }
  66245. else {
  66246. if (!camera) {
  66247. return null;
  66248. }
  66249. return this._postProcesses[camera.name];
  66250. }
  66251. };
  66252. return PostProcessRenderEffect;
  66253. }());
  66254. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  66255. })(BABYLON || (BABYLON = {}));
  66256. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  66257. var BABYLON;
  66258. (function (BABYLON) {
  66259. var PostProcessRenderPipeline = /** @class */ (function () {
  66260. function PostProcessRenderPipeline(engine, name) {
  66261. this._name = name;
  66262. this._renderEffects = {};
  66263. this._renderEffectsForIsolatedPass = new Array();
  66264. this._cameras = [];
  66265. }
  66266. PostProcessRenderPipeline.prototype.getClassName = function () {
  66267. return "PostProcessRenderPipeline";
  66268. };
  66269. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  66270. get: function () {
  66271. for (var renderEffectName in this._renderEffects) {
  66272. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  66273. if (!this._renderEffects[renderEffectName].isSupported) {
  66274. return false;
  66275. }
  66276. }
  66277. }
  66278. return true;
  66279. },
  66280. enumerable: true,
  66281. configurable: true
  66282. });
  66283. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  66284. this._renderEffects[renderEffect._name] = renderEffect;
  66285. };
  66286. // private
  66287. PostProcessRenderPipeline.prototype._rebuild = function () {
  66288. };
  66289. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  66290. var renderEffects = this._renderEffects[renderEffectName];
  66291. if (!renderEffects) {
  66292. return;
  66293. }
  66294. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  66295. };
  66296. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  66297. var renderEffects = this._renderEffects[renderEffectName];
  66298. if (!renderEffects) {
  66299. return;
  66300. }
  66301. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  66302. };
  66303. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  66304. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  66305. if (!cams) {
  66306. return;
  66307. }
  66308. var indicesToDelete = [];
  66309. var i;
  66310. for (i = 0; i < cams.length; i++) {
  66311. var camera = cams[i];
  66312. var cameraName = camera.name;
  66313. if (this._cameras.indexOf(camera) === -1) {
  66314. this._cameras[cameraName] = camera;
  66315. }
  66316. else if (unique) {
  66317. indicesToDelete.push(i);
  66318. }
  66319. }
  66320. for (i = 0; i < indicesToDelete.length; i++) {
  66321. cameras.splice(indicesToDelete[i], 1);
  66322. }
  66323. for (var renderEffectName in this._renderEffects) {
  66324. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  66325. this._renderEffects[renderEffectName]._attachCameras(cams);
  66326. }
  66327. }
  66328. };
  66329. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  66330. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  66331. if (!cams) {
  66332. return;
  66333. }
  66334. for (var renderEffectName in this._renderEffects) {
  66335. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  66336. this._renderEffects[renderEffectName]._detachCameras(cams);
  66337. }
  66338. }
  66339. for (var i = 0; i < cams.length; i++) {
  66340. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  66341. }
  66342. };
  66343. PostProcessRenderPipeline.prototype._update = function () {
  66344. for (var renderEffectName in this._renderEffects) {
  66345. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  66346. this._renderEffects[renderEffectName]._update();
  66347. }
  66348. }
  66349. for (var i = 0; i < this._cameras.length; i++) {
  66350. var cameraName = this._cameras[i].name;
  66351. if (this._renderEffectsForIsolatedPass[cameraName]) {
  66352. this._renderEffectsForIsolatedPass[cameraName]._update();
  66353. }
  66354. }
  66355. };
  66356. PostProcessRenderPipeline.prototype._reset = function () {
  66357. this._renderEffects = {};
  66358. this._renderEffectsForIsolatedPass = new Array();
  66359. };
  66360. PostProcessRenderPipeline.prototype.dispose = function () {
  66361. // Must be implemented by children
  66362. };
  66363. __decorate([
  66364. BABYLON.serialize()
  66365. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  66366. return PostProcessRenderPipeline;
  66367. }());
  66368. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  66369. })(BABYLON || (BABYLON = {}));
  66370. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  66371. var BABYLON;
  66372. (function (BABYLON) {
  66373. /**
  66374. * This represents a depth renderer in Babylon.
  66375. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  66376. */
  66377. var DepthRenderer = /** @class */ (function () {
  66378. /**
  66379. * Instantiates a depth renderer
  66380. * @param scene The scene the renderer belongs to
  66381. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  66382. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  66383. */
  66384. function DepthRenderer(scene, type, camera) {
  66385. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  66386. if (camera === void 0) { camera = null; }
  66387. var _this = this;
  66388. this._scene = scene;
  66389. this._camera = camera;
  66390. var engine = scene.getEngine();
  66391. // Render target
  66392. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  66393. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66394. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66395. this._depthMap.refreshRate = 1;
  66396. this._depthMap.renderParticles = false;
  66397. this._depthMap.renderList = null;
  66398. // Camera to get depth map from to support multiple concurrent cameras
  66399. this._depthMap.activeCamera = this._camera;
  66400. this._depthMap.ignoreCameraViewport = true;
  66401. this._depthMap.useCameraPostProcesses = false;
  66402. // set default depth value to 1.0 (far away)
  66403. this._depthMap.onClearObservable.add(function (engine) {
  66404. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  66405. });
  66406. // Custom render function
  66407. var renderSubMesh = function (subMesh) {
  66408. var mesh = subMesh.getRenderingMesh();
  66409. var scene = _this._scene;
  66410. var engine = scene.getEngine();
  66411. var material = subMesh.getMaterial();
  66412. if (!material) {
  66413. return;
  66414. }
  66415. // Culling and reverse (right handed system)
  66416. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  66417. // Managing instances
  66418. var batch = mesh._getInstancesRenderList(subMesh._id);
  66419. if (batch.mustReturn) {
  66420. return;
  66421. }
  66422. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  66423. var camera = _this._camera || scene.activeCamera;
  66424. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  66425. engine.enableEffect(_this._effect);
  66426. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  66427. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  66428. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  66429. // Alpha test
  66430. if (material && material.needAlphaTesting()) {
  66431. var alphaTexture = material.getAlphaTestTexture();
  66432. if (alphaTexture) {
  66433. _this._effect.setTexture("diffuseSampler", alphaTexture);
  66434. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  66435. }
  66436. }
  66437. // Bones
  66438. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  66439. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  66440. }
  66441. // Draw
  66442. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  66443. }
  66444. };
  66445. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  66446. var index;
  66447. if (depthOnlySubMeshes.length) {
  66448. engine.setColorWrite(false);
  66449. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  66450. renderSubMesh(depthOnlySubMeshes.data[index]);
  66451. }
  66452. engine.setColorWrite(true);
  66453. }
  66454. for (index = 0; index < opaqueSubMeshes.length; index++) {
  66455. renderSubMesh(opaqueSubMeshes.data[index]);
  66456. }
  66457. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  66458. renderSubMesh(alphaTestSubMeshes.data[index]);
  66459. }
  66460. };
  66461. }
  66462. /**
  66463. * Creates the depth rendering effect and checks if the effect is ready.
  66464. * @param subMesh The submesh to be used to render the depth map of
  66465. * @param useInstances If multiple world instances should be used
  66466. * @returns if the depth renderer is ready to render the depth map
  66467. */
  66468. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  66469. var material = subMesh.getMaterial();
  66470. if (material.disableDepthWrite) {
  66471. return false;
  66472. }
  66473. var defines = [];
  66474. var attribs = [BABYLON.VertexBuffer.PositionKind];
  66475. var mesh = subMesh.getMesh();
  66476. // Alpha test
  66477. if (material && material.needAlphaTesting()) {
  66478. defines.push("#define ALPHATEST");
  66479. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  66480. attribs.push(BABYLON.VertexBuffer.UVKind);
  66481. defines.push("#define UV1");
  66482. }
  66483. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  66484. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  66485. defines.push("#define UV2");
  66486. }
  66487. }
  66488. // Bones
  66489. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  66490. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  66491. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  66492. if (mesh.numBoneInfluencers > 4) {
  66493. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  66494. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  66495. }
  66496. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  66497. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  66498. }
  66499. else {
  66500. defines.push("#define NUM_BONE_INFLUENCERS 0");
  66501. }
  66502. // Instances
  66503. if (useInstances) {
  66504. defines.push("#define INSTANCES");
  66505. attribs.push("world0");
  66506. attribs.push("world1");
  66507. attribs.push("world2");
  66508. attribs.push("world3");
  66509. }
  66510. // Get correct effect
  66511. var join = defines.join("\n");
  66512. if (this._cachedDefines !== join) {
  66513. this._cachedDefines = join;
  66514. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  66515. }
  66516. return this._effect.isReady();
  66517. };
  66518. /**
  66519. * Gets the texture which the depth map will be written to.
  66520. * @returns The depth map texture
  66521. */
  66522. DepthRenderer.prototype.getDepthMap = function () {
  66523. return this._depthMap;
  66524. };
  66525. /**
  66526. * Disposes of the depth renderer.
  66527. */
  66528. DepthRenderer.prototype.dispose = function () {
  66529. this._depthMap.dispose();
  66530. };
  66531. return DepthRenderer;
  66532. }());
  66533. BABYLON.DepthRenderer = DepthRenderer;
  66534. })(BABYLON || (BABYLON = {}));
  66535. //# sourceMappingURL=babylon.depthRenderer.js.map
  66536. var BABYLON;
  66537. (function (BABYLON) {
  66538. var SSAORenderingPipeline = /** @class */ (function (_super) {
  66539. __extends(SSAORenderingPipeline, _super);
  66540. /**
  66541. * @constructor
  66542. * @param {string} name - The rendering pipeline name
  66543. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  66544. * @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 }
  66545. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  66546. */
  66547. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  66548. var _this = _super.call(this, scene.getEngine(), name) || this;
  66549. // Members
  66550. /**
  66551. * The PassPostProcess id in the pipeline that contains the original scene color
  66552. * @type {string}
  66553. */
  66554. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  66555. /**
  66556. * The SSAO PostProcess id in the pipeline
  66557. * @type {string}
  66558. */
  66559. _this.SSAORenderEffect = "SSAORenderEffect";
  66560. /**
  66561. * The horizontal blur PostProcess id in the pipeline
  66562. * @type {string}
  66563. */
  66564. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  66565. /**
  66566. * The vertical blur PostProcess id in the pipeline
  66567. * @type {string}
  66568. */
  66569. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  66570. /**
  66571. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  66572. * @type {string}
  66573. */
  66574. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  66575. /**
  66576. * The output strength of the SSAO post-process. Default value is 1.0.
  66577. * @type {number}
  66578. */
  66579. _this.totalStrength = 1.0;
  66580. /**
  66581. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  66582. * @type {number}
  66583. */
  66584. _this.radius = 0.0001;
  66585. /**
  66586. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  66587. * Must not be equal to fallOff and superior to fallOff.
  66588. * Default value is 0.975
  66589. * @type {number}
  66590. */
  66591. _this.area = 0.0075;
  66592. /**
  66593. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  66594. * Must not be equal to area and inferior to area.
  66595. * Default value is 0.0
  66596. * @type {number}
  66597. */
  66598. _this.fallOff = 0.000001;
  66599. /**
  66600. * The base color of the SSAO post-process
  66601. * The final result is "base + ssao" between [0, 1]
  66602. * @type {number}
  66603. */
  66604. _this.base = 0.5;
  66605. _this._firstUpdate = true;
  66606. _this._scene = scene;
  66607. // Set up assets
  66608. _this._createRandomTexture();
  66609. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  66610. var ssaoRatio = ratio.ssaoRatio || ratio;
  66611. var combineRatio = ratio.combineRatio || ratio;
  66612. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  66613. _this._createSSAOPostProcess(ssaoRatio);
  66614. _this._createBlurPostProcess(ssaoRatio);
  66615. _this._createSSAOCombinePostProcess(combineRatio);
  66616. // Set up pipeline
  66617. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  66618. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  66619. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  66620. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  66621. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  66622. // Finish
  66623. scene.postProcessRenderPipelineManager.addPipeline(_this);
  66624. if (cameras)
  66625. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  66626. return _this;
  66627. }
  66628. // Public Methods
  66629. /**
  66630. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  66631. */
  66632. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  66633. if (disableDepthRender === void 0) { disableDepthRender = false; }
  66634. for (var i = 0; i < this._scene.cameras.length; i++) {
  66635. var camera = this._scene.cameras[i];
  66636. this._originalColorPostProcess.dispose(camera);
  66637. this._ssaoPostProcess.dispose(camera);
  66638. this._blurHPostProcess.dispose(camera);
  66639. this._blurVPostProcess.dispose(camera);
  66640. this._ssaoCombinePostProcess.dispose(camera);
  66641. }
  66642. this._randomTexture.dispose();
  66643. if (disableDepthRender)
  66644. this._scene.disableDepthRenderer();
  66645. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  66646. _super.prototype.dispose.call(this);
  66647. };
  66648. // Private Methods
  66649. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  66650. var _this = this;
  66651. var size = 16;
  66652. 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);
  66653. 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);
  66654. this._blurHPostProcess.onActivateObservable.add(function () {
  66655. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  66656. _this._blurHPostProcess.kernel = size * dw;
  66657. });
  66658. this._blurVPostProcess.onActivateObservable.add(function () {
  66659. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  66660. _this._blurVPostProcess.kernel = size * dw;
  66661. });
  66662. };
  66663. SSAORenderingPipeline.prototype._rebuild = function () {
  66664. this._firstUpdate = true;
  66665. _super.prototype._rebuild.call(this);
  66666. };
  66667. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  66668. var _this = this;
  66669. var numSamples = 16;
  66670. var sampleSphere = [
  66671. 0.5381, 0.1856, -0.4319,
  66672. 0.1379, 0.2486, 0.4430,
  66673. 0.3371, 0.5679, -0.0057,
  66674. -0.6999, -0.0451, -0.0019,
  66675. 0.0689, -0.1598, -0.8547,
  66676. 0.0560, 0.0069, -0.1843,
  66677. -0.0146, 0.1402, 0.0762,
  66678. 0.0100, -0.1924, -0.0344,
  66679. -0.3577, -0.5301, -0.4358,
  66680. -0.3169, 0.1063, 0.0158,
  66681. 0.0103, -0.5869, 0.0046,
  66682. -0.0897, -0.4940, 0.3287,
  66683. 0.7119, -0.0154, -0.0918,
  66684. -0.0533, 0.0596, -0.5411,
  66685. 0.0352, -0.0631, 0.5460,
  66686. -0.4776, 0.2847, -0.0271
  66687. ];
  66688. var samplesFactor = 1.0 / numSamples;
  66689. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  66690. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  66691. "area", "fallOff", "base", "range", "viewport"
  66692. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  66693. this._ssaoPostProcess.onApply = function (effect) {
  66694. if (_this._firstUpdate) {
  66695. effect.setArray3("sampleSphere", sampleSphere);
  66696. effect.setFloat("samplesFactor", samplesFactor);
  66697. effect.setFloat("randTextureTiles", 4.0);
  66698. }
  66699. effect.setFloat("totalStrength", _this.totalStrength);
  66700. effect.setFloat("radius", _this.radius);
  66701. effect.setFloat("area", _this.area);
  66702. effect.setFloat("fallOff", _this.fallOff);
  66703. effect.setFloat("base", _this.base);
  66704. effect.setTexture("textureSampler", _this._depthTexture);
  66705. effect.setTexture("randomSampler", _this._randomTexture);
  66706. };
  66707. };
  66708. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  66709. var _this = this;
  66710. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  66711. this._ssaoCombinePostProcess.onApply = function (effect) {
  66712. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  66713. };
  66714. };
  66715. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  66716. var size = 512;
  66717. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  66718. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  66719. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  66720. var context = this._randomTexture.getContext();
  66721. var rand = function (min, max) {
  66722. return Math.random() * (max - min) + min;
  66723. };
  66724. var randVector = BABYLON.Vector3.Zero();
  66725. for (var x = 0; x < size; x++) {
  66726. for (var y = 0; y < size; y++) {
  66727. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  66728. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  66729. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  66730. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  66731. context.fillRect(x, y, 1, 1);
  66732. }
  66733. }
  66734. this._randomTexture.update(false);
  66735. };
  66736. __decorate([
  66737. BABYLON.serialize()
  66738. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  66739. __decorate([
  66740. BABYLON.serialize()
  66741. ], SSAORenderingPipeline.prototype, "radius", void 0);
  66742. __decorate([
  66743. BABYLON.serialize()
  66744. ], SSAORenderingPipeline.prototype, "area", void 0);
  66745. __decorate([
  66746. BABYLON.serialize()
  66747. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  66748. __decorate([
  66749. BABYLON.serialize()
  66750. ], SSAORenderingPipeline.prototype, "base", void 0);
  66751. return SSAORenderingPipeline;
  66752. }(BABYLON.PostProcessRenderPipeline));
  66753. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  66754. })(BABYLON || (BABYLON = {}));
  66755. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  66756. var BABYLON;
  66757. (function (BABYLON) {
  66758. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  66759. __extends(SSAO2RenderingPipeline, _super);
  66760. /**
  66761. * @constructor
  66762. * @param {string} name - The rendering pipeline name
  66763. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  66764. * @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 }
  66765. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  66766. */
  66767. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  66768. var _this = _super.call(this, scene.getEngine(), name) || this;
  66769. // Members
  66770. /**
  66771. * The PassPostProcess id in the pipeline that contains the original scene color
  66772. * @type {string}
  66773. */
  66774. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  66775. /**
  66776. * The SSAO PostProcess id in the pipeline
  66777. * @type {string}
  66778. */
  66779. _this.SSAORenderEffect = "SSAORenderEffect";
  66780. /**
  66781. * The horizontal blur PostProcess id in the pipeline
  66782. * @type {string}
  66783. */
  66784. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  66785. /**
  66786. * The vertical blur PostProcess id in the pipeline
  66787. * @type {string}
  66788. */
  66789. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  66790. /**
  66791. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  66792. * @type {string}
  66793. */
  66794. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  66795. /**
  66796. * The output strength of the SSAO post-process. Default value is 1.0.
  66797. * @type {number}
  66798. */
  66799. _this.totalStrength = 1.0;
  66800. /**
  66801. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  66802. * @type {number}
  66803. */
  66804. _this.maxZ = 100.0;
  66805. /**
  66806. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  66807. * @type {number}
  66808. */
  66809. _this.minZAspect = 0.2;
  66810. /**
  66811. * Number of samples used for the SSAO calculations. Default value is 8
  66812. * @type {number}
  66813. */
  66814. _this._samples = 8;
  66815. /**
  66816. * Are we using bilateral blur ?
  66817. * @type {boolean}
  66818. */
  66819. _this._expensiveBlur = true;
  66820. /**
  66821. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  66822. * @type {number}
  66823. */
  66824. _this.radius = 2.0;
  66825. /**
  66826. * The base color of the SSAO post-process
  66827. * The final result is "base + ssao" between [0, 1]
  66828. * @type {number}
  66829. */
  66830. _this.base = 0.1;
  66831. _this._firstUpdate = true;
  66832. _this._scene = scene;
  66833. if (!_this.isSupported) {
  66834. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  66835. return _this;
  66836. }
  66837. var ssaoRatio = ratio.ssaoRatio || ratio;
  66838. var blurRatio = ratio.blurRatio || ratio;
  66839. // Set up assets
  66840. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  66841. _this._createRandomTexture();
  66842. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  66843. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  66844. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  66845. _this._createSSAOPostProcess(1.0);
  66846. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  66847. _this._createSSAOCombinePostProcess(blurRatio);
  66848. // Set up pipeline
  66849. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  66850. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  66851. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  66852. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  66853. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  66854. // Finish
  66855. scene.postProcessRenderPipelineManager.addPipeline(_this);
  66856. if (cameras)
  66857. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  66858. return _this;
  66859. }
  66860. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  66861. get: function () {
  66862. return this._samples;
  66863. },
  66864. set: function (n) {
  66865. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  66866. this._samples = n;
  66867. this._sampleSphere = this._generateHemisphere();
  66868. this._firstUpdate = true;
  66869. },
  66870. enumerable: true,
  66871. configurable: true
  66872. });
  66873. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  66874. get: function () {
  66875. return this._expensiveBlur;
  66876. },
  66877. set: function (b) {
  66878. 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"]);
  66879. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  66880. this._expensiveBlur = b;
  66881. this._firstUpdate = true;
  66882. },
  66883. enumerable: true,
  66884. configurable: true
  66885. });
  66886. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  66887. /**
  66888. * Support test.
  66889. * @type {boolean}
  66890. */
  66891. get: function () {
  66892. var engine = BABYLON.Engine.LastCreatedEngine;
  66893. if (!engine) {
  66894. return false;
  66895. }
  66896. return engine.getCaps().drawBuffersExtension;
  66897. },
  66898. enumerable: true,
  66899. configurable: true
  66900. });
  66901. // Public Methods
  66902. /**
  66903. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  66904. */
  66905. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  66906. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  66907. for (var i = 0; i < this._scene.cameras.length; i++) {
  66908. var camera = this._scene.cameras[i];
  66909. this._originalColorPostProcess.dispose(camera);
  66910. this._ssaoPostProcess.dispose(camera);
  66911. this._blurHPostProcess.dispose(camera);
  66912. this._blurVPostProcess.dispose(camera);
  66913. this._ssaoCombinePostProcess.dispose(camera);
  66914. }
  66915. this._randomTexture.dispose();
  66916. if (disableGeometryBufferRenderer)
  66917. this._scene.disableGeometryBufferRenderer();
  66918. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  66919. _super.prototype.dispose.call(this);
  66920. };
  66921. // Private Methods
  66922. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  66923. var _this = this;
  66924. this._samplerOffsets = [];
  66925. var expensive = this.expensiveBlur;
  66926. for (var i = -8; i < 8; i++) {
  66927. this._samplerOffsets.push(i * 2 + 0.5);
  66928. }
  66929. 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");
  66930. this._blurHPostProcess.onApply = function (effect) {
  66931. if (!_this._scene.activeCamera) {
  66932. return;
  66933. }
  66934. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  66935. effect.setFloat("near", _this._scene.activeCamera.minZ);
  66936. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  66937. effect.setFloat("radius", _this.radius);
  66938. effect.setTexture("depthSampler", _this._depthTexture);
  66939. if (_this._firstUpdate) {
  66940. effect.setArray("samplerOffsets", _this._samplerOffsets);
  66941. }
  66942. };
  66943. 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");
  66944. this._blurVPostProcess.onApply = function (effect) {
  66945. if (!_this._scene.activeCamera) {
  66946. return;
  66947. }
  66948. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  66949. effect.setFloat("near", _this._scene.activeCamera.minZ);
  66950. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  66951. effect.setFloat("radius", _this.radius);
  66952. effect.setTexture("depthSampler", _this._depthTexture);
  66953. if (_this._firstUpdate) {
  66954. effect.setArray("samplerOffsets", _this._samplerOffsets);
  66955. _this._firstUpdate = false;
  66956. }
  66957. };
  66958. };
  66959. SSAO2RenderingPipeline.prototype._rebuild = function () {
  66960. this._firstUpdate = true;
  66961. _super.prototype._rebuild.call(this);
  66962. };
  66963. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  66964. var numSamples = this.samples;
  66965. var result = [];
  66966. var vector, scale;
  66967. var rand = function (min, max) {
  66968. return Math.random() * (max - min) + min;
  66969. };
  66970. var i = 0;
  66971. while (i < numSamples) {
  66972. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  66973. vector.normalize();
  66974. scale = i / numSamples;
  66975. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  66976. vector.scaleInPlace(scale);
  66977. result.push(vector.x, vector.y, vector.z);
  66978. i++;
  66979. }
  66980. return result;
  66981. };
  66982. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  66983. var _this = this;
  66984. var numSamples = this.samples;
  66985. this._sampleSphere = this._generateHemisphere();
  66986. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  66987. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  66988. "base", "range", "projection", "near", "far", "texelSize",
  66989. "xViewport", "yViewport", "maxZ", "minZAspect"
  66990. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  66991. this._ssaoPostProcess.onApply = function (effect) {
  66992. if (_this._firstUpdate) {
  66993. effect.setArray3("sampleSphere", _this._sampleSphere);
  66994. effect.setFloat("randTextureTiles", 4.0);
  66995. }
  66996. if (!_this._scene.activeCamera) {
  66997. return;
  66998. }
  66999. effect.setFloat("samplesFactor", 1 / _this.samples);
  67000. effect.setFloat("totalStrength", _this.totalStrength);
  67001. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  67002. effect.setFloat("radius", _this.radius);
  67003. effect.setFloat("maxZ", _this.maxZ);
  67004. effect.setFloat("minZAspect", _this.minZAspect);
  67005. effect.setFloat("base", _this.base);
  67006. effect.setFloat("near", _this._scene.activeCamera.minZ);
  67007. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  67008. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  67009. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  67010. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  67011. effect.setTexture("textureSampler", _this._depthTexture);
  67012. effect.setTexture("normalSampler", _this._normalTexture);
  67013. effect.setTexture("randomSampler", _this._randomTexture);
  67014. };
  67015. };
  67016. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  67017. var _this = this;
  67018. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  67019. this._ssaoCombinePostProcess.onApply = function (effect) {
  67020. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  67021. };
  67022. };
  67023. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  67024. var size = 512;
  67025. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  67026. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  67027. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  67028. var context = this._randomTexture.getContext();
  67029. var rand = function (min, max) {
  67030. return Math.random() * (max - min) + min;
  67031. };
  67032. var randVector = BABYLON.Vector3.Zero();
  67033. for (var x = 0; x < size; x++) {
  67034. for (var y = 0; y < size; y++) {
  67035. randVector.x = rand(0.0, 1.0);
  67036. randVector.y = rand(0.0, 1.0);
  67037. randVector.z = 0.0;
  67038. randVector.normalize();
  67039. randVector.scaleInPlace(255);
  67040. randVector.x = Math.floor(randVector.x);
  67041. randVector.y = Math.floor(randVector.y);
  67042. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  67043. context.fillRect(x, y, 1, 1);
  67044. }
  67045. }
  67046. this._randomTexture.update(false);
  67047. };
  67048. __decorate([
  67049. BABYLON.serialize()
  67050. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  67051. __decorate([
  67052. BABYLON.serialize()
  67053. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  67054. __decorate([
  67055. BABYLON.serialize()
  67056. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  67057. __decorate([
  67058. BABYLON.serialize("samples")
  67059. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  67060. __decorate([
  67061. BABYLON.serialize("expensiveBlur")
  67062. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  67063. __decorate([
  67064. BABYLON.serialize()
  67065. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  67066. __decorate([
  67067. BABYLON.serialize()
  67068. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  67069. return SSAO2RenderingPipeline;
  67070. }(BABYLON.PostProcessRenderPipeline));
  67071. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  67072. })(BABYLON || (BABYLON = {}));
  67073. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  67074. // BABYLON.JS Chromatic Aberration GLSL Shader
  67075. // Author: Olivier Guyot
  67076. // Separates very slightly R, G and B colors on the edges of the screen
  67077. // Inspired by Francois Tarlier & Martins Upitis
  67078. var BABYLON;
  67079. (function (BABYLON) {
  67080. var LensRenderingPipeline = /** @class */ (function (_super) {
  67081. __extends(LensRenderingPipeline, _super);
  67082. /**
  67083. * @constructor
  67084. *
  67085. * Effect parameters are as follow:
  67086. * {
  67087. * chromatic_aberration: number; // from 0 to x (1 for realism)
  67088. * edge_blur: number; // from 0 to x (1 for realism)
  67089. * distortion: number; // from 0 to x (1 for realism)
  67090. * grain_amount: number; // from 0 to 1
  67091. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  67092. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  67093. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  67094. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  67095. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  67096. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  67097. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  67098. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  67099. * }
  67100. * Note: if an effect parameter is unset, effect is disabled
  67101. *
  67102. * @param {string} name - The rendering pipeline name
  67103. * @param {object} parameters - An object containing all parameters (see above)
  67104. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  67105. * @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)
  67106. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  67107. */
  67108. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  67109. if (ratio === void 0) { ratio = 1.0; }
  67110. var _this = _super.call(this, scene.getEngine(), name) || this;
  67111. // Lens effects can be of the following:
  67112. // - chromatic aberration (slight shift of RGB colors)
  67113. // - blur on the edge of the lens
  67114. // - lens distortion
  67115. // - depth-of-field blur & highlights enhancing
  67116. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  67117. // - grain effect (noise or custom texture)
  67118. // Two additional texture samplers are needed:
  67119. // - depth map (for depth-of-field)
  67120. // - grain texture
  67121. /**
  67122. * The chromatic aberration PostProcess id in the pipeline
  67123. * @type {string}
  67124. */
  67125. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  67126. /**
  67127. * The highlights enhancing PostProcess id in the pipeline
  67128. * @type {string}
  67129. */
  67130. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  67131. /**
  67132. * The depth-of-field PostProcess id in the pipeline
  67133. * @type {string}
  67134. */
  67135. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  67136. _this._scene = scene;
  67137. // Fetch texture samplers
  67138. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  67139. if (parameters.grain_texture) {
  67140. _this._grainTexture = parameters.grain_texture;
  67141. }
  67142. else {
  67143. _this._createGrainTexture();
  67144. }
  67145. // save parameters
  67146. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  67147. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  67148. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  67149. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  67150. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  67151. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  67152. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  67153. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  67154. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  67155. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  67156. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  67157. // Create effects
  67158. _this._createChromaticAberrationPostProcess(ratio);
  67159. _this._createHighlightsPostProcess(ratio);
  67160. _this._createDepthOfFieldPostProcess(ratio / 4);
  67161. // Set up pipeline
  67162. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  67163. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  67164. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  67165. if (_this._highlightsGain === -1) {
  67166. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  67167. }
  67168. // Finish
  67169. scene.postProcessRenderPipelineManager.addPipeline(_this);
  67170. if (cameras) {
  67171. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  67172. }
  67173. return _this;
  67174. }
  67175. // public methods (self explanatory)
  67176. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  67177. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  67178. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  67179. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  67180. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  67181. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  67182. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  67183. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  67184. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  67185. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  67186. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  67187. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  67188. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  67189. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  67190. };
  67191. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  67192. this._highlightsPostProcess.updateEffect();
  67193. };
  67194. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  67195. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  67196. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  67197. this._highlightsGain = amount;
  67198. };
  67199. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  67200. if (this._highlightsGain === -1) {
  67201. this._highlightsGain = 1.0;
  67202. }
  67203. this._highlightsThreshold = amount;
  67204. };
  67205. LensRenderingPipeline.prototype.disableHighlights = function () {
  67206. this._highlightsGain = -1;
  67207. };
  67208. /**
  67209. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  67210. */
  67211. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  67212. if (disableDepthRender === void 0) { disableDepthRender = false; }
  67213. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  67214. this._chromaticAberrationPostProcess = null;
  67215. this._highlightsPostProcess = null;
  67216. this._depthOfFieldPostProcess = null;
  67217. this._grainTexture.dispose();
  67218. if (disableDepthRender)
  67219. this._scene.disableDepthRenderer();
  67220. };
  67221. // colors shifting and distortion
  67222. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  67223. var _this = this;
  67224. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  67225. [], // samplers
  67226. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  67227. this._chromaticAberrationPostProcess.onApply = function (effect) {
  67228. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  67229. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  67230. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  67231. };
  67232. };
  67233. // highlights enhancing
  67234. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  67235. var _this = this;
  67236. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  67237. [], // samplers
  67238. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  67239. this._highlightsPostProcess.onApply = function (effect) {
  67240. effect.setFloat('gain', _this._highlightsGain);
  67241. effect.setFloat('threshold', _this._highlightsThreshold);
  67242. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  67243. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  67244. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  67245. };
  67246. };
  67247. // colors shifting and distortion
  67248. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  67249. var _this = this;
  67250. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  67251. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  67252. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  67253. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  67254. this._depthOfFieldPostProcess.onApply = function (effect) {
  67255. effect.setTexture("depthSampler", _this._depthTexture);
  67256. effect.setTexture("grainSampler", _this._grainTexture);
  67257. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  67258. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  67259. effect.setFloat('grain_amount', _this._grainAmount);
  67260. effect.setBool('blur_noise', _this._blurNoise);
  67261. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  67262. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  67263. effect.setFloat('distortion', _this._distortion);
  67264. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  67265. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  67266. effect.setFloat('aperture', _this._dofAperture);
  67267. effect.setFloat('darken', _this._dofDarken);
  67268. effect.setFloat('edge_blur', _this._edgeBlur);
  67269. effect.setBool('highlights', (_this._highlightsGain !== -1));
  67270. if (_this._scene.activeCamera) {
  67271. effect.setFloat('near', _this._scene.activeCamera.minZ);
  67272. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  67273. }
  67274. };
  67275. };
  67276. // creates a black and white random noise texture, 512x512
  67277. LensRenderingPipeline.prototype._createGrainTexture = function () {
  67278. var size = 512;
  67279. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  67280. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  67281. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  67282. var context = this._grainTexture.getContext();
  67283. var rand = function (min, max) {
  67284. return Math.random() * (max - min) + min;
  67285. };
  67286. var value;
  67287. for (var x = 0; x < size; x++) {
  67288. for (var y = 0; y < size; y++) {
  67289. value = Math.floor(rand(0.42, 0.58) * 255);
  67290. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  67291. context.fillRect(x, y, 1, 1);
  67292. }
  67293. }
  67294. this._grainTexture.update(false);
  67295. };
  67296. return LensRenderingPipeline;
  67297. }(BABYLON.PostProcessRenderPipeline));
  67298. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  67299. })(BABYLON || (BABYLON = {}));
  67300. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  67301. var BABYLON;
  67302. (function (BABYLON) {
  67303. var StandardRenderingPipeline = /** @class */ (function (_super) {
  67304. __extends(StandardRenderingPipeline, _super);
  67305. /**
  67306. * @constructor
  67307. * @param {string} name - The rendering pipeline name
  67308. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  67309. * @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)
  67310. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  67311. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  67312. */
  67313. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  67314. if (originalPostProcess === void 0) { originalPostProcess = null; }
  67315. var _this = _super.call(this, scene.getEngine(), name) || this;
  67316. _this.downSampleX4PostProcess = null;
  67317. _this.brightPassPostProcess = null;
  67318. _this.blurHPostProcesses = [];
  67319. _this.blurVPostProcesses = [];
  67320. _this.textureAdderPostProcess = null;
  67321. _this.volumetricLightPostProcess = null;
  67322. _this.volumetricLightSmoothXPostProcess = null;
  67323. _this.volumetricLightSmoothYPostProcess = null;
  67324. _this.volumetricLightMergePostProces = null;
  67325. _this.volumetricLightFinalPostProcess = null;
  67326. _this.luminancePostProcess = null;
  67327. _this.luminanceDownSamplePostProcesses = [];
  67328. _this.hdrPostProcess = null;
  67329. _this.textureAdderFinalPostProcess = null;
  67330. _this.lensFlareFinalPostProcess = null;
  67331. _this.hdrFinalPostProcess = null;
  67332. _this.lensFlarePostProcess = null;
  67333. _this.lensFlareComposePostProcess = null;
  67334. _this.motionBlurPostProcess = null;
  67335. _this.depthOfFieldPostProcess = null;
  67336. // Values
  67337. _this.brightThreshold = 1.0;
  67338. _this.blurWidth = 512.0;
  67339. _this.horizontalBlur = false;
  67340. _this.exposure = 1.0;
  67341. _this.lensTexture = null;
  67342. _this.volumetricLightCoefficient = 0.2;
  67343. _this.volumetricLightPower = 4.0;
  67344. _this.volumetricLightBlurScale = 64.0;
  67345. _this.sourceLight = null;
  67346. _this.hdrMinimumLuminance = 1.0;
  67347. _this.hdrDecreaseRate = 0.5;
  67348. _this.hdrIncreaseRate = 0.5;
  67349. _this.lensColorTexture = null;
  67350. _this.lensFlareStrength = 20.0;
  67351. _this.lensFlareGhostDispersal = 1.4;
  67352. _this.lensFlareHaloWidth = 0.7;
  67353. _this.lensFlareDistortionStrength = 16.0;
  67354. _this.lensStarTexture = null;
  67355. _this.lensFlareDirtTexture = null;
  67356. _this.depthOfFieldDistance = 10.0;
  67357. _this.depthOfFieldBlurWidth = 64.0;
  67358. _this.motionStrength = 1.0;
  67359. // IAnimatable
  67360. _this.animations = [];
  67361. _this._currentDepthOfFieldSource = null;
  67362. _this._hdrCurrentLuminance = 1.0;
  67363. // Getters and setters
  67364. _this._bloomEnabled = true;
  67365. _this._depthOfFieldEnabled = false;
  67366. _this._vlsEnabled = false;
  67367. _this._lensFlareEnabled = false;
  67368. _this._hdrEnabled = false;
  67369. _this._motionBlurEnabled = false;
  67370. _this._motionBlurSamples = 64.0;
  67371. _this._volumetricLightStepsCount = 50.0;
  67372. _this._cameras = cameras || [];
  67373. // Initialize
  67374. _this._scene = scene;
  67375. _this._basePostProcess = originalPostProcess;
  67376. _this._ratio = ratio;
  67377. // Misc
  67378. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  67379. // Finish
  67380. scene.postProcessRenderPipelineManager.addPipeline(_this);
  67381. _this._buildPipeline();
  67382. return _this;
  67383. }
  67384. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  67385. get: function () {
  67386. return this._bloomEnabled;
  67387. },
  67388. set: function (enabled) {
  67389. if (this._bloomEnabled === enabled) {
  67390. return;
  67391. }
  67392. this._bloomEnabled = enabled;
  67393. this._buildPipeline();
  67394. },
  67395. enumerable: true,
  67396. configurable: true
  67397. });
  67398. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  67399. get: function () {
  67400. return this._depthOfFieldEnabled;
  67401. },
  67402. set: function (enabled) {
  67403. if (this._depthOfFieldEnabled === enabled) {
  67404. return;
  67405. }
  67406. this._depthOfFieldEnabled = enabled;
  67407. this._buildPipeline();
  67408. },
  67409. enumerable: true,
  67410. configurable: true
  67411. });
  67412. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  67413. get: function () {
  67414. return this._lensFlareEnabled;
  67415. },
  67416. set: function (enabled) {
  67417. if (this._lensFlareEnabled === enabled) {
  67418. return;
  67419. }
  67420. this._lensFlareEnabled = enabled;
  67421. this._buildPipeline();
  67422. },
  67423. enumerable: true,
  67424. configurable: true
  67425. });
  67426. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  67427. get: function () {
  67428. return this._hdrEnabled;
  67429. },
  67430. set: function (enabled) {
  67431. if (this._hdrEnabled === enabled) {
  67432. return;
  67433. }
  67434. this._hdrEnabled = enabled;
  67435. this._buildPipeline();
  67436. },
  67437. enumerable: true,
  67438. configurable: true
  67439. });
  67440. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  67441. get: function () {
  67442. return this._vlsEnabled;
  67443. },
  67444. set: function (enabled) {
  67445. if (this._vlsEnabled === enabled) {
  67446. return;
  67447. }
  67448. if (enabled) {
  67449. var geometry = this._scene.enableGeometryBufferRenderer();
  67450. if (!geometry) {
  67451. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  67452. return;
  67453. }
  67454. }
  67455. this._vlsEnabled = enabled;
  67456. this._buildPipeline();
  67457. },
  67458. enumerable: true,
  67459. configurable: true
  67460. });
  67461. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  67462. get: function () {
  67463. return this._motionBlurEnabled;
  67464. },
  67465. set: function (enabled) {
  67466. if (this._motionBlurEnabled === enabled) {
  67467. return;
  67468. }
  67469. this._motionBlurEnabled = enabled;
  67470. this._buildPipeline();
  67471. },
  67472. enumerable: true,
  67473. configurable: true
  67474. });
  67475. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  67476. get: function () {
  67477. return this._volumetricLightStepsCount;
  67478. },
  67479. set: function (count) {
  67480. if (this.volumetricLightPostProcess) {
  67481. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  67482. }
  67483. this._volumetricLightStepsCount = count;
  67484. },
  67485. enumerable: true,
  67486. configurable: true
  67487. });
  67488. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  67489. get: function () {
  67490. return this._motionBlurSamples;
  67491. },
  67492. set: function (samples) {
  67493. if (this.motionBlurPostProcess) {
  67494. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  67495. }
  67496. this._motionBlurSamples = samples;
  67497. },
  67498. enumerable: true,
  67499. configurable: true
  67500. });
  67501. StandardRenderingPipeline.prototype._buildPipeline = function () {
  67502. var _this = this;
  67503. var ratio = this._ratio;
  67504. var scene = this._scene;
  67505. this._disposePostProcesses();
  67506. this._reset();
  67507. // Create pass post-process
  67508. if (!this._basePostProcess) {
  67509. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  67510. this.originalPostProcess.onApply = function (effect) {
  67511. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  67512. };
  67513. }
  67514. else {
  67515. this.originalPostProcess = this._basePostProcess;
  67516. }
  67517. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  67518. this._currentDepthOfFieldSource = this.originalPostProcess;
  67519. if (this._vlsEnabled) {
  67520. // Create volumetric light
  67521. this._createVolumetricLightPostProcess(scene, ratio);
  67522. // Create volumetric light final post-process
  67523. 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);
  67524. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  67525. }
  67526. if (this._bloomEnabled) {
  67527. // Create down sample X4 post-process
  67528. this._createDownSampleX4PostProcess(scene, ratio / 2);
  67529. // Create bright pass post-process
  67530. this._createBrightPassPostProcess(scene, ratio / 2);
  67531. // Create gaussian blur post-processes (down sampling blurs)
  67532. this._createBlurPostProcesses(scene, ratio / 4, 1);
  67533. // Create texture adder post-process
  67534. this._createTextureAdderPostProcess(scene, ratio);
  67535. // Create depth-of-field source post-process
  67536. 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);
  67537. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  67538. }
  67539. if (this._lensFlareEnabled) {
  67540. // Create lens flare post-process
  67541. this._createLensFlarePostProcess(scene, ratio);
  67542. // Create depth-of-field source post-process post lens-flare and disable it now
  67543. 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);
  67544. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  67545. }
  67546. if (this._hdrEnabled) {
  67547. // Create luminance
  67548. this._createLuminancePostProcesses(scene, this._floatTextureType);
  67549. // Create HDR
  67550. this._createHdrPostProcess(scene, ratio);
  67551. // Create depth-of-field source post-process post hdr and disable it now
  67552. 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);
  67553. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  67554. }
  67555. if (this._depthOfFieldEnabled) {
  67556. // Create gaussian blur used by depth-of-field
  67557. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  67558. // Create depth-of-field post-process
  67559. this._createDepthOfFieldPostProcess(scene, ratio);
  67560. }
  67561. if (this._motionBlurEnabled) {
  67562. // Create motion blur post-process
  67563. this._createMotionBlurPostProcess(scene, ratio);
  67564. }
  67565. if (this._cameras !== null) {
  67566. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  67567. }
  67568. };
  67569. // Down Sample X4 Post-Processs
  67570. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  67571. var _this = this;
  67572. var downSampleX4Offsets = new Array(32);
  67573. 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);
  67574. this.downSampleX4PostProcess.onApply = function (effect) {
  67575. var id = 0;
  67576. var width = _this.downSampleX4PostProcess.width;
  67577. var height = _this.downSampleX4PostProcess.height;
  67578. for (var i = -2; i < 2; i++) {
  67579. for (var j = -2; j < 2; j++) {
  67580. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  67581. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  67582. id += 2;
  67583. }
  67584. }
  67585. effect.setArray2("dsOffsets", downSampleX4Offsets);
  67586. };
  67587. // Add to pipeline
  67588. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  67589. };
  67590. // Brightpass Post-Process
  67591. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  67592. var _this = this;
  67593. var brightOffsets = new Array(8);
  67594. 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);
  67595. this.brightPassPostProcess.onApply = function (effect) {
  67596. var sU = (1.0 / _this.brightPassPostProcess.width);
  67597. var sV = (1.0 / _this.brightPassPostProcess.height);
  67598. brightOffsets[0] = -0.5 * sU;
  67599. brightOffsets[1] = 0.5 * sV;
  67600. brightOffsets[2] = 0.5 * sU;
  67601. brightOffsets[3] = 0.5 * sV;
  67602. brightOffsets[4] = -0.5 * sU;
  67603. brightOffsets[5] = -0.5 * sV;
  67604. brightOffsets[6] = 0.5 * sU;
  67605. brightOffsets[7] = -0.5 * sV;
  67606. effect.setArray2("dsOffsets", brightOffsets);
  67607. effect.setFloat("brightThreshold", _this.brightThreshold);
  67608. };
  67609. // Add to pipeline
  67610. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  67611. };
  67612. // Create blur H&V post-processes
  67613. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  67614. var _this = this;
  67615. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  67616. var engine = scene.getEngine();
  67617. 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);
  67618. 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);
  67619. blurX.onActivateObservable.add(function () {
  67620. var dw = blurX.width / engine.getRenderWidth();
  67621. blurX.kernel = _this[blurWidthKey] * dw;
  67622. });
  67623. blurY.onActivateObservable.add(function () {
  67624. var dw = blurY.height / engine.getRenderHeight();
  67625. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  67626. });
  67627. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  67628. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  67629. this.blurHPostProcesses.push(blurX);
  67630. this.blurVPostProcesses.push(blurY);
  67631. };
  67632. // Create texture adder post-process
  67633. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  67634. var _this = this;
  67635. 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);
  67636. this.textureAdderPostProcess.onApply = function (effect) {
  67637. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  67638. effect.setTexture("lensSampler", _this.lensTexture);
  67639. effect.setFloat("exposure", _this.exposure);
  67640. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  67641. };
  67642. // Add to pipeline
  67643. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  67644. };
  67645. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  67646. var _this = this;
  67647. var geometryRenderer = scene.enableGeometryBufferRenderer();
  67648. geometryRenderer.enablePosition = true;
  67649. var geometry = geometryRenderer.getGBuffer();
  67650. // Base post-process
  67651. 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));
  67652. var depthValues = BABYLON.Vector2.Zero();
  67653. this.volumetricLightPostProcess.onApply = function (effect) {
  67654. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  67655. var generator = _this.sourceLight.getShadowGenerator();
  67656. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  67657. effect.setTexture("positionSampler", geometry.textures[2]);
  67658. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  67659. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  67660. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  67661. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  67662. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  67663. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  67664. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  67665. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  67666. effect.setVector2("depthValues", depthValues);
  67667. }
  67668. };
  67669. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  67670. // Smooth
  67671. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  67672. // Merge
  67673. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  67674. this.volumetricLightMergePostProces.onApply = function (effect) {
  67675. effect.setTextureFromPostProcess("originalSampler", _this.originalPostProcess);
  67676. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  67677. };
  67678. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  67679. };
  67680. // Create luminance
  67681. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  67682. var _this = this;
  67683. // Create luminance
  67684. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  67685. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  67686. var offsets = [];
  67687. this.luminancePostProcess.onApply = function (effect) {
  67688. var sU = (1.0 / _this.luminancePostProcess.width);
  67689. var sV = (1.0 / _this.luminancePostProcess.height);
  67690. offsets[0] = -0.5 * sU;
  67691. offsets[1] = 0.5 * sV;
  67692. offsets[2] = 0.5 * sU;
  67693. offsets[3] = 0.5 * sV;
  67694. offsets[4] = -0.5 * sU;
  67695. offsets[5] = -0.5 * sV;
  67696. offsets[6] = 0.5 * sU;
  67697. offsets[7] = -0.5 * sV;
  67698. effect.setArray2("lumOffsets", offsets);
  67699. };
  67700. // Add to pipeline
  67701. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  67702. // Create down sample luminance
  67703. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  67704. var size = Math.pow(3, i);
  67705. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  67706. if (i === 0) {
  67707. defines += "#define FINAL_DOWN_SAMPLER";
  67708. }
  67709. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  67710. this.luminanceDownSamplePostProcesses.push(postProcess);
  67711. }
  67712. // Create callbacks and add effects
  67713. var lastLuminance = this.luminancePostProcess;
  67714. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  67715. var downSampleOffsets = new Array(18);
  67716. pp.onApply = function (effect) {
  67717. if (!lastLuminance) {
  67718. return;
  67719. }
  67720. var id = 0;
  67721. for (var x = -1; x < 2; x++) {
  67722. for (var y = -1; y < 2; y++) {
  67723. downSampleOffsets[id] = x / lastLuminance.width;
  67724. downSampleOffsets[id + 1] = y / lastLuminance.height;
  67725. id += 2;
  67726. }
  67727. }
  67728. effect.setArray2("dsOffsets", downSampleOffsets);
  67729. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  67730. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  67731. lastLuminance = _this.luminancePostProcess;
  67732. }
  67733. else {
  67734. lastLuminance = pp;
  67735. }
  67736. };
  67737. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  67738. pp.onAfterRender = function (effect) {
  67739. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  67740. 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);
  67741. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  67742. };
  67743. }
  67744. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  67745. });
  67746. };
  67747. // Create HDR post-process
  67748. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  67749. var _this = this;
  67750. 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);
  67751. var outputLiminance = 1;
  67752. var time = 0;
  67753. var lastTime = 0;
  67754. this.hdrPostProcess.onApply = function (effect) {
  67755. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  67756. time += scene.getEngine().getDeltaTime();
  67757. if (outputLiminance < 0) {
  67758. outputLiminance = _this._hdrCurrentLuminance;
  67759. }
  67760. else {
  67761. var dt = (lastTime - time) / 1000.0;
  67762. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  67763. outputLiminance += _this.hdrDecreaseRate * dt;
  67764. }
  67765. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  67766. outputLiminance -= _this.hdrIncreaseRate * dt;
  67767. }
  67768. else {
  67769. outputLiminance = _this._hdrCurrentLuminance;
  67770. }
  67771. }
  67772. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  67773. effect.setFloat("averageLuminance", outputLiminance);
  67774. lastTime = time;
  67775. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  67776. };
  67777. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  67778. };
  67779. // Create lens flare post-process
  67780. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  67781. var _this = this;
  67782. 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);
  67783. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  67784. this._createBlurPostProcesses(scene, ratio / 4, 2);
  67785. 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);
  67786. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  67787. var resolution = new BABYLON.Vector2(0, 0);
  67788. // Lens flare
  67789. this.lensFlarePostProcess.onApply = function (effect) {
  67790. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  67791. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  67792. effect.setFloat("strength", _this.lensFlareStrength);
  67793. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  67794. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  67795. // Shift
  67796. resolution.x = _this.lensFlarePostProcess.width;
  67797. resolution.y = _this.lensFlarePostProcess.height;
  67798. effect.setVector2("resolution", resolution);
  67799. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  67800. };
  67801. // Compose
  67802. 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);
  67803. 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);
  67804. this.lensFlareComposePostProcess.onApply = function (effect) {
  67805. if (!_this._scene.activeCamera) {
  67806. return;
  67807. }
  67808. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  67809. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  67810. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  67811. // Lens start rotation matrix
  67812. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  67813. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  67814. 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));
  67815. camRot *= 4.0;
  67816. 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);
  67817. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  67818. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  67819. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  67820. };
  67821. };
  67822. // Create depth-of-field post-process
  67823. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  67824. var _this = this;
  67825. 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);
  67826. this.depthOfFieldPostProcess.onApply = function (effect) {
  67827. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  67828. effect.setTexture("depthSampler", _this._getDepthTexture());
  67829. effect.setFloat("distance", _this.depthOfFieldDistance);
  67830. };
  67831. // Add to pipeline
  67832. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  67833. };
  67834. // Create motion blur post-process
  67835. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  67836. var _this = this;
  67837. 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);
  67838. var motionScale = 0;
  67839. var prevViewProjection = BABYLON.Matrix.Identity();
  67840. var invViewProjection = BABYLON.Matrix.Identity();
  67841. var viewProjection = BABYLON.Matrix.Identity();
  67842. var screenSize = BABYLON.Vector2.Zero();
  67843. this.motionBlurPostProcess.onApply = function (effect) {
  67844. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  67845. viewProjection.invertToRef(invViewProjection);
  67846. effect.setMatrix("inverseViewProjection", invViewProjection);
  67847. effect.setMatrix("prevViewProjection", prevViewProjection);
  67848. prevViewProjection = viewProjection;
  67849. screenSize.x = _this.motionBlurPostProcess.width;
  67850. screenSize.y = _this.motionBlurPostProcess.height;
  67851. effect.setVector2("screenSize", screenSize);
  67852. motionScale = scene.getEngine().getFps() / 60.0;
  67853. effect.setFloat("motionScale", motionScale);
  67854. effect.setFloat("motionStrength", _this.motionStrength);
  67855. effect.setTexture("depthSampler", _this._getDepthTexture());
  67856. };
  67857. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  67858. };
  67859. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  67860. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  67861. var renderer = this._scene.enableGeometryBufferRenderer();
  67862. return renderer.getGBuffer().textures[0];
  67863. }
  67864. return this._scene.enableDepthRenderer().getDepthMap();
  67865. };
  67866. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  67867. for (var i = 0; i < this._cameras.length; i++) {
  67868. var camera = this._cameras[i];
  67869. if (this.originalPostProcess) {
  67870. this.originalPostProcess.dispose(camera);
  67871. }
  67872. if (this.downSampleX4PostProcess) {
  67873. this.downSampleX4PostProcess.dispose(camera);
  67874. }
  67875. if (this.brightPassPostProcess) {
  67876. this.brightPassPostProcess.dispose(camera);
  67877. }
  67878. if (this.textureAdderPostProcess) {
  67879. this.textureAdderPostProcess.dispose(camera);
  67880. }
  67881. if (this.textureAdderFinalPostProcess) {
  67882. this.textureAdderFinalPostProcess.dispose(camera);
  67883. }
  67884. if (this.volumetricLightPostProcess) {
  67885. this.volumetricLightPostProcess.dispose(camera);
  67886. }
  67887. if (this.volumetricLightSmoothXPostProcess) {
  67888. this.volumetricLightSmoothXPostProcess.dispose(camera);
  67889. }
  67890. if (this.volumetricLightSmoothYPostProcess) {
  67891. this.volumetricLightSmoothYPostProcess.dispose(camera);
  67892. }
  67893. if (this.volumetricLightMergePostProces) {
  67894. this.volumetricLightMergePostProces.dispose(camera);
  67895. }
  67896. if (this.volumetricLightFinalPostProcess) {
  67897. this.volumetricLightFinalPostProcess.dispose(camera);
  67898. }
  67899. if (this.lensFlarePostProcess) {
  67900. this.lensFlarePostProcess.dispose(camera);
  67901. }
  67902. if (this.lensFlareComposePostProcess) {
  67903. this.lensFlareComposePostProcess.dispose(camera);
  67904. }
  67905. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  67906. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  67907. }
  67908. if (this.luminancePostProcess) {
  67909. this.luminancePostProcess.dispose(camera);
  67910. }
  67911. if (this.hdrPostProcess) {
  67912. this.hdrPostProcess.dispose(camera);
  67913. }
  67914. if (this.hdrFinalPostProcess) {
  67915. this.hdrFinalPostProcess.dispose(camera);
  67916. }
  67917. if (this.depthOfFieldPostProcess) {
  67918. this.depthOfFieldPostProcess.dispose(camera);
  67919. }
  67920. if (this.motionBlurPostProcess) {
  67921. this.motionBlurPostProcess.dispose(camera);
  67922. }
  67923. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  67924. this.blurHPostProcesses[j].dispose(camera);
  67925. }
  67926. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  67927. this.blurVPostProcesses[j].dispose(camera);
  67928. }
  67929. }
  67930. this.originalPostProcess = null;
  67931. this.downSampleX4PostProcess = null;
  67932. this.brightPassPostProcess = null;
  67933. this.textureAdderPostProcess = null;
  67934. this.textureAdderFinalPostProcess = null;
  67935. this.volumetricLightPostProcess = null;
  67936. this.volumetricLightSmoothXPostProcess = null;
  67937. this.volumetricLightSmoothYPostProcess = null;
  67938. this.volumetricLightMergePostProces = null;
  67939. this.volumetricLightFinalPostProcess = null;
  67940. this.lensFlarePostProcess = null;
  67941. this.lensFlareComposePostProcess = null;
  67942. this.luminancePostProcess = null;
  67943. this.hdrPostProcess = null;
  67944. this.hdrFinalPostProcess = null;
  67945. this.depthOfFieldPostProcess = null;
  67946. this.motionBlurPostProcess = null;
  67947. this.luminanceDownSamplePostProcesses = [];
  67948. this.blurHPostProcesses = [];
  67949. this.blurVPostProcesses = [];
  67950. };
  67951. // Dispose
  67952. StandardRenderingPipeline.prototype.dispose = function () {
  67953. this._disposePostProcesses();
  67954. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  67955. _super.prototype.dispose.call(this);
  67956. };
  67957. // Serialize rendering pipeline
  67958. StandardRenderingPipeline.prototype.serialize = function () {
  67959. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  67960. serializationObject.customType = "StandardRenderingPipeline";
  67961. return serializationObject;
  67962. };
  67963. /**
  67964. * Static members
  67965. */
  67966. // Parse serialized pipeline
  67967. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  67968. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  67969. };
  67970. // Luminance steps
  67971. StandardRenderingPipeline.LuminanceSteps = 6;
  67972. __decorate([
  67973. BABYLON.serialize()
  67974. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  67975. __decorate([
  67976. BABYLON.serialize()
  67977. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  67978. __decorate([
  67979. BABYLON.serialize()
  67980. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  67981. __decorate([
  67982. BABYLON.serialize()
  67983. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  67984. __decorate([
  67985. BABYLON.serializeAsTexture("lensTexture")
  67986. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  67987. __decorate([
  67988. BABYLON.serialize()
  67989. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  67990. __decorate([
  67991. BABYLON.serialize()
  67992. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  67993. __decorate([
  67994. BABYLON.serialize()
  67995. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  67996. __decorate([
  67997. BABYLON.serialize()
  67998. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  67999. __decorate([
  68000. BABYLON.serialize()
  68001. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  68002. __decorate([
  68003. BABYLON.serialize()
  68004. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  68005. __decorate([
  68006. BABYLON.serializeAsTexture("lensColorTexture")
  68007. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  68008. __decorate([
  68009. BABYLON.serialize()
  68010. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  68011. __decorate([
  68012. BABYLON.serialize()
  68013. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  68014. __decorate([
  68015. BABYLON.serialize()
  68016. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  68017. __decorate([
  68018. BABYLON.serialize()
  68019. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  68020. __decorate([
  68021. BABYLON.serializeAsTexture("lensStarTexture")
  68022. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  68023. __decorate([
  68024. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  68025. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  68026. __decorate([
  68027. BABYLON.serialize()
  68028. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  68029. __decorate([
  68030. BABYLON.serialize()
  68031. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  68032. __decorate([
  68033. BABYLON.serialize()
  68034. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  68035. __decorate([
  68036. BABYLON.serialize()
  68037. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  68038. __decorate([
  68039. BABYLON.serialize()
  68040. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  68041. __decorate([
  68042. BABYLON.serialize()
  68043. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  68044. __decorate([
  68045. BABYLON.serialize()
  68046. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  68047. __decorate([
  68048. BABYLON.serialize()
  68049. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  68050. __decorate([
  68051. BABYLON.serialize()
  68052. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  68053. __decorate([
  68054. BABYLON.serialize()
  68055. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  68056. __decorate([
  68057. BABYLON.serialize()
  68058. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  68059. __decorate([
  68060. BABYLON.serialize()
  68061. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  68062. return StandardRenderingPipeline;
  68063. }(BABYLON.PostProcessRenderPipeline));
  68064. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  68065. })(BABYLON || (BABYLON = {}));
  68066. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  68067. var BABYLON;
  68068. (function (BABYLON) {
  68069. var FxaaPostProcess = /** @class */ (function (_super) {
  68070. __extends(FxaaPostProcess, _super);
  68071. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  68072. if (camera === void 0) { camera = null; }
  68073. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68074. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  68075. _this.onApplyObservable.add(function (effect) {
  68076. var texelSize = _this.texelSize;
  68077. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  68078. });
  68079. return _this;
  68080. }
  68081. return FxaaPostProcess;
  68082. }(BABYLON.PostProcess));
  68083. BABYLON.FxaaPostProcess = FxaaPostProcess;
  68084. })(BABYLON || (BABYLON = {}));
  68085. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  68086. var BABYLON;
  68087. (function (BABYLON) {
  68088. /**
  68089. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  68090. */
  68091. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  68092. __extends(CircleOfConfusionPostProcess, _super);
  68093. /**
  68094. * Creates a new instance of @see CircleOfConfusionPostProcess
  68095. * @param name The name of the effect.
  68096. * @param depthTexture The depth texture of the scene to compute the circle of confusion.
  68097. * @param options The required width/height ratio to downsize to before computing the render pass.
  68098. * @param camera The camera to apply the render pass to.
  68099. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  68100. * @param engine The engine which the post process will be applied. (default: current engine)
  68101. * @param reusable If the post process can be reused on the same frame. (default: false)
  68102. * @param textureType Type of textures used when performing the post process. (default: 0)
  68103. */
  68104. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType) {
  68105. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68106. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType) || this;
  68107. /**
  68108. * Max lens size in scene units/1000 (eg. millimeter). Standard cameras are 50mm. (default: 50) The diamater of the resulting aperture can be computed by lensSize/fStop.
  68109. */
  68110. _this.lensSize = 50;
  68111. /**
  68112. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  68113. */
  68114. _this.fStop = 1.4;
  68115. /**
  68116. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  68117. */
  68118. _this.focusDistance = 2000;
  68119. /**
  68120. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  68121. */
  68122. _this.focalLength = 50;
  68123. _this.onApplyObservable.add(function (effect) {
  68124. effect.setTexture("depthSampler", depthTexture);
  68125. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  68126. var aperture = _this.lensSize / _this.fStop;
  68127. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  68128. effect.setFloat('focusDistance', _this.focusDistance);
  68129. effect.setFloat('cocPrecalculation', cocPrecalculation);
  68130. effect.setFloat2('cameraMinMaxZ', depthTexture.activeCamera.minZ, depthTexture.activeCamera.maxZ);
  68131. });
  68132. return _this;
  68133. }
  68134. return CircleOfConfusionPostProcess;
  68135. }(BABYLON.PostProcess));
  68136. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  68137. })(BABYLON || (BABYLON = {}));
  68138. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  68139. var BABYLON;
  68140. (function (BABYLON) {
  68141. /**
  68142. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  68143. */
  68144. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  68145. __extends(DepthOfFieldMergePostProcess, _super);
  68146. /**
  68147. * Creates a new instance of @see CircleOfConfusionPostProcess
  68148. * @param name The name of the effect.
  68149. * @param original The non-blurred image to be modified
  68150. * @param circleOfConfusion The circle of confusion post process that will determine how blurred each pixel should become.
  68151. * @param blurSteps Incrimental bluring post processes.
  68152. * @param options The required width/height ratio to downsize to before computing the render pass.
  68153. * @param camera The camera to apply the render pass to.
  68154. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  68155. * @param engine The engine which the post process will be applied. (default: current engine)
  68156. * @param reusable If the post process can be reused on the same frame. (default: false)
  68157. * @param textureType Type of textures used when performing the post process. (default: 0)
  68158. */
  68159. function DepthOfFieldMergePostProcess(name, original, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType) {
  68160. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68161. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "originalSampler", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, "#define BLUR_LEVEL " + blurSteps.length + "\n", textureType) || this;
  68162. _this.onApplyObservable.add(function (effect) {
  68163. effect.setTextureFromPostProcess("circleOfConfusionSampler", circleOfConfusion);
  68164. effect.setTextureFromPostProcess("originalSampler", original);
  68165. blurSteps.forEach(function (step, index) {
  68166. effect.setTextureFromPostProcess("blurStep" + (index + 1), step);
  68167. });
  68168. });
  68169. return _this;
  68170. }
  68171. return DepthOfFieldMergePostProcess;
  68172. }(BABYLON.PostProcess));
  68173. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  68174. })(BABYLON || (BABYLON = {}));
  68175. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  68176. var BABYLON;
  68177. (function (BABYLON) {
  68178. /**
  68179. * Specifies the level of max blur that should be applied when using the depth of field effect
  68180. */
  68181. var DepthOfFieldEffectBlurLevel;
  68182. (function (DepthOfFieldEffectBlurLevel) {
  68183. /**
  68184. * Subtle blur
  68185. */
  68186. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  68187. /**
  68188. * Medium blur
  68189. */
  68190. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  68191. /**
  68192. * Large blur
  68193. */
  68194. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  68195. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  68196. ;
  68197. /**
  68198. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  68199. */
  68200. var DepthOfFieldEffect = /** @class */ (function (_super) {
  68201. __extends(DepthOfFieldEffect, _super);
  68202. /**
  68203. * Creates a new instance of @see DepthOfFieldEffect
  68204. * @param scene The scene the effect belongs to.
  68205. * @param depthTexture The depth texture of the scene to compute the circle of confusion.
  68206. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  68207. */
  68208. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType) {
  68209. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  68210. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  68211. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  68212. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  68213. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  68214. // Capture circle of confusion texture
  68215. _this._depthOfFieldPass = new BABYLON.PassPostProcess("depthOfFieldPass", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  68216. _this._depthOfFieldPass.autoClear = false;
  68217. // Create a pyramid of blurred images (eg. fullSize 1/4 blur, half size 1/2 blur, quarter size 3/4 blur, eith size 4/4 blur)
  68218. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  68219. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  68220. _this._depthOfFieldBlurY = [];
  68221. _this._depthOfFieldBlurX = [];
  68222. var blurCount = 1;
  68223. var kernelSize = 15;
  68224. switch (blurLevel) {
  68225. case DepthOfFieldEffectBlurLevel.High: {
  68226. blurCount = 3;
  68227. kernelSize = 51;
  68228. break;
  68229. }
  68230. case DepthOfFieldEffectBlurLevel.Medium: {
  68231. blurCount = 2;
  68232. kernelSize = 31;
  68233. break;
  68234. }
  68235. default: {
  68236. kernelSize = 15;
  68237. blurCount = 1;
  68238. break;
  68239. }
  68240. }
  68241. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  68242. for (var i = 0; i < blurCount; i++) {
  68243. var blurY = new BABYLON.DepthOfFieldBlurPostProcess("verticle blur", scene, new BABYLON.Vector2(0, 1.0), adjustedKernelSize, 1.0 / Math.pow(2, i), null, _this._depthOfFieldPass, i == 0 ? _this._circleOfConfusion : null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  68244. blurY.autoClear = false;
  68245. var blurX = new BABYLON.DepthOfFieldBlurPostProcess("horizontal blur", scene, new BABYLON.Vector2(1.0, 0), adjustedKernelSize, 1.0 / Math.pow(2, i), null, _this._depthOfFieldPass, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  68246. blurX.autoClear = false;
  68247. _this._depthOfFieldBlurY.push(blurY);
  68248. _this._depthOfFieldBlurX.push(blurX);
  68249. }
  68250. // Merge blurred images with original image based on circleOfConfusion
  68251. _this._depthOfFieldMerge = new BABYLON.DepthOfFieldMergePostProcess("depthOfFieldMerge", _this._circleOfConfusion, _this._depthOfFieldPass, _this._depthOfFieldBlurY.slice(1), 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  68252. _this._depthOfFieldMerge.autoClear = false;
  68253. // Set all post processes on the effect.
  68254. var effects = [_this._circleOfConfusion, _this._depthOfFieldPass];
  68255. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  68256. effects.push(_this._depthOfFieldBlurY[i]);
  68257. effects.push(_this._depthOfFieldBlurX[i]);
  68258. }
  68259. effects.push(_this._depthOfFieldMerge);
  68260. return effects;
  68261. }, true) || this;
  68262. return _this;
  68263. }
  68264. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  68265. get: function () {
  68266. return this._circleOfConfusion.focalLength;
  68267. },
  68268. /**
  68269. * The focal the length of the camera used in the effect
  68270. */
  68271. set: function (value) {
  68272. this._circleOfConfusion.focalLength = value;
  68273. },
  68274. enumerable: true,
  68275. configurable: true
  68276. });
  68277. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  68278. get: function () {
  68279. return this._circleOfConfusion.fStop;
  68280. },
  68281. /**
  68282. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  68283. */
  68284. set: function (value) {
  68285. this._circleOfConfusion.fStop = value;
  68286. },
  68287. enumerable: true,
  68288. configurable: true
  68289. });
  68290. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  68291. get: function () {
  68292. return this._circleOfConfusion.focusDistance;
  68293. },
  68294. /**
  68295. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  68296. */
  68297. set: function (value) {
  68298. this._circleOfConfusion.focusDistance = value;
  68299. },
  68300. enumerable: true,
  68301. configurable: true
  68302. });
  68303. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  68304. get: function () {
  68305. return this._circleOfConfusion.lensSize;
  68306. },
  68307. /**
  68308. * Max lens size in scene units/1000 (eg. millimeter). Standard cameras are 50mm. (default: 50) The diamater of the resulting aperture can be computed by lensSize/fStop.
  68309. */
  68310. set: function (value) {
  68311. this._circleOfConfusion.lensSize = value;
  68312. },
  68313. enumerable: true,
  68314. configurable: true
  68315. });
  68316. /**
  68317. * Disposes each of the internal effects for a given camera.
  68318. * @param camera The camera to dispose the effect on.
  68319. */
  68320. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  68321. this._depthOfFieldPass.dispose(camera);
  68322. this._circleOfConfusion.dispose(camera);
  68323. this._depthOfFieldBlurX.forEach(function (element) {
  68324. element.dispose(camera);
  68325. });
  68326. this._depthOfFieldBlurY.forEach(function (element) {
  68327. element.dispose(camera);
  68328. });
  68329. this._depthOfFieldMerge.dispose(camera);
  68330. };
  68331. return DepthOfFieldEffect;
  68332. }(BABYLON.PostProcessRenderEffect));
  68333. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  68334. })(BABYLON || (BABYLON = {}));
  68335. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  68336. var BABYLON;
  68337. (function (BABYLON) {
  68338. /**
  68339. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  68340. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  68341. */
  68342. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  68343. __extends(DefaultRenderingPipeline, _super);
  68344. /**
  68345. * @constructor
  68346. * @param {string} name - The rendering pipeline name
  68347. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  68348. * @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)
  68349. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  68350. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  68351. */
  68352. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  68353. if (automaticBuild === void 0) { automaticBuild = true; }
  68354. var _this = _super.call(this, scene.getEngine(), name) || this;
  68355. /**
  68356. * ID of the pass post process used for bloom,
  68357. */
  68358. _this.PassPostProcessId = "PassPostProcessEffect";
  68359. /**
  68360. * ID of the highlight post process used for bloom,
  68361. */
  68362. _this.HighLightsPostProcessId = "HighLightsPostProcessEffect";
  68363. /**
  68364. * ID of the blurX post process used for bloom,
  68365. */
  68366. _this.BlurXPostProcessId = "BlurXPostProcessEffect";
  68367. /**
  68368. * ID of the blurY post process used for bloom,
  68369. */
  68370. _this.BlurYPostProcessId = "BlurYPostProcessEffect";
  68371. /**
  68372. * ID of the copy back post process used for bloom,
  68373. */
  68374. _this.CopyBackPostProcessId = "CopyBackPostProcessEffect";
  68375. /**
  68376. * ID of the image processing post process;
  68377. */
  68378. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  68379. /**
  68380. * ID of the Fast Approximate Anti-Aliasing post process;
  68381. */
  68382. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  68383. /**
  68384. * ID of the final merge post process;
  68385. */
  68386. _this.FinalMergePostProcessId = "FinalMergePostProcessEffect";
  68387. /**
  68388. * Animations which can be used to tweak settings over a period of time
  68389. */
  68390. _this.animations = [];
  68391. // Values
  68392. _this._bloomEnabled = false;
  68393. _this._depthOfFieldEnabled = false;
  68394. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  68395. _this._fxaaEnabled = false;
  68396. _this._imageProcessingEnabled = true;
  68397. _this._bloomScale = 0.6;
  68398. _this._buildAllowed = true;
  68399. /**
  68400. * Specifies the size of the bloom blur kernel, relative to the final output size
  68401. */
  68402. _this.bloomKernel = 64;
  68403. /**
  68404. * Specifies the weight of the bloom in the final rendering
  68405. */
  68406. _this._bloomWeight = 0.15;
  68407. _this._cameras = cameras || [];
  68408. _this._buildAllowed = automaticBuild;
  68409. // Initialize
  68410. _this._scene = scene;
  68411. var caps = _this._scene.getEngine().getCaps();
  68412. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  68413. // Misc
  68414. if (_this._hdr) {
  68415. if (caps.textureHalfFloatRender) {
  68416. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  68417. }
  68418. else if (caps.textureFloatRender) {
  68419. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  68420. }
  68421. }
  68422. else {
  68423. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  68424. }
  68425. // Attach
  68426. scene.postProcessRenderPipelineManager.addPipeline(_this);
  68427. _this._buildPipeline();
  68428. return _this;
  68429. }
  68430. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  68431. get: function () {
  68432. return this._bloomWeight;
  68433. },
  68434. /**
  68435. * The strength of the bloom.
  68436. */
  68437. set: function (value) {
  68438. if (this._bloomWeight === value) {
  68439. return;
  68440. }
  68441. this._bloomWeight = value;
  68442. if (this._hdr && this.copyBack) {
  68443. this.copyBack.alphaConstants = new BABYLON.Color4(value, value, value, value);
  68444. }
  68445. },
  68446. enumerable: true,
  68447. configurable: true
  68448. });
  68449. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  68450. get: function () {
  68451. return this._bloomScale;
  68452. },
  68453. /**
  68454. * The scale of the bloom, lower value will provide better performance.
  68455. */
  68456. set: function (value) {
  68457. if (this._bloomScale === value) {
  68458. return;
  68459. }
  68460. this._bloomScale = value;
  68461. this._buildPipeline();
  68462. },
  68463. enumerable: true,
  68464. configurable: true
  68465. });
  68466. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  68467. get: function () {
  68468. return this._bloomEnabled;
  68469. },
  68470. /**
  68471. * Enable or disable the bloom from the pipeline
  68472. */
  68473. set: function (enabled) {
  68474. if (this._bloomEnabled === enabled) {
  68475. return;
  68476. }
  68477. this._bloomEnabled = enabled;
  68478. this._buildPipeline();
  68479. },
  68480. enumerable: true,
  68481. configurable: true
  68482. });
  68483. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  68484. /**
  68485. * If the depth of field is enabled.
  68486. */
  68487. get: function () {
  68488. return this._depthOfFieldEnabled;
  68489. },
  68490. set: function (enabled) {
  68491. if (this._depthOfFieldEnabled === enabled) {
  68492. return;
  68493. }
  68494. this._depthOfFieldEnabled = enabled;
  68495. this._buildPipeline();
  68496. },
  68497. enumerable: true,
  68498. configurable: true
  68499. });
  68500. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  68501. /**
  68502. * Blur level of the depth of field effect. (Higher blur will effect performance)
  68503. */
  68504. get: function () {
  68505. return this._depthOfFieldBlurLevel;
  68506. },
  68507. set: function (value) {
  68508. if (this._depthOfFieldBlurLevel === value) {
  68509. return;
  68510. }
  68511. this._depthOfFieldBlurLevel = value;
  68512. this._buildPipeline();
  68513. },
  68514. enumerable: true,
  68515. configurable: true
  68516. });
  68517. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  68518. get: function () {
  68519. return this._fxaaEnabled;
  68520. },
  68521. /**
  68522. * If the anti aliasing is enabled.
  68523. */
  68524. set: function (enabled) {
  68525. if (this._fxaaEnabled === enabled) {
  68526. return;
  68527. }
  68528. this._fxaaEnabled = enabled;
  68529. this._buildPipeline();
  68530. },
  68531. enumerable: true,
  68532. configurable: true
  68533. });
  68534. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  68535. get: function () {
  68536. return this._imageProcessingEnabled;
  68537. },
  68538. /**
  68539. * If image processing is enabled.
  68540. */
  68541. set: function (enabled) {
  68542. if (this._imageProcessingEnabled === enabled) {
  68543. return;
  68544. }
  68545. this._imageProcessingEnabled = enabled;
  68546. this._buildPipeline();
  68547. },
  68548. enumerable: true,
  68549. configurable: true
  68550. });
  68551. /**
  68552. * Force the compilation of the entire pipeline.
  68553. */
  68554. DefaultRenderingPipeline.prototype.prepare = function () {
  68555. var previousState = this._buildAllowed;
  68556. this._buildAllowed = true;
  68557. this._buildPipeline();
  68558. this._buildAllowed = previousState;
  68559. };
  68560. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  68561. var _this = this;
  68562. if (!this._buildAllowed) {
  68563. return;
  68564. }
  68565. var engine = this._scene.getEngine();
  68566. this._disposePostProcesses();
  68567. this._reset();
  68568. if (this.depthOfFieldEnabled) {
  68569. // Enable and get current depth map
  68570. var depthTexture = this._scene.enableDepthRenderer(this._cameras[0]).getDepthMap();
  68571. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, depthTexture, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType);
  68572. this.addEffect(this.depthOfField);
  68573. }
  68574. if (this.bloomEnabled) {
  68575. this.pass = new BABYLON.PassPostProcess("sceneRenderTarget", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  68576. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.PassPostProcessId, function () { return _this.pass; }, true));
  68577. if (!this._hdr) {
  68578. this.highlights = new BABYLON.HighlightsPostProcess("highlights", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  68579. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.HighLightsPostProcessId, function () { return _this.highlights; }, true));
  68580. this.highlights.autoClear = false;
  68581. this.highlights.alwaysForcePOT = true;
  68582. }
  68583. 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);
  68584. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurXPostProcessId, function () { return _this.blurX; }, true));
  68585. this.blurX.alwaysForcePOT = true;
  68586. this.blurX.autoClear = false;
  68587. this.blurX.onActivateObservable.add(function () {
  68588. var dw = _this.blurX.width / engine.getRenderWidth(true);
  68589. _this.blurX.kernel = _this.bloomKernel * dw;
  68590. });
  68591. 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);
  68592. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurYPostProcessId, function () { return _this.blurY; }, true));
  68593. this.blurY.alwaysForcePOT = true;
  68594. this.blurY.autoClear = false;
  68595. this.blurY.onActivateObservable.add(function () {
  68596. var dh = _this.blurY.height / engine.getRenderHeight(true);
  68597. _this.blurY.kernel = _this.bloomKernel * dh;
  68598. });
  68599. this.copyBack = new BABYLON.PassPostProcess("bloomBlendBlit", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  68600. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.CopyBackPostProcessId, function () { return _this.copyBack; }, true));
  68601. this.copyBack.alwaysForcePOT = true;
  68602. if (this._hdr) {
  68603. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_INTERPOLATE;
  68604. var w = this.bloomWeight;
  68605. this.copyBack.alphaConstants = new BABYLON.Color4(w, w, w, w);
  68606. }
  68607. else {
  68608. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_SCREENMODE;
  68609. }
  68610. this.copyBack.autoClear = false;
  68611. }
  68612. if (this._imageProcessingEnabled) {
  68613. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  68614. if (this._hdr) {
  68615. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  68616. }
  68617. else {
  68618. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  68619. }
  68620. }
  68621. if (this.fxaaEnabled) {
  68622. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  68623. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  68624. this.fxaa.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  68625. }
  68626. else if (this._hdr && this.imageProcessing) {
  68627. this.finalMerge = this.imageProcessing;
  68628. }
  68629. else {
  68630. this.finalMerge = new BABYLON.PassPostProcess("finalMerge", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  68631. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FinalMergePostProcessId, function () { return _this.finalMerge; }, true));
  68632. this.finalMerge.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  68633. }
  68634. if (this.bloomEnabled) {
  68635. if (this._hdr) {
  68636. this.copyBack.shareOutputWith(this.blurX);
  68637. if (this.imageProcessing) {
  68638. this.imageProcessing.shareOutputWith(this.pass);
  68639. this.imageProcessing.autoClear = false;
  68640. }
  68641. else if (this.fxaa) {
  68642. this.fxaa.shareOutputWith(this.pass);
  68643. }
  68644. else {
  68645. this.finalMerge.shareOutputWith(this.pass);
  68646. }
  68647. }
  68648. else {
  68649. if (this.fxaa) {
  68650. this.fxaa.shareOutputWith(this.pass);
  68651. }
  68652. else {
  68653. this.finalMerge.shareOutputWith(this.pass);
  68654. }
  68655. }
  68656. }
  68657. if (this._cameras !== null) {
  68658. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  68659. }
  68660. };
  68661. DefaultRenderingPipeline.prototype._disposePostProcesses = function () {
  68662. for (var i = 0; i < this._cameras.length; i++) {
  68663. var camera = this._cameras[i];
  68664. if (this.pass) {
  68665. this.pass.dispose(camera);
  68666. }
  68667. if (this.highlights) {
  68668. this.highlights.dispose(camera);
  68669. }
  68670. if (this.blurX) {
  68671. this.blurX.dispose(camera);
  68672. }
  68673. if (this.blurY) {
  68674. this.blurY.dispose(camera);
  68675. }
  68676. if (this.copyBack) {
  68677. this.copyBack.dispose(camera);
  68678. }
  68679. if (this.imageProcessing) {
  68680. this.imageProcessing.dispose(camera);
  68681. }
  68682. if (this.fxaa) {
  68683. this.fxaa.dispose(camera);
  68684. }
  68685. if (this.finalMerge) {
  68686. this.finalMerge.dispose(camera);
  68687. }
  68688. if (this.depthOfField) {
  68689. this.depthOfField.disposeEffects(camera);
  68690. }
  68691. }
  68692. this.pass = null;
  68693. this.highlights = null;
  68694. this.blurX = null;
  68695. this.blurY = null;
  68696. this.copyBack = null;
  68697. this.imageProcessing = null;
  68698. this.fxaa = null;
  68699. this.finalMerge = null;
  68700. this.depthOfField = null;
  68701. };
  68702. /**
  68703. * Dispose of the pipeline and stop all post processes
  68704. */
  68705. DefaultRenderingPipeline.prototype.dispose = function () {
  68706. this._disposePostProcesses();
  68707. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  68708. _super.prototype.dispose.call(this);
  68709. };
  68710. /**
  68711. * Serialize the rendering pipeline (Used when exporting)
  68712. * @returns the serialized object
  68713. */
  68714. DefaultRenderingPipeline.prototype.serialize = function () {
  68715. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  68716. serializationObject.customType = "DefaultRenderingPipeline";
  68717. return serializationObject;
  68718. };
  68719. /**
  68720. * Parse the serialized pipeline
  68721. * @param source Source pipeline.
  68722. * @param scene The scene to load the pipeline to.
  68723. * @param rootUrl The URL of the serialized pipeline.
  68724. * @returns An instantiated pipeline from the serialized object.
  68725. */
  68726. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  68727. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  68728. };
  68729. __decorate([
  68730. BABYLON.serialize()
  68731. ], DefaultRenderingPipeline.prototype, "bloomKernel", void 0);
  68732. __decorate([
  68733. BABYLON.serialize()
  68734. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  68735. __decorate([
  68736. BABYLON.serialize()
  68737. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  68738. __decorate([
  68739. BABYLON.serialize()
  68740. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  68741. __decorate([
  68742. BABYLON.serialize()
  68743. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  68744. __decorate([
  68745. BABYLON.serialize()
  68746. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  68747. __decorate([
  68748. BABYLON.serialize()
  68749. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  68750. __decorate([
  68751. BABYLON.serialize()
  68752. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  68753. __decorate([
  68754. BABYLON.serialize()
  68755. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  68756. __decorate([
  68757. BABYLON.serialize()
  68758. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  68759. return DefaultRenderingPipeline;
  68760. }(BABYLON.PostProcessRenderPipeline));
  68761. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  68762. })(BABYLON || (BABYLON = {}));
  68763. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  68764. var BABYLON;
  68765. (function (BABYLON) {
  68766. /**
  68767. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  68768. */
  68769. var GeometryBufferRenderer = /** @class */ (function () {
  68770. /**
  68771. * Creates a new G Buffer for the scene. @see GeometryBufferRenderer
  68772. * @param scene The scene the buffer belongs to
  68773. * @param ratio How big is the buffer related to the main canvas.
  68774. */
  68775. function GeometryBufferRenderer(scene, ratio) {
  68776. if (ratio === void 0) { ratio = 1; }
  68777. this._enablePosition = false;
  68778. this._scene = scene;
  68779. this._ratio = ratio;
  68780. // Render target
  68781. this._createRenderTargets();
  68782. }
  68783. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  68784. /**
  68785. * Set the render list (meshes to be rendered) used in the G buffer.
  68786. */
  68787. set: function (meshes) {
  68788. this._multiRenderTarget.renderList = meshes;
  68789. },
  68790. enumerable: true,
  68791. configurable: true
  68792. });
  68793. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  68794. /**
  68795. * Gets wether or not G buffer are supported by the running hardware.
  68796. * This requires draw buffer supports
  68797. */
  68798. get: function () {
  68799. return this._multiRenderTarget.isSupported;
  68800. },
  68801. enumerable: true,
  68802. configurable: true
  68803. });
  68804. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  68805. /**
  68806. * Gets wether or not position are enabled for the G buffer.
  68807. */
  68808. get: function () {
  68809. return this._enablePosition;
  68810. },
  68811. /**
  68812. * Sets wether or not position are enabled for the G buffer.
  68813. */
  68814. set: function (enable) {
  68815. this._enablePosition = enable;
  68816. this.dispose();
  68817. this._createRenderTargets();
  68818. },
  68819. enumerable: true,
  68820. configurable: true
  68821. });
  68822. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  68823. /**
  68824. * Gets the scene associated with the buffer.
  68825. */
  68826. get: function () {
  68827. return this._scene;
  68828. },
  68829. enumerable: true,
  68830. configurable: true
  68831. });
  68832. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  68833. /**
  68834. * Gets the ratio used by the buffer during its creation.
  68835. * How big is the buffer related to the main canvas.
  68836. */
  68837. get: function () {
  68838. return this._ratio;
  68839. },
  68840. enumerable: true,
  68841. configurable: true
  68842. });
  68843. /**
  68844. * Checks wether everything is ready to render a submesh to the G buffer.
  68845. * @param subMesh the submesh to check readiness for
  68846. * @param useInstances is the mesh drawn using instance or not
  68847. * @returns true if ready otherwise false
  68848. */
  68849. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  68850. var material = subMesh.getMaterial();
  68851. if (material && material.disableDepthWrite) {
  68852. return false;
  68853. }
  68854. var defines = [];
  68855. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  68856. var mesh = subMesh.getMesh();
  68857. // Alpha test
  68858. if (material && material.needAlphaTesting()) {
  68859. defines.push("#define ALPHATEST");
  68860. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  68861. attribs.push(BABYLON.VertexBuffer.UVKind);
  68862. defines.push("#define UV1");
  68863. }
  68864. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  68865. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  68866. defines.push("#define UV2");
  68867. }
  68868. }
  68869. // Buffers
  68870. if (this._enablePosition) {
  68871. defines.push("#define POSITION");
  68872. }
  68873. // Bones
  68874. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  68875. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  68876. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  68877. if (mesh.numBoneInfluencers > 4) {
  68878. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  68879. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  68880. }
  68881. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  68882. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  68883. }
  68884. else {
  68885. defines.push("#define NUM_BONE_INFLUENCERS 0");
  68886. }
  68887. // Instances
  68888. if (useInstances) {
  68889. defines.push("#define INSTANCES");
  68890. attribs.push("world0");
  68891. attribs.push("world1");
  68892. attribs.push("world2");
  68893. attribs.push("world3");
  68894. }
  68895. // Get correct effect
  68896. var join = defines.join("\n");
  68897. if (this._cachedDefines !== join) {
  68898. this._cachedDefines = join;
  68899. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  68900. }
  68901. return this._effect.isReady();
  68902. };
  68903. /**
  68904. * Gets the current underlying G Buffer.
  68905. * @returns the buffer
  68906. */
  68907. GeometryBufferRenderer.prototype.getGBuffer = function () {
  68908. return this._multiRenderTarget;
  68909. };
  68910. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  68911. /**
  68912. * Gets the number of samples used to render the buffer (anti aliasing).
  68913. */
  68914. get: function () {
  68915. return this._multiRenderTarget.samples;
  68916. },
  68917. /**
  68918. * Sets the number of samples used to render the buffer (anti aliasing).
  68919. */
  68920. set: function (value) {
  68921. this._multiRenderTarget.samples = value;
  68922. },
  68923. enumerable: true,
  68924. configurable: true
  68925. });
  68926. /**
  68927. * Disposes the renderer and frees up associated resources.
  68928. */
  68929. GeometryBufferRenderer.prototype.dispose = function () {
  68930. this.getGBuffer().dispose();
  68931. };
  68932. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  68933. var _this = this;
  68934. var engine = this._scene.getEngine();
  68935. var count = this._enablePosition ? 3 : 2;
  68936. this._multiRenderTarget = new BABYLON.MultiRenderTarget("gBuffer", { width: engine.getRenderWidth() * this._ratio, height: engine.getRenderHeight() * this._ratio }, count, this._scene, { generateMipMaps: false, generateDepthTexture: true, defaultType: BABYLON.Engine.TEXTURETYPE_FLOAT });
  68937. if (!this.isSupported) {
  68938. return;
  68939. }
  68940. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68941. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68942. this._multiRenderTarget.refreshRate = 1;
  68943. this._multiRenderTarget.renderParticles = false;
  68944. this._multiRenderTarget.renderList = null;
  68945. // set default depth value to 1.0 (far away)
  68946. this._multiRenderTarget.onClearObservable.add(function (engine) {
  68947. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  68948. });
  68949. // Custom render function
  68950. var renderSubMesh = function (subMesh) {
  68951. var mesh = subMesh.getRenderingMesh();
  68952. var scene = _this._scene;
  68953. var engine = scene.getEngine();
  68954. var material = subMesh.getMaterial();
  68955. if (!material) {
  68956. return;
  68957. }
  68958. // Culling
  68959. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  68960. // Managing instances
  68961. var batch = mesh._getInstancesRenderList(subMesh._id);
  68962. if (batch.mustReturn) {
  68963. return;
  68964. }
  68965. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  68966. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  68967. engine.enableEffect(_this._effect);
  68968. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  68969. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  68970. _this._effect.setMatrix("view", scene.getViewMatrix());
  68971. // Alpha test
  68972. if (material && material.needAlphaTesting()) {
  68973. var alphaTexture = material.getAlphaTestTexture();
  68974. if (alphaTexture) {
  68975. _this._effect.setTexture("diffuseSampler", alphaTexture);
  68976. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  68977. }
  68978. }
  68979. // Bones
  68980. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  68981. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  68982. }
  68983. // Draw
  68984. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  68985. }
  68986. };
  68987. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  68988. var index;
  68989. if (depthOnlySubMeshes.length) {
  68990. engine.setColorWrite(false);
  68991. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  68992. renderSubMesh(depthOnlySubMeshes.data[index]);
  68993. }
  68994. engine.setColorWrite(true);
  68995. }
  68996. for (index = 0; index < opaqueSubMeshes.length; index++) {
  68997. renderSubMesh(opaqueSubMeshes.data[index]);
  68998. }
  68999. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  69000. renderSubMesh(alphaTestSubMeshes.data[index]);
  69001. }
  69002. };
  69003. };
  69004. return GeometryBufferRenderer;
  69005. }());
  69006. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  69007. })(BABYLON || (BABYLON = {}));
  69008. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  69009. var BABYLON;
  69010. (function (BABYLON) {
  69011. var RefractionPostProcess = /** @class */ (function (_super) {
  69012. __extends(RefractionPostProcess, _super);
  69013. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  69014. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  69015. _this.color = color;
  69016. _this.depth = depth;
  69017. _this.colorLevel = colorLevel;
  69018. _this._ownRefractionTexture = true;
  69019. _this.onActivateObservable.add(function (cam) {
  69020. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  69021. });
  69022. _this.onApplyObservable.add(function (effect) {
  69023. effect.setColor3("baseColor", _this.color);
  69024. effect.setFloat("depth", _this.depth);
  69025. effect.setFloat("colorLevel", _this.colorLevel);
  69026. effect.setTexture("refractionSampler", _this._refTexture);
  69027. });
  69028. return _this;
  69029. }
  69030. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  69031. /**
  69032. * Gets or sets the refraction texture
  69033. * Please note that you are responsible for disposing the texture if you set it manually
  69034. */
  69035. get: function () {
  69036. return this._refTexture;
  69037. },
  69038. set: function (value) {
  69039. if (this._refTexture && this._ownRefractionTexture) {
  69040. this._refTexture.dispose();
  69041. }
  69042. this._refTexture = value;
  69043. this._ownRefractionTexture = false;
  69044. },
  69045. enumerable: true,
  69046. configurable: true
  69047. });
  69048. // Methods
  69049. RefractionPostProcess.prototype.dispose = function (camera) {
  69050. if (this._refTexture && this._ownRefractionTexture) {
  69051. this._refTexture.dispose();
  69052. this._refTexture = null;
  69053. }
  69054. _super.prototype.dispose.call(this, camera);
  69055. };
  69056. return RefractionPostProcess;
  69057. }(BABYLON.PostProcess));
  69058. BABYLON.RefractionPostProcess = RefractionPostProcess;
  69059. })(BABYLON || (BABYLON = {}));
  69060. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  69061. var BABYLON;
  69062. (function (BABYLON) {
  69063. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  69064. __extends(BlackAndWhitePostProcess, _super);
  69065. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  69066. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  69067. _this.degree = 1;
  69068. _this.onApplyObservable.add(function (effect) {
  69069. effect.setFloat("degree", _this.degree);
  69070. });
  69071. return _this;
  69072. }
  69073. return BlackAndWhitePostProcess;
  69074. }(BABYLON.PostProcess));
  69075. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  69076. })(BABYLON || (BABYLON = {}));
  69077. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  69078. var BABYLON;
  69079. (function (BABYLON) {
  69080. var ConvolutionPostProcess = /** @class */ (function (_super) {
  69081. __extends(ConvolutionPostProcess, _super);
  69082. function ConvolutionPostProcess(name, kernel, options, camera, samplingMode, engine, reusable) {
  69083. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable) || this;
  69084. _this.kernel = kernel;
  69085. _this.onApply = function (effect) {
  69086. effect.setFloat2("screenSize", _this.width, _this.height);
  69087. effect.setArray("kernel", _this.kernel);
  69088. };
  69089. return _this;
  69090. }
  69091. // Statics
  69092. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  69093. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  69094. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  69095. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  69096. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  69097. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  69098. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  69099. return ConvolutionPostProcess;
  69100. }(BABYLON.PostProcess));
  69101. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  69102. })(BABYLON || (BABYLON = {}));
  69103. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  69104. var BABYLON;
  69105. (function (BABYLON) {
  69106. var FilterPostProcess = /** @class */ (function (_super) {
  69107. __extends(FilterPostProcess, _super);
  69108. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  69109. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  69110. _this.kernelMatrix = kernelMatrix;
  69111. _this.onApply = function (effect) {
  69112. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  69113. };
  69114. return _this;
  69115. }
  69116. return FilterPostProcess;
  69117. }(BABYLON.PostProcess));
  69118. BABYLON.FilterPostProcess = FilterPostProcess;
  69119. })(BABYLON || (BABYLON = {}));
  69120. //# sourceMappingURL=babylon.filterPostProcess.js.map
  69121. var BABYLON;
  69122. (function (BABYLON) {
  69123. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  69124. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  69125. __extends(VolumetricLightScatteringPostProcess, _super);
  69126. /**
  69127. * @constructor
  69128. * @param {string} name - The post-process name
  69129. * @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)
  69130. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  69131. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  69132. * @param {number} samples - The post-process quality, default 100
  69133. * @param {number} samplingMode - The post-process filtering mode
  69134. * @param {BABYLON.Engine} engine - The babylon engine
  69135. * @param {boolean} reusable - If the post-process is reusable
  69136. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  69137. */
  69138. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  69139. if (samples === void 0) { samples = 100; }
  69140. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  69141. 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;
  69142. _this._screenCoordinates = BABYLON.Vector2.Zero();
  69143. /**
  69144. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  69145. * @type {Vector3}
  69146. */
  69147. _this.customMeshPosition = BABYLON.Vector3.Zero();
  69148. /**
  69149. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  69150. * @type {boolean}
  69151. */
  69152. _this.useCustomMeshPosition = false;
  69153. /**
  69154. * If the post-process should inverse the light scattering direction
  69155. * @type {boolean}
  69156. */
  69157. _this.invert = true;
  69158. /**
  69159. * Array containing the excluded meshes not rendered in the internal pass
  69160. */
  69161. _this.excludedMeshes = new Array();
  69162. /**
  69163. * Controls the overall intensity of the post-process
  69164. * @type {number}
  69165. */
  69166. _this.exposure = 0.3;
  69167. /**
  69168. * Dissipates each sample's contribution in range [0, 1]
  69169. * @type {number}
  69170. */
  69171. _this.decay = 0.96815;
  69172. /**
  69173. * Controls the overall intensity of each sample
  69174. * @type {number}
  69175. */
  69176. _this.weight = 0.58767;
  69177. /**
  69178. * Controls the density of each sample
  69179. * @type {number}
  69180. */
  69181. _this.density = 0.926;
  69182. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  69183. engine = scene.getEngine();
  69184. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  69185. // Configure mesh
  69186. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  69187. // Configure
  69188. _this._createPass(scene, ratio.passRatio || ratio);
  69189. _this.onActivate = function (camera) {
  69190. if (!_this.isSupported) {
  69191. _this.dispose(camera);
  69192. }
  69193. _this.onActivate = null;
  69194. };
  69195. _this.onApplyObservable.add(function (effect) {
  69196. _this._updateMeshScreenCoordinates(scene);
  69197. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  69198. effect.setFloat("exposure", _this.exposure);
  69199. effect.setFloat("decay", _this.decay);
  69200. effect.setFloat("weight", _this.weight);
  69201. effect.setFloat("density", _this.density);
  69202. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  69203. });
  69204. return _this;
  69205. }
  69206. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  69207. get: function () {
  69208. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  69209. return false;
  69210. },
  69211. set: function (useDiffuseColor) {
  69212. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  69213. },
  69214. enumerable: true,
  69215. configurable: true
  69216. });
  69217. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  69218. return "VolumetricLightScatteringPostProcess";
  69219. };
  69220. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  69221. var mesh = subMesh.getMesh();
  69222. // Render this.mesh as default
  69223. if (mesh === this.mesh && mesh.material) {
  69224. return mesh.material.isReady(mesh);
  69225. }
  69226. var defines = [];
  69227. var attribs = [BABYLON.VertexBuffer.PositionKind];
  69228. var material = subMesh.getMaterial();
  69229. // Alpha test
  69230. if (material) {
  69231. if (material.needAlphaTesting()) {
  69232. defines.push("#define ALPHATEST");
  69233. }
  69234. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  69235. attribs.push(BABYLON.VertexBuffer.UVKind);
  69236. defines.push("#define UV1");
  69237. }
  69238. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  69239. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  69240. defines.push("#define UV2");
  69241. }
  69242. }
  69243. // Bones
  69244. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  69245. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  69246. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  69247. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  69248. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  69249. }
  69250. else {
  69251. defines.push("#define NUM_BONE_INFLUENCERS 0");
  69252. }
  69253. // Instances
  69254. if (useInstances) {
  69255. defines.push("#define INSTANCES");
  69256. attribs.push("world0");
  69257. attribs.push("world1");
  69258. attribs.push("world2");
  69259. attribs.push("world3");
  69260. }
  69261. // Get correct effect
  69262. var join = defines.join("\n");
  69263. if (this._cachedDefines !== join) {
  69264. this._cachedDefines = join;
  69265. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  69266. }
  69267. return this._volumetricLightScatteringPass.isReady();
  69268. };
  69269. /**
  69270. * Sets the new light position for light scattering effect
  69271. * @param {BABYLON.Vector3} The new custom light position
  69272. */
  69273. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  69274. this.customMeshPosition = position;
  69275. };
  69276. /**
  69277. * Returns the light position for light scattering effect
  69278. * @return {BABYLON.Vector3} The custom light position
  69279. */
  69280. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  69281. return this.customMeshPosition;
  69282. };
  69283. /**
  69284. * Disposes the internal assets and detaches the post-process from the camera
  69285. */
  69286. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  69287. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  69288. if (rttIndex !== -1) {
  69289. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  69290. }
  69291. this._volumetricLightScatteringRTT.dispose();
  69292. _super.prototype.dispose.call(this, camera);
  69293. };
  69294. /**
  69295. * Returns the render target texture used by the post-process
  69296. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  69297. */
  69298. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  69299. return this._volumetricLightScatteringRTT;
  69300. };
  69301. // Private methods
  69302. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  69303. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  69304. return true;
  69305. }
  69306. return false;
  69307. };
  69308. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  69309. var _this = this;
  69310. var engine = scene.getEngine();
  69311. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  69312. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69313. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69314. this._volumetricLightScatteringRTT.renderList = null;
  69315. this._volumetricLightScatteringRTT.renderParticles = false;
  69316. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  69317. var camera = this.getCamera();
  69318. if (camera) {
  69319. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  69320. }
  69321. else {
  69322. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  69323. }
  69324. // Custom render function for submeshes
  69325. var renderSubMesh = function (subMesh) {
  69326. var mesh = subMesh.getRenderingMesh();
  69327. if (_this._meshExcluded(mesh)) {
  69328. return;
  69329. }
  69330. var material = subMesh.getMaterial();
  69331. if (!material) {
  69332. return;
  69333. }
  69334. var scene = mesh.getScene();
  69335. var engine = scene.getEngine();
  69336. // Culling
  69337. engine.setState(material.backFaceCulling);
  69338. // Managing instances
  69339. var batch = mesh._getInstancesRenderList(subMesh._id);
  69340. if (batch.mustReturn) {
  69341. return;
  69342. }
  69343. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  69344. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  69345. var effect = _this._volumetricLightScatteringPass;
  69346. if (mesh === _this.mesh) {
  69347. if (subMesh.effect) {
  69348. effect = subMesh.effect;
  69349. }
  69350. else {
  69351. effect = material.getEffect();
  69352. }
  69353. }
  69354. engine.enableEffect(effect);
  69355. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  69356. if (mesh === _this.mesh) {
  69357. material.bind(mesh.getWorldMatrix(), mesh);
  69358. }
  69359. else {
  69360. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  69361. // Alpha test
  69362. if (material && material.needAlphaTesting()) {
  69363. var alphaTexture = material.getAlphaTestTexture();
  69364. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  69365. if (alphaTexture) {
  69366. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  69367. }
  69368. }
  69369. // Bones
  69370. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  69371. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  69372. }
  69373. }
  69374. // Draw
  69375. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  69376. }
  69377. };
  69378. // Render target texture callbacks
  69379. var savedSceneClearColor;
  69380. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  69381. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  69382. savedSceneClearColor = scene.clearColor;
  69383. scene.clearColor = sceneClearColor;
  69384. });
  69385. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  69386. scene.clearColor = savedSceneClearColor;
  69387. });
  69388. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  69389. var engine = scene.getEngine();
  69390. var index;
  69391. if (depthOnlySubMeshes.length) {
  69392. engine.setColorWrite(false);
  69393. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  69394. renderSubMesh(depthOnlySubMeshes.data[index]);
  69395. }
  69396. engine.setColorWrite(true);
  69397. }
  69398. for (index = 0; index < opaqueSubMeshes.length; index++) {
  69399. renderSubMesh(opaqueSubMeshes.data[index]);
  69400. }
  69401. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  69402. renderSubMesh(alphaTestSubMeshes.data[index]);
  69403. }
  69404. if (transparentSubMeshes.length) {
  69405. // Sort sub meshes
  69406. for (index = 0; index < transparentSubMeshes.length; index++) {
  69407. var submesh = transparentSubMeshes.data[index];
  69408. var boundingInfo = submesh.getBoundingInfo();
  69409. if (boundingInfo && scene.activeCamera) {
  69410. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  69411. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  69412. }
  69413. }
  69414. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  69415. sortedArray.sort(function (a, b) {
  69416. // Alpha index first
  69417. if (a._alphaIndex > b._alphaIndex) {
  69418. return 1;
  69419. }
  69420. if (a._alphaIndex < b._alphaIndex) {
  69421. return -1;
  69422. }
  69423. // Then distance to camera
  69424. if (a._distanceToCamera < b._distanceToCamera) {
  69425. return 1;
  69426. }
  69427. if (a._distanceToCamera > b._distanceToCamera) {
  69428. return -1;
  69429. }
  69430. return 0;
  69431. });
  69432. // Render sub meshes
  69433. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  69434. for (index = 0; index < sortedArray.length; index++) {
  69435. renderSubMesh(sortedArray[index]);
  69436. }
  69437. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  69438. }
  69439. };
  69440. };
  69441. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  69442. var transform = scene.getTransformMatrix();
  69443. var meshPosition;
  69444. if (this.useCustomMeshPosition) {
  69445. meshPosition = this.customMeshPosition;
  69446. }
  69447. else if (this.attachedNode) {
  69448. meshPosition = this.attachedNode.position;
  69449. }
  69450. else {
  69451. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  69452. }
  69453. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  69454. this._screenCoordinates.x = pos.x / this._viewPort.width;
  69455. this._screenCoordinates.y = pos.y / this._viewPort.height;
  69456. if (this.invert)
  69457. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  69458. };
  69459. // Static methods
  69460. /**
  69461. * Creates a default mesh for the Volumeric Light Scattering post-process
  69462. * @param {string} The mesh name
  69463. * @param {BABYLON.Scene} The scene where to create the mesh
  69464. * @return {BABYLON.Mesh} the default mesh
  69465. */
  69466. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  69467. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  69468. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  69469. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  69470. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  69471. mesh.material = material;
  69472. return mesh;
  69473. };
  69474. __decorate([
  69475. BABYLON.serializeAsVector3()
  69476. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  69477. __decorate([
  69478. BABYLON.serialize()
  69479. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  69480. __decorate([
  69481. BABYLON.serialize()
  69482. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  69483. __decorate([
  69484. BABYLON.serializeAsMeshReference()
  69485. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  69486. __decorate([
  69487. BABYLON.serialize()
  69488. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  69489. __decorate([
  69490. BABYLON.serialize()
  69491. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  69492. __decorate([
  69493. BABYLON.serialize()
  69494. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  69495. __decorate([
  69496. BABYLON.serialize()
  69497. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  69498. __decorate([
  69499. BABYLON.serialize()
  69500. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  69501. return VolumetricLightScatteringPostProcess;
  69502. }(BABYLON.PostProcess));
  69503. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  69504. })(BABYLON || (BABYLON = {}));
  69505. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  69506. //
  69507. // This post-process allows the modification of rendered colors by using
  69508. // a 'look-up table' (LUT). This effect is also called Color Grading.
  69509. //
  69510. // The object needs to be provided an url to a texture containing the color
  69511. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  69512. // Use an image editing software to tweak the LUT to match your needs.
  69513. //
  69514. // For an example of a color LUT, see here:
  69515. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  69516. // For explanations on color grading, see here:
  69517. // http://udn.epicgames.com/Three/ColorGrading.html
  69518. //
  69519. var BABYLON;
  69520. (function (BABYLON) {
  69521. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  69522. __extends(ColorCorrectionPostProcess, _super);
  69523. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  69524. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  69525. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  69526. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  69527. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69528. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69529. _this.onApply = function (effect) {
  69530. effect.setTexture("colorTable", _this._colorTableTexture);
  69531. };
  69532. return _this;
  69533. }
  69534. return ColorCorrectionPostProcess;
  69535. }(BABYLON.PostProcess));
  69536. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  69537. })(BABYLON || (BABYLON = {}));
  69538. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  69539. var BABYLON;
  69540. (function (BABYLON) {
  69541. var TonemappingOperator;
  69542. (function (TonemappingOperator) {
  69543. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  69544. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  69545. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  69546. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  69547. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  69548. ;
  69549. var TonemapPostProcess = /** @class */ (function (_super) {
  69550. __extends(TonemapPostProcess, _super);
  69551. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  69552. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  69553. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69554. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  69555. _this._operator = _operator;
  69556. _this.exposureAdjustment = exposureAdjustment;
  69557. var defines = "#define ";
  69558. if (_this._operator === TonemappingOperator.Hable)
  69559. defines += "HABLE_TONEMAPPING";
  69560. else if (_this._operator === TonemappingOperator.Reinhard)
  69561. defines += "REINHARD_TONEMAPPING";
  69562. else if (_this._operator === TonemappingOperator.HejiDawson)
  69563. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  69564. else if (_this._operator === TonemappingOperator.Photographic)
  69565. defines += "PHOTOGRAPHIC_TONEMAPPING";
  69566. //sadly a second call to create the effect.
  69567. _this.updateEffect(defines);
  69568. _this.onApply = function (effect) {
  69569. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  69570. };
  69571. return _this;
  69572. }
  69573. return TonemapPostProcess;
  69574. }(BABYLON.PostProcess));
  69575. BABYLON.TonemapPostProcess = TonemapPostProcess;
  69576. })(BABYLON || (BABYLON = {}));
  69577. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  69578. var BABYLON;
  69579. (function (BABYLON) {
  69580. var DisplayPassPostProcess = /** @class */ (function (_super) {
  69581. __extends(DisplayPassPostProcess, _super);
  69582. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  69583. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  69584. }
  69585. return DisplayPassPostProcess;
  69586. }(BABYLON.PostProcess));
  69587. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  69588. })(BABYLON || (BABYLON = {}));
  69589. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  69590. var BABYLON;
  69591. (function (BABYLON) {
  69592. var HighlightsPostProcess = /** @class */ (function (_super) {
  69593. __extends(HighlightsPostProcess, _super);
  69594. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  69595. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69596. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  69597. }
  69598. return HighlightsPostProcess;
  69599. }(BABYLON.PostProcess));
  69600. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  69601. })(BABYLON || (BABYLON = {}));
  69602. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  69603. var BABYLON;
  69604. (function (BABYLON) {
  69605. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  69606. __extends(ImageProcessingPostProcess, _super);
  69607. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  69608. if (camera === void 0) { camera = null; }
  69609. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69610. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  69611. _this._fromLinearSpace = true;
  69612. /**
  69613. * Defines cache preventing GC.
  69614. */
  69615. _this._defines = {
  69616. IMAGEPROCESSING: false,
  69617. VIGNETTE: false,
  69618. VIGNETTEBLENDMODEMULTIPLY: false,
  69619. VIGNETTEBLENDMODEOPAQUE: false,
  69620. TONEMAPPING: false,
  69621. CONTRAST: false,
  69622. COLORCURVES: false,
  69623. COLORGRADING: false,
  69624. COLORGRADING3D: false,
  69625. FROMLINEARSPACE: false,
  69626. SAMPLER3DGREENDEPTH: false,
  69627. SAMPLER3DBGRMAP: false,
  69628. IMAGEPROCESSINGPOSTPROCESS: false,
  69629. EXPOSURE: false,
  69630. };
  69631. // Setup the configuration as forced by the constructor. This would then not force the
  69632. // scene materials output in linear space and let untouched the default forward pass.
  69633. if (imageProcessingConfiguration) {
  69634. imageProcessingConfiguration.applyByPostProcess = true;
  69635. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  69636. // This will cause the shader to be compiled
  69637. _this.fromLinearSpace = false;
  69638. }
  69639. else {
  69640. _this._attachImageProcessingConfiguration(null, true);
  69641. _this.imageProcessingConfiguration.applyByPostProcess = true;
  69642. }
  69643. _this.onApply = function (effect) {
  69644. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  69645. };
  69646. return _this;
  69647. }
  69648. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  69649. /**
  69650. * Gets the image processing configuration used either in this material.
  69651. */
  69652. get: function () {
  69653. return this._imageProcessingConfiguration;
  69654. },
  69655. /**
  69656. * Sets the Default image processing configuration used either in the this material.
  69657. *
  69658. * If sets to null, the scene one is in use.
  69659. */
  69660. set: function (value) {
  69661. this._attachImageProcessingConfiguration(value);
  69662. },
  69663. enumerable: true,
  69664. configurable: true
  69665. });
  69666. /**
  69667. * Attaches a new image processing configuration to the PBR Material.
  69668. * @param configuration
  69669. */
  69670. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  69671. var _this = this;
  69672. if (doNotBuild === void 0) { doNotBuild = false; }
  69673. if (configuration === this._imageProcessingConfiguration) {
  69674. return;
  69675. }
  69676. // Detaches observer.
  69677. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  69678. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  69679. }
  69680. // Pick the scene configuration if needed.
  69681. if (!configuration) {
  69682. var scene = null;
  69683. var engine = this.getEngine();
  69684. var camera = this.getCamera();
  69685. if (camera) {
  69686. scene = camera.getScene();
  69687. }
  69688. else if (engine && engine.scenes) {
  69689. var scenes = engine.scenes;
  69690. scene = scenes[scenes.length - 1];
  69691. }
  69692. else {
  69693. scene = BABYLON.Engine.LastCreatedScene;
  69694. }
  69695. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  69696. }
  69697. else {
  69698. this._imageProcessingConfiguration = configuration;
  69699. }
  69700. // Attaches observer.
  69701. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  69702. _this._updateParameters();
  69703. });
  69704. // Ensure the effect will be rebuilt.
  69705. if (!doNotBuild) {
  69706. this._updateParameters();
  69707. }
  69708. };
  69709. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  69710. /**
  69711. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  69712. */
  69713. get: function () {
  69714. return this.imageProcessingConfiguration.colorCurves;
  69715. },
  69716. /**
  69717. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  69718. */
  69719. set: function (value) {
  69720. this.imageProcessingConfiguration.colorCurves = value;
  69721. },
  69722. enumerable: true,
  69723. configurable: true
  69724. });
  69725. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  69726. /**
  69727. * Gets wether the color curves effect is enabled.
  69728. */
  69729. get: function () {
  69730. return this.imageProcessingConfiguration.colorCurvesEnabled;
  69731. },
  69732. /**
  69733. * Sets wether the color curves effect is enabled.
  69734. */
  69735. set: function (value) {
  69736. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  69737. },
  69738. enumerable: true,
  69739. configurable: true
  69740. });
  69741. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  69742. /**
  69743. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  69744. */
  69745. get: function () {
  69746. return this.imageProcessingConfiguration.colorGradingTexture;
  69747. },
  69748. /**
  69749. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  69750. */
  69751. set: function (value) {
  69752. this.imageProcessingConfiguration.colorGradingTexture = value;
  69753. },
  69754. enumerable: true,
  69755. configurable: true
  69756. });
  69757. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  69758. /**
  69759. * Gets wether the color grading effect is enabled.
  69760. */
  69761. get: function () {
  69762. return this.imageProcessingConfiguration.colorGradingEnabled;
  69763. },
  69764. /**
  69765. * Gets wether the color grading effect is enabled.
  69766. */
  69767. set: function (value) {
  69768. this.imageProcessingConfiguration.colorGradingEnabled = value;
  69769. },
  69770. enumerable: true,
  69771. configurable: true
  69772. });
  69773. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  69774. /**
  69775. * Gets exposure used in the effect.
  69776. */
  69777. get: function () {
  69778. return this.imageProcessingConfiguration.exposure;
  69779. },
  69780. /**
  69781. * Sets exposure used in the effect.
  69782. */
  69783. set: function (value) {
  69784. this.imageProcessingConfiguration.exposure = value;
  69785. },
  69786. enumerable: true,
  69787. configurable: true
  69788. });
  69789. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  69790. /**
  69791. * Gets wether tonemapping is enabled or not.
  69792. */
  69793. get: function () {
  69794. return this._imageProcessingConfiguration.toneMappingEnabled;
  69795. },
  69796. /**
  69797. * Sets wether tonemapping is enabled or not
  69798. */
  69799. set: function (value) {
  69800. this._imageProcessingConfiguration.toneMappingEnabled = value;
  69801. },
  69802. enumerable: true,
  69803. configurable: true
  69804. });
  69805. ;
  69806. ;
  69807. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  69808. /**
  69809. * Gets contrast used in the effect.
  69810. */
  69811. get: function () {
  69812. return this.imageProcessingConfiguration.contrast;
  69813. },
  69814. /**
  69815. * Sets contrast used in the effect.
  69816. */
  69817. set: function (value) {
  69818. this.imageProcessingConfiguration.contrast = value;
  69819. },
  69820. enumerable: true,
  69821. configurable: true
  69822. });
  69823. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  69824. /**
  69825. * Gets Vignette stretch size.
  69826. */
  69827. get: function () {
  69828. return this.imageProcessingConfiguration.vignetteStretch;
  69829. },
  69830. /**
  69831. * Sets Vignette stretch size.
  69832. */
  69833. set: function (value) {
  69834. this.imageProcessingConfiguration.vignetteStretch = value;
  69835. },
  69836. enumerable: true,
  69837. configurable: true
  69838. });
  69839. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  69840. /**
  69841. * Gets Vignette centre X Offset.
  69842. */
  69843. get: function () {
  69844. return this.imageProcessingConfiguration.vignetteCentreX;
  69845. },
  69846. /**
  69847. * Sets Vignette centre X Offset.
  69848. */
  69849. set: function (value) {
  69850. this.imageProcessingConfiguration.vignetteCentreX = value;
  69851. },
  69852. enumerable: true,
  69853. configurable: true
  69854. });
  69855. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  69856. /**
  69857. * Gets Vignette centre Y Offset.
  69858. */
  69859. get: function () {
  69860. return this.imageProcessingConfiguration.vignetteCentreY;
  69861. },
  69862. /**
  69863. * Sets Vignette centre Y Offset.
  69864. */
  69865. set: function (value) {
  69866. this.imageProcessingConfiguration.vignetteCentreY = value;
  69867. },
  69868. enumerable: true,
  69869. configurable: true
  69870. });
  69871. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  69872. /**
  69873. * Gets Vignette weight or intensity of the vignette effect.
  69874. */
  69875. get: function () {
  69876. return this.imageProcessingConfiguration.vignetteWeight;
  69877. },
  69878. /**
  69879. * Sets Vignette weight or intensity of the vignette effect.
  69880. */
  69881. set: function (value) {
  69882. this.imageProcessingConfiguration.vignetteWeight = value;
  69883. },
  69884. enumerable: true,
  69885. configurable: true
  69886. });
  69887. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  69888. /**
  69889. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  69890. * if vignetteEnabled is set to true.
  69891. */
  69892. get: function () {
  69893. return this.imageProcessingConfiguration.vignetteColor;
  69894. },
  69895. /**
  69896. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  69897. * if vignetteEnabled is set to true.
  69898. */
  69899. set: function (value) {
  69900. this.imageProcessingConfiguration.vignetteColor = value;
  69901. },
  69902. enumerable: true,
  69903. configurable: true
  69904. });
  69905. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  69906. /**
  69907. * Gets Camera field of view used by the Vignette effect.
  69908. */
  69909. get: function () {
  69910. return this.imageProcessingConfiguration.vignetteCameraFov;
  69911. },
  69912. /**
  69913. * Sets Camera field of view used by the Vignette effect.
  69914. */
  69915. set: function (value) {
  69916. this.imageProcessingConfiguration.vignetteCameraFov = value;
  69917. },
  69918. enumerable: true,
  69919. configurable: true
  69920. });
  69921. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  69922. /**
  69923. * Gets the vignette blend mode allowing different kind of effect.
  69924. */
  69925. get: function () {
  69926. return this.imageProcessingConfiguration.vignetteBlendMode;
  69927. },
  69928. /**
  69929. * Sets the vignette blend mode allowing different kind of effect.
  69930. */
  69931. set: function (value) {
  69932. this.imageProcessingConfiguration.vignetteBlendMode = value;
  69933. },
  69934. enumerable: true,
  69935. configurable: true
  69936. });
  69937. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  69938. /**
  69939. * Gets wether the vignette effect is enabled.
  69940. */
  69941. get: function () {
  69942. return this.imageProcessingConfiguration.vignetteEnabled;
  69943. },
  69944. /**
  69945. * Sets wether the vignette effect is enabled.
  69946. */
  69947. set: function (value) {
  69948. this.imageProcessingConfiguration.vignetteEnabled = value;
  69949. },
  69950. enumerable: true,
  69951. configurable: true
  69952. });
  69953. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  69954. /**
  69955. * Gets wether the input of the processing is in Gamma or Linear Space.
  69956. */
  69957. get: function () {
  69958. return this._fromLinearSpace;
  69959. },
  69960. /**
  69961. * Sets wether the input of the processing is in Gamma or Linear Space.
  69962. */
  69963. set: function (value) {
  69964. if (this._fromLinearSpace === value) {
  69965. return;
  69966. }
  69967. this._fromLinearSpace = value;
  69968. this._updateParameters();
  69969. },
  69970. enumerable: true,
  69971. configurable: true
  69972. });
  69973. ImageProcessingPostProcess.prototype.getClassName = function () {
  69974. return "ImageProcessingPostProcess";
  69975. };
  69976. ImageProcessingPostProcess.prototype._updateParameters = function () {
  69977. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  69978. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  69979. var defines = "";
  69980. for (var define in this._defines) {
  69981. if (this._defines[define]) {
  69982. defines += "#define " + define + ";\r\n";
  69983. }
  69984. }
  69985. var samplers = ["textureSampler"];
  69986. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  69987. var uniforms = ["scale"];
  69988. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  69989. this.updateEffect(defines, uniforms, samplers);
  69990. };
  69991. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  69992. _super.prototype.dispose.call(this, camera);
  69993. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  69994. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  69995. }
  69996. this.imageProcessingConfiguration.applyByPostProcess = false;
  69997. };
  69998. __decorate([
  69999. BABYLON.serialize()
  70000. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  70001. return ImageProcessingPostProcess;
  70002. }(BABYLON.PostProcess));
  70003. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  70004. })(BABYLON || (BABYLON = {}));
  70005. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  70006. var BABYLON;
  70007. (function (BABYLON) {
  70008. /**
  70009. * The Blur Post Process which blurs an image based on a kernel and direction.
  70010. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  70011. */
  70012. var BlurPostProcess = /** @class */ (function (_super) {
  70013. __extends(BlurPostProcess, _super);
  70014. /**
  70015. * Creates a new instance of @see BlurPostProcess
  70016. * @param name The name of the effect.
  70017. * @param direction The direction in which to blur the image.
  70018. * @param kernel The size of the kernel to be used when computing the blur. eg. Size of 3 will blur the center pixel by 2 pixels surrounding it.
  70019. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  70020. * @param camera The camera to apply the render pass to.
  70021. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  70022. * @param engine The engine which the post process will be applied. (default: current engine)
  70023. * @param reusable If the post process can be reused on the same frame. (default: false)
  70024. * @param textureType Type of textures used when performing the post process. (default: 0)
  70025. */
  70026. function BlurPostProcess(name, /** The direction in which to blur the image. */ direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines) {
  70027. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  70028. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70029. if (defines === void 0) { defines = ""; }
  70030. var _this = _super.call(this, name, "kernelBlur", ["delta", "direction", "cameraMinMaxZ"], ["circleOfConfusionSampler"], options, camera, samplingMode, engine, reusable, null, textureType, "kernelBlur", { varyingCount: 0, depCount: 0 }, true) || this;
  70031. _this.direction = direction;
  70032. _this._packedFloat = false;
  70033. _this._staticDefines = "";
  70034. _this._staticDefines = defines;
  70035. _this.onApplyObservable.add(function (effect) {
  70036. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  70037. });
  70038. _this.kernel = kernel;
  70039. return _this;
  70040. }
  70041. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  70042. /**
  70043. * Gets the length in pixels of the blur sample region
  70044. */
  70045. get: function () {
  70046. return this._idealKernel;
  70047. },
  70048. /**
  70049. * Sets the length in pixels of the blur sample region
  70050. */
  70051. set: function (v) {
  70052. if (this._idealKernel === v) {
  70053. return;
  70054. }
  70055. v = Math.max(v, 1);
  70056. this._idealKernel = v;
  70057. this._kernel = this._nearestBestKernel(v);
  70058. this._updateParameters();
  70059. },
  70060. enumerable: true,
  70061. configurable: true
  70062. });
  70063. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  70064. /**
  70065. * Gets wether or not the blur is unpacking/repacking floats
  70066. */
  70067. get: function () {
  70068. return this._packedFloat;
  70069. },
  70070. /**
  70071. * Sets wether or not the blur needs to unpack/repack floats
  70072. */
  70073. set: function (v) {
  70074. if (this._packedFloat === v) {
  70075. return;
  70076. }
  70077. this._packedFloat = v;
  70078. this._updateParameters();
  70079. },
  70080. enumerable: true,
  70081. configurable: true
  70082. });
  70083. BlurPostProcess.prototype._updateParameters = function () {
  70084. // Generate sampling offsets and weights
  70085. var N = this._kernel;
  70086. var centerIndex = (N - 1) / 2;
  70087. // Generate Gaussian sampling weights over kernel
  70088. var offsets = [];
  70089. var weights = [];
  70090. var totalWeight = 0;
  70091. for (var i = 0; i < N; i++) {
  70092. var u = i / (N - 1);
  70093. var w = this._gaussianWeight(u * 2.0 - 1);
  70094. offsets[i] = (i - centerIndex);
  70095. weights[i] = w;
  70096. totalWeight += w;
  70097. }
  70098. // Normalize weights
  70099. for (var i = 0; i < weights.length; i++) {
  70100. weights[i] /= totalWeight;
  70101. }
  70102. // Optimize: combine samples to take advantage of hardware linear sampling
  70103. // Walk from left to center, combining pairs (symmetrically)
  70104. var linearSamplingWeights = [];
  70105. var linearSamplingOffsets = [];
  70106. var linearSamplingMap = [];
  70107. for (var i = 0; i <= centerIndex; i += 2) {
  70108. var j = Math.min(i + 1, Math.floor(centerIndex));
  70109. var singleCenterSample = i === j;
  70110. if (singleCenterSample) {
  70111. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  70112. }
  70113. else {
  70114. var sharedCell = j === centerIndex;
  70115. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  70116. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  70117. if (offsetLinear === 0) {
  70118. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  70119. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  70120. }
  70121. else {
  70122. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  70123. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  70124. }
  70125. }
  70126. }
  70127. for (var i = 0; i < linearSamplingMap.length; i++) {
  70128. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  70129. linearSamplingWeights[i] = linearSamplingMap[i].w;
  70130. }
  70131. // Replace with optimized
  70132. offsets = linearSamplingOffsets;
  70133. weights = linearSamplingWeights;
  70134. // Generate shaders
  70135. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  70136. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  70137. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  70138. var defines = "";
  70139. defines += this._staticDefines;
  70140. for (var i = 0; i < varyingCount; i++) {
  70141. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  70142. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  70143. }
  70144. var depCount = 0;
  70145. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  70146. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  70147. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  70148. depCount++;
  70149. }
  70150. if (this.packedFloat) {
  70151. defines += "#define PACKEDFLOAT 1";
  70152. }
  70153. this.updateEffect(defines, null, null, {
  70154. varyingCount: varyingCount,
  70155. depCount: depCount
  70156. });
  70157. };
  70158. /**
  70159. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  70160. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  70161. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  70162. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  70163. * The gaps between physical kernels are compensated for in the weighting of the samples
  70164. * @param idealKernel Ideal blur kernel.
  70165. * @return Nearest best kernel.
  70166. */
  70167. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  70168. var v = Math.round(idealKernel);
  70169. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  70170. var k = _a[_i];
  70171. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  70172. return Math.max(k, 3);
  70173. }
  70174. }
  70175. return Math.max(v, 3);
  70176. };
  70177. /**
  70178. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  70179. * @param x The point on the Gaussian distribution to sample.
  70180. * @return the value of the Gaussian function at x.
  70181. */
  70182. BlurPostProcess.prototype._gaussianWeight = function (x) {
  70183. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  70184. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  70185. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  70186. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  70187. // truncated at around 1.3% of peak strength.
  70188. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  70189. var sigma = (1 / 3);
  70190. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  70191. var exponent = -((x * x) / (2.0 * sigma * sigma));
  70192. var weight = (1.0 / denominator) * Math.exp(exponent);
  70193. return weight;
  70194. };
  70195. /**
  70196. * Generates a string that can be used as a floating point number in GLSL.
  70197. * @param x Value to print.
  70198. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  70199. * @return GLSL float string.
  70200. */
  70201. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  70202. if (decimalFigures === void 0) { decimalFigures = 8; }
  70203. return x.toFixed(decimalFigures).replace(/0+$/, '');
  70204. };
  70205. return BlurPostProcess;
  70206. }(BABYLON.PostProcess));
  70207. BABYLON.BlurPostProcess = BlurPostProcess;
  70208. })(BABYLON || (BABYLON = {}));
  70209. //# sourceMappingURL=babylon.blurPostProcess.js.map
  70210. var BABYLON;
  70211. (function (BABYLON) {
  70212. /**
  70213. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  70214. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  70215. * based on samples that have a large difference in distance than the center pixel.
  70216. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  70217. */
  70218. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  70219. __extends(DepthOfFieldBlurPostProcess, _super);
  70220. /**
  70221. * Creates a new instance of @see CircleOfConfusionPostProcess
  70222. * @param name The name of the effect.
  70223. * @param scene The scene the effect belongs to.
  70224. * @param direction The direction the blur should be applied.
  70225. * @param kernel The size of the kernel used to blur.
  70226. * @param options The required width/height ratio to downsize to before computing the render pass.
  70227. * @param camera The camera to apply the render pass to.
  70228. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  70229. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  70230. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  70231. * @param engine The engine which the post process will be applied. (default: current engine)
  70232. * @param reusable If the post process can be reused on the same frame. (default: false)
  70233. * @param textureType Type of textures used when performing the post process. (default: 0)
  70234. */
  70235. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType) {
  70236. if (imageToBlur === void 0) { imageToBlur = null; }
  70237. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  70238. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70239. var _this = _super.call(this, name, direction, kernel, options, camera, samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, "#define DOF 1\r\n") || this;
  70240. _this.direction = direction;
  70241. _this.onApplyObservable.add(function (effect) {
  70242. if (imageToBlur != null) {
  70243. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  70244. }
  70245. effect.setTextureFromPostProcess("circleOfConfusionSampler", circleOfConfusion);
  70246. if (scene.activeCamera) {
  70247. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  70248. }
  70249. });
  70250. return _this;
  70251. }
  70252. return DepthOfFieldBlurPostProcess;
  70253. }(BABYLON.BlurPostProcess));
  70254. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  70255. })(BABYLON || (BABYLON = {}));
  70256. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  70257. var BABYLON;
  70258. (function (BABYLON) {
  70259. var Bone = /** @class */ (function (_super) {
  70260. __extends(Bone, _super);
  70261. function Bone(name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  70262. if (parentBone === void 0) { parentBone = null; }
  70263. if (localMatrix === void 0) { localMatrix = null; }
  70264. if (restPose === void 0) { restPose = null; }
  70265. if (baseMatrix === void 0) { baseMatrix = null; }
  70266. if (index === void 0) { index = null; }
  70267. var _this = _super.call(this, name, skeleton.getScene()) || this;
  70268. _this.name = name;
  70269. _this.children = new Array();
  70270. _this.animations = new Array();
  70271. // Set this value to map this bone to a different index in the transform matrices.
  70272. // Set this value to -1 to exclude the bone from the transform matrices.
  70273. _this._index = null;
  70274. _this._worldTransform = new BABYLON.Matrix();
  70275. _this._absoluteTransform = new BABYLON.Matrix();
  70276. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  70277. _this._scaleMatrix = BABYLON.Matrix.Identity();
  70278. _this._scaleVector = BABYLON.Vector3.One();
  70279. _this._negateScaleChildren = BABYLON.Vector3.One();
  70280. _this._scalingDeterminant = 1;
  70281. _this._skeleton = skeleton;
  70282. _this._localMatrix = localMatrix ? localMatrix : BABYLON.Matrix.Identity();
  70283. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  70284. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  70285. _this._index = index;
  70286. skeleton.bones.push(_this);
  70287. _this.setParent(parentBone, false);
  70288. _this._updateDifferenceMatrix();
  70289. return _this;
  70290. }
  70291. Object.defineProperty(Bone.prototype, "_matrix", {
  70292. get: function () {
  70293. return this._localMatrix;
  70294. },
  70295. set: function (val) {
  70296. if (this._localMatrix) {
  70297. this._localMatrix.copyFrom(val);
  70298. }
  70299. else {
  70300. this._localMatrix = val;
  70301. }
  70302. },
  70303. enumerable: true,
  70304. configurable: true
  70305. });
  70306. // Members
  70307. Bone.prototype.getSkeleton = function () {
  70308. return this._skeleton;
  70309. };
  70310. Bone.prototype.getParent = function () {
  70311. return this._parent;
  70312. };
  70313. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  70314. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  70315. if (this._parent === parent) {
  70316. return;
  70317. }
  70318. if (this._parent) {
  70319. var index = this._parent.children.indexOf(this);
  70320. if (index !== -1) {
  70321. this._parent.children.splice(index, 1);
  70322. }
  70323. }
  70324. this._parent = parent;
  70325. if (this._parent) {
  70326. this._parent.children.push(this);
  70327. }
  70328. if (updateDifferenceMatrix) {
  70329. this._updateDifferenceMatrix();
  70330. }
  70331. };
  70332. Bone.prototype.getLocalMatrix = function () {
  70333. return this._localMatrix;
  70334. };
  70335. Bone.prototype.getBaseMatrix = function () {
  70336. return this._baseMatrix;
  70337. };
  70338. Bone.prototype.getRestPose = function () {
  70339. return this._restPose;
  70340. };
  70341. Bone.prototype.returnToRest = function () {
  70342. this.updateMatrix(this._restPose.clone());
  70343. };
  70344. Bone.prototype.getWorldMatrix = function () {
  70345. return this._worldTransform;
  70346. };
  70347. Bone.prototype.getInvertedAbsoluteTransform = function () {
  70348. return this._invertedAbsoluteTransform;
  70349. };
  70350. Bone.prototype.getAbsoluteTransform = function () {
  70351. return this._absoluteTransform;
  70352. };
  70353. Object.defineProperty(Bone.prototype, "position", {
  70354. // Properties (matches AbstractMesh properties)
  70355. get: function () {
  70356. return this.getPosition();
  70357. },
  70358. set: function (newPosition) {
  70359. this.setPosition(newPosition);
  70360. },
  70361. enumerable: true,
  70362. configurable: true
  70363. });
  70364. Object.defineProperty(Bone.prototype, "rotation", {
  70365. get: function () {
  70366. return this.getRotation();
  70367. },
  70368. set: function (newRotation) {
  70369. this.setRotation(newRotation);
  70370. },
  70371. enumerable: true,
  70372. configurable: true
  70373. });
  70374. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  70375. get: function () {
  70376. return this.getRotationQuaternion();
  70377. },
  70378. set: function (newRotation) {
  70379. this.setRotationQuaternion(newRotation);
  70380. },
  70381. enumerable: true,
  70382. configurable: true
  70383. });
  70384. Object.defineProperty(Bone.prototype, "scaling", {
  70385. get: function () {
  70386. return this.getScale();
  70387. },
  70388. set: function (newScaling) {
  70389. this.setScale(newScaling.x, newScaling.y, newScaling.z);
  70390. },
  70391. enumerable: true,
  70392. configurable: true
  70393. });
  70394. // Methods
  70395. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  70396. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  70397. this._baseMatrix = matrix.clone();
  70398. this._localMatrix = matrix.clone();
  70399. this._skeleton._markAsDirty();
  70400. if (updateDifferenceMatrix) {
  70401. this._updateDifferenceMatrix();
  70402. }
  70403. };
  70404. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  70405. if (!rootMatrix) {
  70406. rootMatrix = this._baseMatrix;
  70407. }
  70408. if (this._parent) {
  70409. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  70410. }
  70411. else {
  70412. this._absoluteTransform.copyFrom(rootMatrix);
  70413. }
  70414. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  70415. for (var index = 0; index < this.children.length; index++) {
  70416. this.children[index]._updateDifferenceMatrix();
  70417. }
  70418. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  70419. };
  70420. Bone.prototype.markAsDirty = function () {
  70421. this._currentRenderId++;
  70422. this._skeleton._markAsDirty();
  70423. };
  70424. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  70425. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  70426. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  70427. // all animation may be coming from a library skeleton, so may need to create animation
  70428. if (this.animations.length === 0) {
  70429. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  70430. this.animations[0].setKeys([]);
  70431. }
  70432. // get animation info / verify there is such a range from the source bone
  70433. var sourceRange = source.animations[0].getRange(rangeName);
  70434. if (!sourceRange) {
  70435. return false;
  70436. }
  70437. var from = sourceRange.from;
  70438. var to = sourceRange.to;
  70439. var sourceKeys = source.animations[0].getKeys();
  70440. // rescaling prep
  70441. var sourceBoneLength = source.length;
  70442. var sourceParent = source.getParent();
  70443. var parent = this.getParent();
  70444. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  70445. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  70446. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  70447. var destKeys = this.animations[0].getKeys();
  70448. // loop vars declaration
  70449. var orig;
  70450. var origTranslation;
  70451. var mat;
  70452. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  70453. orig = sourceKeys[key];
  70454. if (orig.frame >= from && orig.frame <= to) {
  70455. if (rescaleAsRequired) {
  70456. mat = orig.value.clone();
  70457. // scale based on parent ratio, when bone has parent
  70458. if (parentScalingReqd) {
  70459. origTranslation = mat.getTranslation();
  70460. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  70461. // scale based on skeleton dimension ratio when root bone, and value is passed
  70462. }
  70463. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  70464. origTranslation = mat.getTranslation();
  70465. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  70466. // use original when root bone, and no data for skelDimensionsRatio
  70467. }
  70468. else {
  70469. mat = orig.value;
  70470. }
  70471. }
  70472. else {
  70473. mat = orig.value;
  70474. }
  70475. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  70476. }
  70477. }
  70478. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  70479. return true;
  70480. };
  70481. /**
  70482. * Translate the bone in local or world space.
  70483. * @param vec The amount to translate the bone.
  70484. * @param space The space that the translation is in.
  70485. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70486. */
  70487. Bone.prototype.translate = function (vec, space, mesh) {
  70488. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70489. var lm = this.getLocalMatrix();
  70490. if (space == BABYLON.Space.LOCAL) {
  70491. lm.m[12] += vec.x;
  70492. lm.m[13] += vec.y;
  70493. lm.m[14] += vec.z;
  70494. }
  70495. else {
  70496. var wm = null;
  70497. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  70498. if (mesh) {
  70499. wm = mesh.getWorldMatrix();
  70500. }
  70501. this._skeleton.computeAbsoluteTransforms();
  70502. var tmat = Bone._tmpMats[0];
  70503. var tvec = Bone._tmpVecs[0];
  70504. if (this._parent) {
  70505. if (mesh && wm) {
  70506. tmat.copyFrom(this._parent.getAbsoluteTransform());
  70507. tmat.multiplyToRef(wm, tmat);
  70508. }
  70509. else {
  70510. tmat.copyFrom(this._parent.getAbsoluteTransform());
  70511. }
  70512. }
  70513. tmat.m[12] = 0;
  70514. tmat.m[13] = 0;
  70515. tmat.m[14] = 0;
  70516. tmat.invert();
  70517. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  70518. lm.m[12] += tvec.x;
  70519. lm.m[13] += tvec.y;
  70520. lm.m[14] += tvec.z;
  70521. }
  70522. this.markAsDirty();
  70523. };
  70524. /**
  70525. * Set the postion of the bone in local or world space.
  70526. * @param position The position to set the bone.
  70527. * @param space The space that the position is in.
  70528. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70529. */
  70530. Bone.prototype.setPosition = function (position, space, mesh) {
  70531. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70532. var lm = this.getLocalMatrix();
  70533. if (space == BABYLON.Space.LOCAL) {
  70534. lm.m[12] = position.x;
  70535. lm.m[13] = position.y;
  70536. lm.m[14] = position.z;
  70537. }
  70538. else {
  70539. var wm = null;
  70540. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  70541. if (mesh) {
  70542. wm = mesh.getWorldMatrix();
  70543. }
  70544. this._skeleton.computeAbsoluteTransforms();
  70545. var tmat = Bone._tmpMats[0];
  70546. var vec = Bone._tmpVecs[0];
  70547. if (this._parent) {
  70548. if (mesh && wm) {
  70549. tmat.copyFrom(this._parent.getAbsoluteTransform());
  70550. tmat.multiplyToRef(wm, tmat);
  70551. }
  70552. else {
  70553. tmat.copyFrom(this._parent.getAbsoluteTransform());
  70554. }
  70555. }
  70556. tmat.invert();
  70557. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  70558. lm.m[12] = vec.x;
  70559. lm.m[13] = vec.y;
  70560. lm.m[14] = vec.z;
  70561. }
  70562. this.markAsDirty();
  70563. };
  70564. /**
  70565. * Set the absolute postion of the bone (world space).
  70566. * @param position The position to set the bone.
  70567. * @param mesh The mesh that this bone is attached to.
  70568. */
  70569. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  70570. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  70571. };
  70572. /**
  70573. * Set the scale of the bone on the x, y and z axes.
  70574. * @param x The scale of the bone on the x axis.
  70575. * @param x The scale of the bone on the y axis.
  70576. * @param z The scale of the bone on the z axis.
  70577. * @param scaleChildren Set this to true if children of the bone should be scaled.
  70578. */
  70579. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  70580. if (scaleChildren === void 0) { scaleChildren = false; }
  70581. if (this.animations[0] && !this.animations[0].hasRunningRuntimeAnimations) {
  70582. if (!scaleChildren) {
  70583. this._negateScaleChildren.x = 1 / x;
  70584. this._negateScaleChildren.y = 1 / y;
  70585. this._negateScaleChildren.z = 1 / z;
  70586. }
  70587. this._syncScaleVector();
  70588. }
  70589. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  70590. };
  70591. /**
  70592. * Scale the bone on the x, y and z axes.
  70593. * @param x The amount to scale the bone on the x axis.
  70594. * @param x The amount to scale the bone on the y axis.
  70595. * @param z The amount to scale the bone on the z axis.
  70596. * @param scaleChildren Set this to true if children of the bone should be scaled.
  70597. */
  70598. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  70599. if (scaleChildren === void 0) { scaleChildren = false; }
  70600. var locMat = this.getLocalMatrix();
  70601. var origLocMat = Bone._tmpMats[0];
  70602. origLocMat.copyFrom(locMat);
  70603. var origLocMatInv = Bone._tmpMats[1];
  70604. origLocMatInv.copyFrom(origLocMat);
  70605. origLocMatInv.invert();
  70606. var scaleMat = Bone._tmpMats[2];
  70607. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  70608. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  70609. this._scaleVector.x *= x;
  70610. this._scaleVector.y *= y;
  70611. this._scaleVector.z *= z;
  70612. locMat.multiplyToRef(origLocMatInv, locMat);
  70613. locMat.multiplyToRef(scaleMat, locMat);
  70614. locMat.multiplyToRef(origLocMat, locMat);
  70615. var parent = this.getParent();
  70616. if (parent) {
  70617. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  70618. }
  70619. else {
  70620. this.getAbsoluteTransform().copyFrom(locMat);
  70621. }
  70622. var len = this.children.length;
  70623. scaleMat.invert();
  70624. for (var i = 0; i < len; i++) {
  70625. var child = this.children[i];
  70626. var cm = child.getLocalMatrix();
  70627. cm.multiplyToRef(scaleMat, cm);
  70628. var lm = child.getLocalMatrix();
  70629. lm.m[12] *= x;
  70630. lm.m[13] *= y;
  70631. lm.m[14] *= z;
  70632. }
  70633. this.computeAbsoluteTransforms();
  70634. if (scaleChildren) {
  70635. for (var i = 0; i < len; i++) {
  70636. this.children[i].scale(x, y, z, scaleChildren);
  70637. }
  70638. }
  70639. this.markAsDirty();
  70640. };
  70641. /**
  70642. * Set the yaw, pitch, and roll of the bone in local or world space.
  70643. * @param yaw The rotation of the bone on the y axis.
  70644. * @param pitch The rotation of the bone on the x axis.
  70645. * @param roll The rotation of the bone on the z axis.
  70646. * @param space The space that the axes of rotation are in.
  70647. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70648. */
  70649. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  70650. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70651. var rotMat = Bone._tmpMats[0];
  70652. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  70653. var rotMatInv = Bone._tmpMats[1];
  70654. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  70655. rotMatInv.multiplyToRef(rotMat, rotMat);
  70656. this._rotateWithMatrix(rotMat, space, mesh);
  70657. };
  70658. /**
  70659. * Rotate the bone on an axis in local or world space.
  70660. * @param axis The axis to rotate the bone on.
  70661. * @param amount The amount to rotate the bone.
  70662. * @param space The space that the axis is in.
  70663. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70664. */
  70665. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  70666. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70667. var rmat = Bone._tmpMats[0];
  70668. rmat.m[12] = 0;
  70669. rmat.m[13] = 0;
  70670. rmat.m[14] = 0;
  70671. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  70672. this._rotateWithMatrix(rmat, space, mesh);
  70673. };
  70674. /**
  70675. * Set the rotation of the bone to a particular axis angle in local or world space.
  70676. * @param axis The axis to rotate the bone on.
  70677. * @param angle The angle that the bone should be rotated to.
  70678. * @param space The space that the axis is in.
  70679. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70680. */
  70681. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  70682. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70683. var rotMat = Bone._tmpMats[0];
  70684. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  70685. var rotMatInv = Bone._tmpMats[1];
  70686. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  70687. rotMatInv.multiplyToRef(rotMat, rotMat);
  70688. this._rotateWithMatrix(rotMat, space, mesh);
  70689. };
  70690. /**
  70691. * Set the euler rotation of the bone in local of world space.
  70692. * @param rotation The euler rotation that the bone should be set to.
  70693. * @param space The space that the rotation is in.
  70694. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70695. */
  70696. Bone.prototype.setRotation = function (rotation, space, mesh) {
  70697. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70698. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  70699. };
  70700. /**
  70701. * Set the quaternion rotation of the bone in local of world space.
  70702. * @param quat The quaternion rotation that the bone should be set to.
  70703. * @param space The space that the rotation is in.
  70704. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70705. */
  70706. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  70707. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70708. var rotMatInv = Bone._tmpMats[0];
  70709. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  70710. var rotMat = Bone._tmpMats[1];
  70711. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  70712. rotMatInv.multiplyToRef(rotMat, rotMat);
  70713. this._rotateWithMatrix(rotMat, space, mesh);
  70714. };
  70715. /**
  70716. * Set the rotation matrix of the bone in local of world space.
  70717. * @param rotMat The rotation matrix that the bone should be set to.
  70718. * @param space The space that the rotation is in.
  70719. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70720. */
  70721. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  70722. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70723. var rotMatInv = Bone._tmpMats[0];
  70724. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  70725. var rotMat2 = Bone._tmpMats[1];
  70726. rotMat2.copyFrom(rotMat);
  70727. rotMatInv.multiplyToRef(rotMat, rotMat2);
  70728. this._rotateWithMatrix(rotMat2, space, mesh);
  70729. };
  70730. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  70731. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70732. var lmat = this.getLocalMatrix();
  70733. var lx = lmat.m[12];
  70734. var ly = lmat.m[13];
  70735. var lz = lmat.m[14];
  70736. var parent = this.getParent();
  70737. var parentScale = Bone._tmpMats[3];
  70738. var parentScaleInv = Bone._tmpMats[4];
  70739. if (parent) {
  70740. if (space == BABYLON.Space.WORLD) {
  70741. if (mesh) {
  70742. parentScale.copyFrom(mesh.getWorldMatrix());
  70743. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  70744. }
  70745. else {
  70746. parentScale.copyFrom(parent.getAbsoluteTransform());
  70747. }
  70748. }
  70749. else {
  70750. parentScale = parent._scaleMatrix;
  70751. }
  70752. parentScaleInv.copyFrom(parentScale);
  70753. parentScaleInv.invert();
  70754. lmat.multiplyToRef(parentScale, lmat);
  70755. lmat.multiplyToRef(rmat, lmat);
  70756. lmat.multiplyToRef(parentScaleInv, lmat);
  70757. }
  70758. else {
  70759. if (space == BABYLON.Space.WORLD && mesh) {
  70760. parentScale.copyFrom(mesh.getWorldMatrix());
  70761. parentScaleInv.copyFrom(parentScale);
  70762. parentScaleInv.invert();
  70763. lmat.multiplyToRef(parentScale, lmat);
  70764. lmat.multiplyToRef(rmat, lmat);
  70765. lmat.multiplyToRef(parentScaleInv, lmat);
  70766. }
  70767. else {
  70768. lmat.multiplyToRef(rmat, lmat);
  70769. }
  70770. }
  70771. lmat.m[12] = lx;
  70772. lmat.m[13] = ly;
  70773. lmat.m[14] = lz;
  70774. this.computeAbsoluteTransforms();
  70775. this.markAsDirty();
  70776. };
  70777. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  70778. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70779. if (space == BABYLON.Space.WORLD) {
  70780. var scaleMatrix = Bone._tmpMats[2];
  70781. scaleMatrix.copyFrom(this._scaleMatrix);
  70782. rotMatInv.copyFrom(this.getAbsoluteTransform());
  70783. if (mesh) {
  70784. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  70785. var meshScale = Bone._tmpMats[3];
  70786. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  70787. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  70788. }
  70789. rotMatInv.invert();
  70790. scaleMatrix.m[0] *= this._scalingDeterminant;
  70791. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  70792. }
  70793. else {
  70794. rotMatInv.copyFrom(this.getLocalMatrix());
  70795. rotMatInv.invert();
  70796. var scaleMatrix = Bone._tmpMats[2];
  70797. scaleMatrix.copyFrom(this._scaleMatrix);
  70798. if (this._parent) {
  70799. var pscaleMatrix = Bone._tmpMats[3];
  70800. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  70801. pscaleMatrix.invert();
  70802. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  70803. }
  70804. else {
  70805. scaleMatrix.m[0] *= this._scalingDeterminant;
  70806. }
  70807. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  70808. }
  70809. };
  70810. /**
  70811. * Get the scale of the bone
  70812. * @returns the scale of the bone
  70813. */
  70814. Bone.prototype.getScale = function () {
  70815. return this._scaleVector.clone();
  70816. };
  70817. /**
  70818. * Copy the scale of the bone to a vector3.
  70819. * @param result The vector3 to copy the scale to
  70820. */
  70821. Bone.prototype.getScaleToRef = function (result) {
  70822. result.copyFrom(this._scaleVector);
  70823. };
  70824. /**
  70825. * Get the position of the bone in local or world space.
  70826. * @param space The space that the returned position is in.
  70827. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70828. * @returns The position of the bone
  70829. */
  70830. Bone.prototype.getPosition = function (space, mesh) {
  70831. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70832. if (mesh === void 0) { mesh = null; }
  70833. var pos = BABYLON.Vector3.Zero();
  70834. this.getPositionToRef(space, mesh, pos);
  70835. return pos;
  70836. };
  70837. /**
  70838. * Copy the position of the bone to a vector3 in local or world space.
  70839. * @param space The space that the returned position is in.
  70840. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70841. * @param result The vector3 to copy the position to.
  70842. */
  70843. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  70844. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70845. if (space == BABYLON.Space.LOCAL) {
  70846. var lm = this.getLocalMatrix();
  70847. result.x = lm.m[12];
  70848. result.y = lm.m[13];
  70849. result.z = lm.m[14];
  70850. }
  70851. else {
  70852. var wm = null;
  70853. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  70854. if (mesh) {
  70855. wm = mesh.getWorldMatrix();
  70856. }
  70857. this._skeleton.computeAbsoluteTransforms();
  70858. var tmat = Bone._tmpMats[0];
  70859. if (mesh && wm) {
  70860. tmat.copyFrom(this.getAbsoluteTransform());
  70861. tmat.multiplyToRef(wm, tmat);
  70862. }
  70863. else {
  70864. tmat = this.getAbsoluteTransform();
  70865. }
  70866. result.x = tmat.m[12];
  70867. result.y = tmat.m[13];
  70868. result.z = tmat.m[14];
  70869. }
  70870. };
  70871. /**
  70872. * Get the absolute position of the bone (world space).
  70873. * @param mesh The mesh that this bone is attached to.
  70874. * @returns The absolute position of the bone
  70875. */
  70876. Bone.prototype.getAbsolutePosition = function (mesh) {
  70877. if (mesh === void 0) { mesh = null; }
  70878. var pos = BABYLON.Vector3.Zero();
  70879. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  70880. return pos;
  70881. };
  70882. /**
  70883. * Copy the absolute position of the bone (world space) to the result param.
  70884. * @param mesh The mesh that this bone is attached to.
  70885. * @param result The vector3 to copy the absolute position to.
  70886. */
  70887. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  70888. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  70889. };
  70890. /**
  70891. * Compute the absolute transforms of this bone and its children.
  70892. */
  70893. Bone.prototype.computeAbsoluteTransforms = function () {
  70894. if (this._parent) {
  70895. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  70896. }
  70897. else {
  70898. this._absoluteTransform.copyFrom(this._localMatrix);
  70899. var poseMatrix = this._skeleton.getPoseMatrix();
  70900. if (poseMatrix) {
  70901. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  70902. }
  70903. }
  70904. var children = this.children;
  70905. var len = children.length;
  70906. for (var i = 0; i < len; i++) {
  70907. children[i].computeAbsoluteTransforms();
  70908. }
  70909. };
  70910. Bone.prototype._syncScaleVector = function () {
  70911. var lm = this.getLocalMatrix();
  70912. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  70913. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  70914. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  70915. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  70916. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  70917. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  70918. this._scaleVector.x = xs * Math.sqrt(xsq);
  70919. this._scaleVector.y = ys * Math.sqrt(ysq);
  70920. this._scaleVector.z = zs * Math.sqrt(zsq);
  70921. if (this._parent) {
  70922. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  70923. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  70924. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  70925. }
  70926. 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);
  70927. };
  70928. /**
  70929. * Get the world direction from an axis that is in the local space of the bone.
  70930. * @param localAxis The local direction that is used to compute the world direction.
  70931. * @param mesh The mesh that this bone is attached to.
  70932. * @returns The world direction
  70933. */
  70934. Bone.prototype.getDirection = function (localAxis, mesh) {
  70935. if (mesh === void 0) { mesh = null; }
  70936. var result = BABYLON.Vector3.Zero();
  70937. this.getDirectionToRef(localAxis, mesh, result);
  70938. return result;
  70939. };
  70940. /**
  70941. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  70942. * @param localAxis The local direction that is used to compute the world direction.
  70943. * @param mesh The mesh that this bone is attached to.
  70944. * @param result The vector3 that the world direction will be copied to.
  70945. */
  70946. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  70947. if (mesh === void 0) { mesh = null; }
  70948. var wm = null;
  70949. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  70950. if (mesh) {
  70951. wm = mesh.getWorldMatrix();
  70952. }
  70953. this._skeleton.computeAbsoluteTransforms();
  70954. var mat = Bone._tmpMats[0];
  70955. mat.copyFrom(this.getAbsoluteTransform());
  70956. if (mesh && wm) {
  70957. mat.multiplyToRef(wm, mat);
  70958. }
  70959. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  70960. result.normalize();
  70961. };
  70962. /**
  70963. * Get the euler rotation of the bone in local or world space.
  70964. * @param space The space that the rotation should be in.
  70965. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70966. * @returns The euler rotation
  70967. */
  70968. Bone.prototype.getRotation = function (space, mesh) {
  70969. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70970. if (mesh === void 0) { mesh = null; }
  70971. var result = BABYLON.Vector3.Zero();
  70972. this.getRotationToRef(space, mesh, result);
  70973. return result;
  70974. };
  70975. /**
  70976. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  70977. * @param space The space that the rotation should be in.
  70978. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70979. * @param result The vector3 that the rotation should be copied to.
  70980. */
  70981. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  70982. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70983. if (mesh === void 0) { mesh = null; }
  70984. var quat = Bone._tmpQuat;
  70985. this.getRotationQuaternionToRef(space, mesh, quat);
  70986. quat.toEulerAnglesToRef(result);
  70987. };
  70988. /**
  70989. * Get the quaternion rotation of the bone in either local or world space.
  70990. * @param space The space that the rotation should be in.
  70991. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70992. * @returns The quaternion rotation
  70993. */
  70994. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  70995. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70996. if (mesh === void 0) { mesh = null; }
  70997. var result = BABYLON.Quaternion.Identity();
  70998. this.getRotationQuaternionToRef(space, mesh, result);
  70999. return result;
  71000. };
  71001. /**
  71002. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  71003. * @param space The space that the rotation should be in.
  71004. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71005. * @param result The quaternion that the rotation should be copied to.
  71006. */
  71007. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  71008. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71009. if (mesh === void 0) { mesh = null; }
  71010. if (space == BABYLON.Space.LOCAL) {
  71011. this.getLocalMatrix().decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  71012. }
  71013. else {
  71014. var mat = Bone._tmpMats[0];
  71015. var amat = this.getAbsoluteTransform();
  71016. if (mesh) {
  71017. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  71018. }
  71019. else {
  71020. mat.copyFrom(amat);
  71021. }
  71022. mat.m[0] *= this._scalingDeterminant;
  71023. mat.m[1] *= this._scalingDeterminant;
  71024. mat.m[2] *= this._scalingDeterminant;
  71025. mat.decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  71026. }
  71027. };
  71028. /**
  71029. * Get the rotation matrix of the bone in local or world space.
  71030. * @param space The space that the rotation should be in.
  71031. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71032. * @returns The rotation matrix
  71033. */
  71034. Bone.prototype.getRotationMatrix = function (space, mesh) {
  71035. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71036. var result = BABYLON.Matrix.Identity();
  71037. this.getRotationMatrixToRef(space, mesh, result);
  71038. return result;
  71039. };
  71040. /**
  71041. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  71042. * @param space The space that the rotation should be in.
  71043. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71044. * @param result The quaternion that the rotation should be copied to.
  71045. */
  71046. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  71047. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71048. if (space == BABYLON.Space.LOCAL) {
  71049. this.getLocalMatrix().getRotationMatrixToRef(result);
  71050. }
  71051. else {
  71052. var mat = Bone._tmpMats[0];
  71053. var amat = this.getAbsoluteTransform();
  71054. if (mesh) {
  71055. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  71056. }
  71057. else {
  71058. mat.copyFrom(amat);
  71059. }
  71060. mat.m[0] *= this._scalingDeterminant;
  71061. mat.m[1] *= this._scalingDeterminant;
  71062. mat.m[2] *= this._scalingDeterminant;
  71063. mat.getRotationMatrixToRef(result);
  71064. }
  71065. };
  71066. /**
  71067. * Get the world position of a point that is in the local space of the bone.
  71068. * @param position The local position
  71069. * @param mesh The mesh that this bone is attached to.
  71070. * @returns The world position
  71071. */
  71072. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  71073. if (mesh === void 0) { mesh = null; }
  71074. var result = BABYLON.Vector3.Zero();
  71075. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  71076. return result;
  71077. };
  71078. /**
  71079. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  71080. * @param position The local position
  71081. * @param mesh The mesh that this bone is attached to.
  71082. * @param result The vector3 that the world position should be copied to.
  71083. */
  71084. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  71085. if (mesh === void 0) { mesh = null; }
  71086. var wm = null;
  71087. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  71088. if (mesh) {
  71089. wm = mesh.getWorldMatrix();
  71090. }
  71091. this._skeleton.computeAbsoluteTransforms();
  71092. var tmat = Bone._tmpMats[0];
  71093. if (mesh && wm) {
  71094. tmat.copyFrom(this.getAbsoluteTransform());
  71095. tmat.multiplyToRef(wm, tmat);
  71096. }
  71097. else {
  71098. tmat = this.getAbsoluteTransform();
  71099. }
  71100. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  71101. };
  71102. /**
  71103. * Get the local position of a point that is in world space.
  71104. * @param position The world position
  71105. * @param mesh The mesh that this bone is attached to.
  71106. * @returns The local position
  71107. */
  71108. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  71109. if (mesh === void 0) { mesh = null; }
  71110. var result = BABYLON.Vector3.Zero();
  71111. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  71112. return result;
  71113. };
  71114. /**
  71115. * Get the local position of a point that is in world space and copy it to the result param.
  71116. * @param position The world position
  71117. * @param mesh The mesh that this bone is attached to.
  71118. * @param result The vector3 that the local position should be copied to.
  71119. */
  71120. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  71121. if (mesh === void 0) { mesh = null; }
  71122. var wm = null;
  71123. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  71124. if (mesh) {
  71125. wm = mesh.getWorldMatrix();
  71126. }
  71127. this._skeleton.computeAbsoluteTransforms();
  71128. var tmat = Bone._tmpMats[0];
  71129. tmat.copyFrom(this.getAbsoluteTransform());
  71130. if (mesh && wm) {
  71131. tmat.multiplyToRef(wm, tmat);
  71132. }
  71133. tmat.invert();
  71134. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  71135. };
  71136. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  71137. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  71138. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  71139. return Bone;
  71140. }(BABYLON.Node));
  71141. BABYLON.Bone = Bone;
  71142. })(BABYLON || (BABYLON = {}));
  71143. //# sourceMappingURL=babylon.bone.js.map
  71144. var BABYLON;
  71145. (function (BABYLON) {
  71146. var BoneIKController = /** @class */ (function () {
  71147. function BoneIKController(mesh, bone, options) {
  71148. this.targetPosition = BABYLON.Vector3.Zero();
  71149. this.poleTargetPosition = BABYLON.Vector3.Zero();
  71150. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  71151. this.poleAngle = 0;
  71152. this.slerpAmount = 1;
  71153. this._bone1Quat = BABYLON.Quaternion.Identity();
  71154. this._bone1Mat = BABYLON.Matrix.Identity();
  71155. this._bone2Ang = Math.PI;
  71156. this._maxAngle = Math.PI;
  71157. this._rightHandedSystem = false;
  71158. this._bendAxis = BABYLON.Vector3.Right();
  71159. this._slerping = false;
  71160. this._adjustRoll = 0;
  71161. this._bone2 = bone;
  71162. this._bone1 = bone.getParent();
  71163. if (!this._bone1) {
  71164. return;
  71165. }
  71166. this.mesh = mesh;
  71167. var bonePos = bone.getPosition();
  71168. if (bone.getAbsoluteTransform().determinant() > 0) {
  71169. this._rightHandedSystem = true;
  71170. this._bendAxis.x = 0;
  71171. this._bendAxis.y = 0;
  71172. this._bendAxis.z = -1;
  71173. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  71174. this._adjustRoll = Math.PI * .5;
  71175. this._bendAxis.z = 1;
  71176. }
  71177. }
  71178. if (this._bone1.length) {
  71179. var boneScale1 = this._bone1.getScale();
  71180. var boneScale2 = this._bone2.getScale();
  71181. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  71182. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  71183. }
  71184. else if (this._bone1.children[0]) {
  71185. mesh.computeWorldMatrix(true);
  71186. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  71187. var pos2 = this._bone2.getAbsolutePosition(mesh);
  71188. var pos3 = this._bone1.getAbsolutePosition(mesh);
  71189. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  71190. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  71191. }
  71192. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  71193. this.maxAngle = Math.PI;
  71194. if (options) {
  71195. if (options.targetMesh) {
  71196. this.targetMesh = options.targetMesh;
  71197. this.targetMesh.computeWorldMatrix(true);
  71198. }
  71199. if (options.poleTargetMesh) {
  71200. this.poleTargetMesh = options.poleTargetMesh;
  71201. this.poleTargetMesh.computeWorldMatrix(true);
  71202. }
  71203. else if (options.poleTargetBone) {
  71204. this.poleTargetBone = options.poleTargetBone;
  71205. }
  71206. else if (this._bone1.getParent()) {
  71207. this.poleTargetBone = this._bone1.getParent();
  71208. }
  71209. if (options.poleTargetLocalOffset) {
  71210. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  71211. }
  71212. if (options.poleAngle) {
  71213. this.poleAngle = options.poleAngle;
  71214. }
  71215. if (options.bendAxis) {
  71216. this._bendAxis.copyFrom(options.bendAxis);
  71217. }
  71218. if (options.maxAngle) {
  71219. this.maxAngle = options.maxAngle;
  71220. }
  71221. if (options.slerpAmount) {
  71222. this.slerpAmount = options.slerpAmount;
  71223. }
  71224. }
  71225. }
  71226. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  71227. get: function () {
  71228. return this._maxAngle;
  71229. },
  71230. set: function (value) {
  71231. this._setMaxAngle(value);
  71232. },
  71233. enumerable: true,
  71234. configurable: true
  71235. });
  71236. BoneIKController.prototype._setMaxAngle = function (ang) {
  71237. if (ang < 0) {
  71238. ang = 0;
  71239. }
  71240. if (ang > Math.PI || ang == undefined) {
  71241. ang = Math.PI;
  71242. }
  71243. this._maxAngle = ang;
  71244. var a = this._bone1Length;
  71245. var b = this._bone2Length;
  71246. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  71247. };
  71248. BoneIKController.prototype.update = function () {
  71249. var bone1 = this._bone1;
  71250. if (!bone1) {
  71251. return;
  71252. }
  71253. var target = this.targetPosition;
  71254. var poleTarget = this.poleTargetPosition;
  71255. var mat1 = BoneIKController._tmpMats[0];
  71256. var mat2 = BoneIKController._tmpMats[1];
  71257. if (this.targetMesh) {
  71258. target.copyFrom(this.targetMesh.getAbsolutePosition());
  71259. }
  71260. if (this.poleTargetBone) {
  71261. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  71262. }
  71263. else if (this.poleTargetMesh) {
  71264. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  71265. }
  71266. var bonePos = BoneIKController._tmpVecs[0];
  71267. var zaxis = BoneIKController._tmpVecs[1];
  71268. var xaxis = BoneIKController._tmpVecs[2];
  71269. var yaxis = BoneIKController._tmpVecs[3];
  71270. var upAxis = BoneIKController._tmpVecs[4];
  71271. var _tmpQuat = BoneIKController._tmpQuat;
  71272. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  71273. poleTarget.subtractToRef(bonePos, upAxis);
  71274. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  71275. upAxis.y = 1;
  71276. }
  71277. else {
  71278. upAxis.normalize();
  71279. }
  71280. target.subtractToRef(bonePos, yaxis);
  71281. yaxis.normalize();
  71282. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  71283. zaxis.normalize();
  71284. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  71285. xaxis.normalize();
  71286. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  71287. var a = this._bone1Length;
  71288. var b = this._bone2Length;
  71289. var c = BABYLON.Vector3.Distance(bonePos, target);
  71290. if (this._maxReach > 0) {
  71291. c = Math.min(this._maxReach, c);
  71292. }
  71293. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  71294. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  71295. if (acosa > 1) {
  71296. acosa = 1;
  71297. }
  71298. if (acosb > 1) {
  71299. acosb = 1;
  71300. }
  71301. if (acosa < -1) {
  71302. acosa = -1;
  71303. }
  71304. if (acosb < -1) {
  71305. acosb = -1;
  71306. }
  71307. var angA = Math.acos(acosa);
  71308. var angB = Math.acos(acosb);
  71309. var angC = -angA - angB;
  71310. if (this._rightHandedSystem) {
  71311. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  71312. mat2.multiplyToRef(mat1, mat1);
  71313. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  71314. mat2.multiplyToRef(mat1, mat1);
  71315. }
  71316. else {
  71317. var _tmpVec = BoneIKController._tmpVecs[5];
  71318. _tmpVec.copyFrom(this._bendAxis);
  71319. _tmpVec.x *= -1;
  71320. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  71321. mat2.multiplyToRef(mat1, mat1);
  71322. }
  71323. if (this.poleAngle) {
  71324. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  71325. mat1.multiplyToRef(mat2, mat1);
  71326. }
  71327. if (this._bone1) {
  71328. if (this.slerpAmount < 1) {
  71329. if (!this._slerping) {
  71330. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  71331. }
  71332. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  71333. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  71334. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  71335. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  71336. this._slerping = true;
  71337. }
  71338. else {
  71339. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  71340. this._bone1Mat.copyFrom(mat1);
  71341. this._slerping = false;
  71342. }
  71343. }
  71344. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  71345. this._bone2Ang = angC;
  71346. };
  71347. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  71348. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  71349. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  71350. return BoneIKController;
  71351. }());
  71352. BABYLON.BoneIKController = BoneIKController;
  71353. })(BABYLON || (BABYLON = {}));
  71354. //# sourceMappingURL=babylon.boneIKController.js.map
  71355. var BABYLON;
  71356. (function (BABYLON) {
  71357. var BoneLookController = /** @class */ (function () {
  71358. /**
  71359. * Create a BoneLookController
  71360. * @param mesh the mesh that the bone belongs to
  71361. * @param bone the bone that will be looking to the target
  71362. * @param target the target Vector3 to look at
  71363. * @param settings optional settings:
  71364. * - maxYaw: the maximum angle the bone will yaw to
  71365. * - minYaw: the minimum angle the bone will yaw to
  71366. * - maxPitch: the maximum angle the bone will pitch to
  71367. * - minPitch: the minimum angle the bone will yaw to
  71368. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  71369. * - upAxis: the up axis of the coordinate system
  71370. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  71371. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  71372. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  71373. * - adjustYaw: used to make an adjustment to the yaw of the bone
  71374. * - adjustPitch: used to make an adjustment to the pitch of the bone
  71375. * - adjustRoll: used to make an adjustment to the roll of the bone
  71376. **/
  71377. function BoneLookController(mesh, bone, target, options) {
  71378. /**
  71379. * The up axis of the coordinate system that is used when the bone is rotated.
  71380. */
  71381. this.upAxis = BABYLON.Vector3.Up();
  71382. /**
  71383. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  71384. */
  71385. this.upAxisSpace = BABYLON.Space.LOCAL;
  71386. /**
  71387. * Used to make an adjustment to the yaw of the bone.
  71388. */
  71389. this.adjustYaw = 0;
  71390. /**
  71391. * Used to make an adjustment to the pitch of the bone.
  71392. */
  71393. this.adjustPitch = 0;
  71394. /**
  71395. * Used to make an adjustment to the roll of the bone.
  71396. */
  71397. this.adjustRoll = 0;
  71398. /**
  71399. * 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).
  71400. */
  71401. this.slerpAmount = 1;
  71402. this._boneQuat = BABYLON.Quaternion.Identity();
  71403. this._slerping = false;
  71404. this._firstFrameSkipped = false;
  71405. this._fowardAxis = BABYLON.Vector3.Forward();
  71406. this.mesh = mesh;
  71407. this.bone = bone;
  71408. this.target = target;
  71409. if (options) {
  71410. if (options.adjustYaw) {
  71411. this.adjustYaw = options.adjustYaw;
  71412. }
  71413. if (options.adjustPitch) {
  71414. this.adjustPitch = options.adjustPitch;
  71415. }
  71416. if (options.adjustRoll) {
  71417. this.adjustRoll = options.adjustRoll;
  71418. }
  71419. if (options.maxYaw != null) {
  71420. this.maxYaw = options.maxYaw;
  71421. }
  71422. else {
  71423. this.maxYaw = Math.PI;
  71424. }
  71425. if (options.minYaw != null) {
  71426. this.minYaw = options.minYaw;
  71427. }
  71428. else {
  71429. this.minYaw = -Math.PI;
  71430. }
  71431. if (options.maxPitch != null) {
  71432. this.maxPitch = options.maxPitch;
  71433. }
  71434. else {
  71435. this.maxPitch = Math.PI;
  71436. }
  71437. if (options.minPitch != null) {
  71438. this.minPitch = options.minPitch;
  71439. }
  71440. else {
  71441. this.minPitch = -Math.PI;
  71442. }
  71443. if (options.slerpAmount != null) {
  71444. this.slerpAmount = options.slerpAmount;
  71445. }
  71446. if (options.upAxis != null) {
  71447. this.upAxis = options.upAxis;
  71448. }
  71449. if (options.upAxisSpace != null) {
  71450. this.upAxisSpace = options.upAxisSpace;
  71451. }
  71452. if (options.yawAxis != null || options.pitchAxis != null) {
  71453. var newYawAxis = BABYLON.Axis.Y;
  71454. var newPitchAxis = BABYLON.Axis.X;
  71455. if (options.yawAxis != null) {
  71456. newYawAxis = options.yawAxis.clone();
  71457. newYawAxis.normalize();
  71458. }
  71459. if (options.pitchAxis != null) {
  71460. newPitchAxis = options.pitchAxis.clone();
  71461. newPitchAxis.normalize();
  71462. }
  71463. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  71464. this._transformYawPitch = BABYLON.Matrix.Identity();
  71465. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  71466. this._transformYawPitchInv = this._transformYawPitch.clone();
  71467. this._transformYawPitch.invert();
  71468. }
  71469. }
  71470. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  71471. this.upAxisSpace = BABYLON.Space.LOCAL;
  71472. }
  71473. }
  71474. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  71475. /**
  71476. * Get/set the minimum yaw angle that the bone can look to.
  71477. */
  71478. get: function () {
  71479. return this._minYaw;
  71480. },
  71481. set: function (value) {
  71482. this._minYaw = value;
  71483. this._minYawSin = Math.sin(value);
  71484. this._minYawCos = Math.cos(value);
  71485. if (this._maxYaw != null) {
  71486. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  71487. this._yawRange = this._maxYaw - this._minYaw;
  71488. }
  71489. },
  71490. enumerable: true,
  71491. configurable: true
  71492. });
  71493. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  71494. /**
  71495. * Get/set the maximum yaw angle that the bone can look to.
  71496. */
  71497. get: function () {
  71498. return this._maxYaw;
  71499. },
  71500. set: function (value) {
  71501. this._maxYaw = value;
  71502. this._maxYawSin = Math.sin(value);
  71503. this._maxYawCos = Math.cos(value);
  71504. if (this._minYaw != null) {
  71505. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  71506. this._yawRange = this._maxYaw - this._minYaw;
  71507. }
  71508. },
  71509. enumerable: true,
  71510. configurable: true
  71511. });
  71512. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  71513. /**
  71514. * Get/set the minimum pitch angle that the bone can look to.
  71515. */
  71516. get: function () {
  71517. return this._minPitch;
  71518. },
  71519. set: function (value) {
  71520. this._minPitch = value;
  71521. this._minPitchTan = Math.tan(value);
  71522. },
  71523. enumerable: true,
  71524. configurable: true
  71525. });
  71526. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  71527. /**
  71528. * Get/set the maximum pitch angle that the bone can look to.
  71529. */
  71530. get: function () {
  71531. return this._maxPitch;
  71532. },
  71533. set: function (value) {
  71534. this._maxPitch = value;
  71535. this._maxPitchTan = Math.tan(value);
  71536. },
  71537. enumerable: true,
  71538. configurable: true
  71539. });
  71540. /**
  71541. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  71542. */
  71543. BoneLookController.prototype.update = function () {
  71544. //skip the first frame when slerping so that the mesh rotation is correct
  71545. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  71546. this._firstFrameSkipped = true;
  71547. return;
  71548. }
  71549. var bone = this.bone;
  71550. var bonePos = BoneLookController._tmpVecs[0];
  71551. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  71552. var target = this.target;
  71553. var _tmpMat1 = BoneLookController._tmpMats[0];
  71554. var _tmpMat2 = BoneLookController._tmpMats[1];
  71555. var mesh = this.mesh;
  71556. var parentBone = bone.getParent();
  71557. var upAxis = BoneLookController._tmpVecs[1];
  71558. upAxis.copyFrom(this.upAxis);
  71559. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  71560. if (this._transformYawPitch) {
  71561. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  71562. }
  71563. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  71564. }
  71565. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  71566. mesh.getDirectionToRef(upAxis, upAxis);
  71567. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  71568. upAxis.normalize();
  71569. }
  71570. }
  71571. var checkYaw = false;
  71572. var checkPitch = false;
  71573. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  71574. checkYaw = true;
  71575. }
  71576. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  71577. checkPitch = true;
  71578. }
  71579. if (checkYaw || checkPitch) {
  71580. var spaceMat = BoneLookController._tmpMats[2];
  71581. var spaceMatInv = BoneLookController._tmpMats[3];
  71582. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  71583. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  71584. }
  71585. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  71586. spaceMat.copyFrom(mesh.getWorldMatrix());
  71587. }
  71588. else {
  71589. var forwardAxis = BoneLookController._tmpVecs[2];
  71590. forwardAxis.copyFrom(this._fowardAxis);
  71591. if (this._transformYawPitch) {
  71592. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  71593. }
  71594. if (parentBone) {
  71595. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  71596. }
  71597. else {
  71598. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  71599. }
  71600. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  71601. rightAxis.normalize();
  71602. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  71603. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  71604. }
  71605. spaceMat.invertToRef(spaceMatInv);
  71606. var xzlen = null;
  71607. if (checkPitch) {
  71608. var localTarget = BoneLookController._tmpVecs[3];
  71609. target.subtractToRef(bonePos, localTarget);
  71610. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  71611. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  71612. var pitch = Math.atan2(localTarget.y, xzlen);
  71613. var newPitch = pitch;
  71614. if (pitch > this._maxPitch) {
  71615. localTarget.y = this._maxPitchTan * xzlen;
  71616. newPitch = this._maxPitch;
  71617. }
  71618. else if (pitch < this._minPitch) {
  71619. localTarget.y = this._minPitchTan * xzlen;
  71620. newPitch = this._minPitch;
  71621. }
  71622. if (pitch != newPitch) {
  71623. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  71624. localTarget.addInPlace(bonePos);
  71625. target = localTarget;
  71626. }
  71627. }
  71628. if (checkYaw) {
  71629. var localTarget = BoneLookController._tmpVecs[4];
  71630. target.subtractToRef(bonePos, localTarget);
  71631. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  71632. var yaw = Math.atan2(localTarget.x, localTarget.z);
  71633. var newYaw = yaw;
  71634. if (yaw > this._maxYaw || yaw < this._minYaw) {
  71635. if (xzlen == null) {
  71636. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  71637. }
  71638. if (this._yawRange > Math.PI) {
  71639. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  71640. localTarget.z = this._maxYawCos * xzlen;
  71641. localTarget.x = this._maxYawSin * xzlen;
  71642. newYaw = this._maxYaw;
  71643. }
  71644. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  71645. localTarget.z = this._minYawCos * xzlen;
  71646. localTarget.x = this._minYawSin * xzlen;
  71647. newYaw = this._minYaw;
  71648. }
  71649. }
  71650. else {
  71651. if (yaw > this._maxYaw) {
  71652. localTarget.z = this._maxYawCos * xzlen;
  71653. localTarget.x = this._maxYawSin * xzlen;
  71654. newYaw = this._maxYaw;
  71655. }
  71656. else if (yaw < this._minYaw) {
  71657. localTarget.z = this._minYawCos * xzlen;
  71658. localTarget.x = this._minYawSin * xzlen;
  71659. newYaw = this._minYaw;
  71660. }
  71661. }
  71662. }
  71663. if (this._slerping && this._yawRange > Math.PI) {
  71664. //are we going to be crossing into the min/max region?
  71665. var boneFwd = BoneLookController._tmpVecs[8];
  71666. boneFwd.copyFrom(BABYLON.Axis.Z);
  71667. if (this._transformYawPitch) {
  71668. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  71669. }
  71670. var boneRotMat = BoneLookController._tmpMats[4];
  71671. this._boneQuat.toRotationMatrix(boneRotMat);
  71672. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  71673. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  71674. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  71675. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  71676. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  71677. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  71678. if (angBtwTar > angBtwMidYaw) {
  71679. if (xzlen == null) {
  71680. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  71681. }
  71682. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  71683. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  71684. if (angBtwMin < angBtwMax) {
  71685. newYaw = boneYaw + Math.PI * .75;
  71686. localTarget.z = Math.cos(newYaw) * xzlen;
  71687. localTarget.x = Math.sin(newYaw) * xzlen;
  71688. }
  71689. else {
  71690. newYaw = boneYaw - Math.PI * .75;
  71691. localTarget.z = Math.cos(newYaw) * xzlen;
  71692. localTarget.x = Math.sin(newYaw) * xzlen;
  71693. }
  71694. }
  71695. }
  71696. if (yaw != newYaw) {
  71697. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  71698. localTarget.addInPlace(bonePos);
  71699. target = localTarget;
  71700. }
  71701. }
  71702. }
  71703. var zaxis = BoneLookController._tmpVecs[5];
  71704. var xaxis = BoneLookController._tmpVecs[6];
  71705. var yaxis = BoneLookController._tmpVecs[7];
  71706. var _tmpQuat = BoneLookController._tmpQuat;
  71707. target.subtractToRef(bonePos, zaxis);
  71708. zaxis.normalize();
  71709. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  71710. xaxis.normalize();
  71711. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  71712. yaxis.normalize();
  71713. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  71714. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  71715. return;
  71716. }
  71717. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  71718. return;
  71719. }
  71720. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  71721. return;
  71722. }
  71723. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  71724. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  71725. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  71726. }
  71727. if (this.slerpAmount < 1) {
  71728. if (!this._slerping) {
  71729. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  71730. }
  71731. if (this._transformYawPitch) {
  71732. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  71733. }
  71734. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  71735. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  71736. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  71737. this._slerping = true;
  71738. }
  71739. else {
  71740. if (this._transformYawPitch) {
  71741. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  71742. }
  71743. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  71744. this._slerping = false;
  71745. }
  71746. };
  71747. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  71748. var angDiff = ang2 - ang1;
  71749. angDiff %= Math.PI * 2;
  71750. if (angDiff > Math.PI) {
  71751. angDiff -= Math.PI * 2;
  71752. }
  71753. else if (angDiff < -Math.PI) {
  71754. angDiff += Math.PI * 2;
  71755. }
  71756. return angDiff;
  71757. };
  71758. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  71759. ang1 %= (2 * Math.PI);
  71760. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  71761. ang2 %= (2 * Math.PI);
  71762. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  71763. var ab = 0;
  71764. if (ang1 < ang2) {
  71765. ab = ang2 - ang1;
  71766. }
  71767. else {
  71768. ab = ang1 - ang2;
  71769. }
  71770. if (ab > Math.PI) {
  71771. ab = Math.PI * 2 - ab;
  71772. }
  71773. return ab;
  71774. };
  71775. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  71776. ang %= (2 * Math.PI);
  71777. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  71778. ang1 %= (2 * Math.PI);
  71779. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  71780. ang2 %= (2 * Math.PI);
  71781. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  71782. if (ang1 < ang2) {
  71783. if (ang > ang1 && ang < ang2) {
  71784. return true;
  71785. }
  71786. }
  71787. else {
  71788. if (ang > ang2 && ang < ang1) {
  71789. return true;
  71790. }
  71791. }
  71792. return false;
  71793. };
  71794. 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()];
  71795. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  71796. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  71797. return BoneLookController;
  71798. }());
  71799. BABYLON.BoneLookController = BoneLookController;
  71800. })(BABYLON || (BABYLON = {}));
  71801. //# sourceMappingURL=babylon.boneLookController.js.map
  71802. var BABYLON;
  71803. (function (BABYLON) {
  71804. var Skeleton = /** @class */ (function () {
  71805. function Skeleton(name, id, scene) {
  71806. this.name = name;
  71807. this.id = id;
  71808. this.bones = new Array();
  71809. this.needInitialSkinMatrix = false;
  71810. this._isDirty = true;
  71811. this._meshesWithPoseMatrix = new Array();
  71812. this._identity = BABYLON.Matrix.Identity();
  71813. this._ranges = {};
  71814. this._lastAbsoluteTransformsUpdateId = -1;
  71815. /**
  71816. * Specifies if the skeleton should be serialized.
  71817. */
  71818. this.doNotSerialize = false;
  71819. // Events
  71820. /**
  71821. * An event triggered before computing the skeleton's matrices
  71822. * @type {BABYLON.Observable}
  71823. */
  71824. this.onBeforeComputeObservable = new BABYLON.Observable();
  71825. this.bones = [];
  71826. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  71827. scene.skeletons.push(this);
  71828. //make sure it will recalculate the matrix next time prepare is called.
  71829. this._isDirty = true;
  71830. }
  71831. // Members
  71832. Skeleton.prototype.getTransformMatrices = function (mesh) {
  71833. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  71834. return mesh._bonesTransformMatrices;
  71835. }
  71836. if (!this._transformMatrices) {
  71837. this.prepare();
  71838. }
  71839. return this._transformMatrices;
  71840. };
  71841. Skeleton.prototype.getScene = function () {
  71842. return this._scene;
  71843. };
  71844. // Methods
  71845. /**
  71846. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  71847. */
  71848. Skeleton.prototype.toString = function (fullDetails) {
  71849. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  71850. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  71851. if (fullDetails) {
  71852. ret += ", Ranges: {";
  71853. var first = true;
  71854. for (var name_1 in this._ranges) {
  71855. if (first) {
  71856. ret += ", ";
  71857. first = false;
  71858. }
  71859. ret += name_1;
  71860. }
  71861. ret += "}";
  71862. }
  71863. return ret;
  71864. };
  71865. /**
  71866. * Get bone's index searching by name
  71867. * @param {string} name is bone's name to search for
  71868. * @return {number} Indice of the bone. Returns -1 if not found
  71869. */
  71870. Skeleton.prototype.getBoneIndexByName = function (name) {
  71871. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  71872. if (this.bones[boneIndex].name === name) {
  71873. return boneIndex;
  71874. }
  71875. }
  71876. return -1;
  71877. };
  71878. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  71879. // check name not already in use
  71880. if (!this._ranges[name]) {
  71881. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  71882. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  71883. if (this.bones[i].animations[0]) {
  71884. this.bones[i].animations[0].createRange(name, from, to);
  71885. }
  71886. }
  71887. }
  71888. };
  71889. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  71890. if (deleteFrames === void 0) { deleteFrames = true; }
  71891. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  71892. if (this.bones[i].animations[0]) {
  71893. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  71894. }
  71895. }
  71896. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  71897. };
  71898. Skeleton.prototype.getAnimationRange = function (name) {
  71899. return this._ranges[name];
  71900. };
  71901. /**
  71902. * Returns as an Array, all AnimationRanges defined on this skeleton
  71903. */
  71904. Skeleton.prototype.getAnimationRanges = function () {
  71905. var animationRanges = [];
  71906. var name;
  71907. var i = 0;
  71908. for (name in this._ranges) {
  71909. animationRanges[i] = this._ranges[name];
  71910. i++;
  71911. }
  71912. return animationRanges;
  71913. };
  71914. /**
  71915. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  71916. */
  71917. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  71918. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  71919. if (this._ranges[name] || !source.getAnimationRange(name)) {
  71920. return false;
  71921. }
  71922. var ret = true;
  71923. var frameOffset = this._getHighestAnimationFrame() + 1;
  71924. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  71925. var boneDict = {};
  71926. var sourceBones = source.bones;
  71927. var nBones;
  71928. var i;
  71929. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  71930. boneDict[sourceBones[i].name] = sourceBones[i];
  71931. }
  71932. if (this.bones.length !== sourceBones.length) {
  71933. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  71934. ret = false;
  71935. }
  71936. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  71937. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  71938. var boneName = this.bones[i].name;
  71939. var sourceBone = boneDict[boneName];
  71940. if (sourceBone) {
  71941. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  71942. }
  71943. else {
  71944. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  71945. ret = false;
  71946. }
  71947. }
  71948. // do not call createAnimationRange(), since it also is done to bones, which was already done
  71949. var range = source.getAnimationRange(name);
  71950. if (range) {
  71951. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  71952. }
  71953. return ret;
  71954. };
  71955. Skeleton.prototype.returnToRest = function () {
  71956. for (var index = 0; index < this.bones.length; index++) {
  71957. this.bones[index].returnToRest();
  71958. }
  71959. };
  71960. Skeleton.prototype._getHighestAnimationFrame = function () {
  71961. var ret = 0;
  71962. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  71963. if (this.bones[i].animations[0]) {
  71964. var highest = this.bones[i].animations[0].getHighestFrame();
  71965. if (ret < highest) {
  71966. ret = highest;
  71967. }
  71968. }
  71969. }
  71970. return ret;
  71971. };
  71972. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  71973. var range = this.getAnimationRange(name);
  71974. if (!range) {
  71975. return null;
  71976. }
  71977. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  71978. };
  71979. Skeleton.prototype._markAsDirty = function () {
  71980. this._isDirty = true;
  71981. };
  71982. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  71983. this._meshesWithPoseMatrix.push(mesh);
  71984. };
  71985. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  71986. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  71987. if (index > -1) {
  71988. this._meshesWithPoseMatrix.splice(index, 1);
  71989. }
  71990. };
  71991. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  71992. this.onBeforeComputeObservable.notifyObservers(this);
  71993. for (var index = 0; index < this.bones.length; index++) {
  71994. var bone = this.bones[index];
  71995. var parentBone = bone.getParent();
  71996. if (parentBone) {
  71997. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  71998. }
  71999. else {
  72000. if (initialSkinMatrix) {
  72001. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  72002. }
  72003. else {
  72004. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  72005. }
  72006. }
  72007. if (bone._index !== -1) {
  72008. var mappedIndex = bone._index === null ? index : bone._index;
  72009. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  72010. }
  72011. }
  72012. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  72013. };
  72014. Skeleton.prototype.prepare = function () {
  72015. if (!this._isDirty) {
  72016. return;
  72017. }
  72018. if (this.needInitialSkinMatrix) {
  72019. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  72020. var mesh = this._meshesWithPoseMatrix[index];
  72021. var poseMatrix = mesh.getPoseMatrix();
  72022. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  72023. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  72024. }
  72025. if (this._synchronizedWithMesh !== mesh) {
  72026. this._synchronizedWithMesh = mesh;
  72027. // Prepare bones
  72028. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  72029. var bone = this.bones[boneIndex];
  72030. if (!bone.getParent()) {
  72031. var matrix = bone.getBaseMatrix();
  72032. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  72033. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  72034. }
  72035. }
  72036. }
  72037. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  72038. }
  72039. }
  72040. else {
  72041. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  72042. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  72043. }
  72044. this._computeTransformMatrices(this._transformMatrices, null);
  72045. }
  72046. this._isDirty = false;
  72047. this._scene._activeBones.addCount(this.bones.length, false);
  72048. };
  72049. Skeleton.prototype.getAnimatables = function () {
  72050. if (!this._animatables || this._animatables.length !== this.bones.length) {
  72051. this._animatables = [];
  72052. for (var index = 0; index < this.bones.length; index++) {
  72053. this._animatables.push(this.bones[index]);
  72054. }
  72055. }
  72056. return this._animatables;
  72057. };
  72058. Skeleton.prototype.clone = function (name, id) {
  72059. var result = new Skeleton(name, id || name, this._scene);
  72060. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  72061. for (var index = 0; index < this.bones.length; index++) {
  72062. var source = this.bones[index];
  72063. var parentBone = null;
  72064. var parent_1 = source.getParent();
  72065. if (parent_1) {
  72066. var parentIndex = this.bones.indexOf(parent_1);
  72067. parentBone = result.bones[parentIndex];
  72068. }
  72069. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  72070. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  72071. }
  72072. if (this._ranges) {
  72073. result._ranges = {};
  72074. for (var rangeName in this._ranges) {
  72075. var range = this._ranges[rangeName];
  72076. if (range) {
  72077. result._ranges[rangeName] = range.clone();
  72078. }
  72079. }
  72080. }
  72081. this._isDirty = true;
  72082. return result;
  72083. };
  72084. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  72085. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  72086. this.bones.forEach(function (bone) {
  72087. bone.animations.forEach(function (animation) {
  72088. animation.enableBlending = true;
  72089. animation.blendingSpeed = blendingSpeed;
  72090. });
  72091. });
  72092. };
  72093. Skeleton.prototype.dispose = function () {
  72094. this._meshesWithPoseMatrix = [];
  72095. // Animations
  72096. this.getScene().stopAnimation(this);
  72097. // Remove from scene
  72098. this.getScene().removeSkeleton(this);
  72099. };
  72100. Skeleton.prototype.serialize = function () {
  72101. var serializationObject = {};
  72102. serializationObject.name = this.name;
  72103. serializationObject.id = this.id;
  72104. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  72105. serializationObject.bones = [];
  72106. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  72107. for (var index = 0; index < this.bones.length; index++) {
  72108. var bone = this.bones[index];
  72109. var parent_2 = bone.getParent();
  72110. var serializedBone = {
  72111. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  72112. name: bone.name,
  72113. matrix: bone.getBaseMatrix().toArray(),
  72114. rest: bone.getRestPose().toArray()
  72115. };
  72116. serializationObject.bones.push(serializedBone);
  72117. if (bone.length) {
  72118. serializedBone.length = bone.length;
  72119. }
  72120. if (bone.animations && bone.animations.length > 0) {
  72121. serializedBone.animation = bone.animations[0].serialize();
  72122. }
  72123. serializationObject.ranges = [];
  72124. for (var name in this._ranges) {
  72125. var source = this._ranges[name];
  72126. if (!source) {
  72127. continue;
  72128. }
  72129. var range = {};
  72130. range.name = name;
  72131. range.from = source.from;
  72132. range.to = source.to;
  72133. serializationObject.ranges.push(range);
  72134. }
  72135. }
  72136. return serializationObject;
  72137. };
  72138. Skeleton.Parse = function (parsedSkeleton, scene) {
  72139. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  72140. if (parsedSkeleton.dimensionsAtRest) {
  72141. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  72142. }
  72143. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  72144. var index;
  72145. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  72146. var parsedBone = parsedSkeleton.bones[index];
  72147. var parentBone = null;
  72148. if (parsedBone.parentBoneIndex > -1) {
  72149. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  72150. }
  72151. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  72152. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  72153. if (parsedBone.length) {
  72154. bone.length = parsedBone.length;
  72155. }
  72156. if (parsedBone.animation) {
  72157. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  72158. }
  72159. }
  72160. // placed after bones, so createAnimationRange can cascade down
  72161. if (parsedSkeleton.ranges) {
  72162. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  72163. var data = parsedSkeleton.ranges[index];
  72164. skeleton.createAnimationRange(data.name, data.from, data.to);
  72165. }
  72166. }
  72167. return skeleton;
  72168. };
  72169. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  72170. if (forceUpdate === void 0) { forceUpdate = false; }
  72171. var renderId = this._scene.getRenderId();
  72172. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  72173. this.bones[0].computeAbsoluteTransforms();
  72174. this._lastAbsoluteTransformsUpdateId = renderId;
  72175. }
  72176. };
  72177. Skeleton.prototype.getPoseMatrix = function () {
  72178. var poseMatrix = null;
  72179. if (this._meshesWithPoseMatrix.length > 0) {
  72180. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  72181. }
  72182. return poseMatrix;
  72183. };
  72184. Skeleton.prototype.sortBones = function () {
  72185. var bones = new Array();
  72186. var visited = new Array(this.bones.length);
  72187. for (var index = 0; index < this.bones.length; index++) {
  72188. this._sortBones(index, bones, visited);
  72189. }
  72190. this.bones = bones;
  72191. };
  72192. Skeleton.prototype._sortBones = function (index, bones, visited) {
  72193. if (visited[index]) {
  72194. return;
  72195. }
  72196. visited[index] = true;
  72197. var bone = this.bones[index];
  72198. if (bone._index === undefined) {
  72199. bone._index = index;
  72200. }
  72201. var parentBone = bone.getParent();
  72202. if (parentBone) {
  72203. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  72204. }
  72205. bones.push(bone);
  72206. };
  72207. return Skeleton;
  72208. }());
  72209. BABYLON.Skeleton = Skeleton;
  72210. })(BABYLON || (BABYLON = {}));
  72211. //# sourceMappingURL=babylon.skeleton.js.map
  72212. var BABYLON;
  72213. (function (BABYLON) {
  72214. var SphericalPolynomial = /** @class */ (function () {
  72215. function SphericalPolynomial() {
  72216. this.x = BABYLON.Vector3.Zero();
  72217. this.y = BABYLON.Vector3.Zero();
  72218. this.z = BABYLON.Vector3.Zero();
  72219. this.xx = BABYLON.Vector3.Zero();
  72220. this.yy = BABYLON.Vector3.Zero();
  72221. this.zz = BABYLON.Vector3.Zero();
  72222. this.xy = BABYLON.Vector3.Zero();
  72223. this.yz = BABYLON.Vector3.Zero();
  72224. this.zx = BABYLON.Vector3.Zero();
  72225. }
  72226. SphericalPolynomial.prototype.addAmbient = function (color) {
  72227. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  72228. this.xx = this.xx.add(colorVector);
  72229. this.yy = this.yy.add(colorVector);
  72230. this.zz = this.zz.add(colorVector);
  72231. };
  72232. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  72233. var result = new SphericalPolynomial();
  72234. result.x = harmonics.L11.scale(1.02333);
  72235. result.y = harmonics.L1_1.scale(1.02333);
  72236. result.z = harmonics.L10.scale(1.02333);
  72237. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  72238. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  72239. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  72240. result.yz = harmonics.L2_1.scale(0.858086);
  72241. result.zx = harmonics.L21.scale(0.858086);
  72242. result.xy = harmonics.L2_2.scale(0.858086);
  72243. result.scale(1.0 / Math.PI);
  72244. return result;
  72245. };
  72246. SphericalPolynomial.prototype.scale = function (scale) {
  72247. this.x = this.x.scale(scale);
  72248. this.y = this.y.scale(scale);
  72249. this.z = this.z.scale(scale);
  72250. this.xx = this.xx.scale(scale);
  72251. this.yy = this.yy.scale(scale);
  72252. this.zz = this.zz.scale(scale);
  72253. this.yz = this.yz.scale(scale);
  72254. this.zx = this.zx.scale(scale);
  72255. this.xy = this.xy.scale(scale);
  72256. };
  72257. return SphericalPolynomial;
  72258. }());
  72259. BABYLON.SphericalPolynomial = SphericalPolynomial;
  72260. var SphericalHarmonics = /** @class */ (function () {
  72261. function SphericalHarmonics() {
  72262. this.L00 = BABYLON.Vector3.Zero();
  72263. this.L1_1 = BABYLON.Vector3.Zero();
  72264. this.L10 = BABYLON.Vector3.Zero();
  72265. this.L11 = BABYLON.Vector3.Zero();
  72266. this.L2_2 = BABYLON.Vector3.Zero();
  72267. this.L2_1 = BABYLON.Vector3.Zero();
  72268. this.L20 = BABYLON.Vector3.Zero();
  72269. this.L21 = BABYLON.Vector3.Zero();
  72270. this.L22 = BABYLON.Vector3.Zero();
  72271. }
  72272. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  72273. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  72274. var c = colorVector.scale(deltaSolidAngle);
  72275. this.L00 = this.L00.add(c.scale(0.282095));
  72276. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  72277. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  72278. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  72279. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  72280. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  72281. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  72282. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  72283. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  72284. };
  72285. SphericalHarmonics.prototype.scale = function (scale) {
  72286. this.L00 = this.L00.scale(scale);
  72287. this.L1_1 = this.L1_1.scale(scale);
  72288. this.L10 = this.L10.scale(scale);
  72289. this.L11 = this.L11.scale(scale);
  72290. this.L2_2 = this.L2_2.scale(scale);
  72291. this.L2_1 = this.L2_1.scale(scale);
  72292. this.L20 = this.L20.scale(scale);
  72293. this.L21 = this.L21.scale(scale);
  72294. this.L22 = this.L22.scale(scale);
  72295. };
  72296. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  72297. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  72298. //
  72299. // E_lm = A_l * L_lm
  72300. //
  72301. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  72302. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  72303. // the scaling factors are given in equation 9.
  72304. // Constant (Band 0)
  72305. this.L00 = this.L00.scale(3.141593);
  72306. // Linear (Band 1)
  72307. this.L1_1 = this.L1_1.scale(2.094395);
  72308. this.L10 = this.L10.scale(2.094395);
  72309. this.L11 = this.L11.scale(2.094395);
  72310. // Quadratic (Band 2)
  72311. this.L2_2 = this.L2_2.scale(0.785398);
  72312. this.L2_1 = this.L2_1.scale(0.785398);
  72313. this.L20 = this.L20.scale(0.785398);
  72314. this.L21 = this.L21.scale(0.785398);
  72315. this.L22 = this.L22.scale(0.785398);
  72316. };
  72317. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  72318. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  72319. // L = (1/pi) * E * rho
  72320. //
  72321. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  72322. this.scale(1.0 / Math.PI);
  72323. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  72324. // (The pixel shader must apply albedo after texture fetches, etc).
  72325. };
  72326. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  72327. var result = new SphericalHarmonics();
  72328. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  72329. result.L1_1 = polynomial.y.scale(0.977204);
  72330. result.L10 = polynomial.z.scale(0.977204);
  72331. result.L11 = polynomial.x.scale(0.977204);
  72332. result.L2_2 = polynomial.xy.scale(1.16538);
  72333. result.L2_1 = polynomial.yz.scale(1.16538);
  72334. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  72335. result.L21 = polynomial.zx.scale(1.16538);
  72336. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  72337. result.scale(Math.PI);
  72338. return result;
  72339. };
  72340. return SphericalHarmonics;
  72341. }());
  72342. BABYLON.SphericalHarmonics = SphericalHarmonics;
  72343. })(BABYLON || (BABYLON = {}));
  72344. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  72345. var BABYLON;
  72346. (function (BABYLON) {
  72347. var FileFaceOrientation = /** @class */ (function () {
  72348. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  72349. this.name = name;
  72350. this.worldAxisForNormal = worldAxisForNormal;
  72351. this.worldAxisForFileX = worldAxisForFileX;
  72352. this.worldAxisForFileY = worldAxisForFileY;
  72353. }
  72354. return FileFaceOrientation;
  72355. }());
  72356. ;
  72357. /**
  72358. * Helper class dealing with the extraction of spherical polynomial dataArray
  72359. * from a cube map.
  72360. */
  72361. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  72362. function CubeMapToSphericalPolynomialTools() {
  72363. }
  72364. /**
  72365. * Converts a texture to the according Spherical Polynomial data.
  72366. * This extracts the first 3 orders only as they are the only one used in the lighting.
  72367. *
  72368. * @param texture The texture to extract the information from.
  72369. * @return The Spherical Polynomial data.
  72370. */
  72371. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  72372. if (!texture.isCube) {
  72373. // Only supports cube Textures currently.
  72374. return null;
  72375. }
  72376. var size = texture.getSize().width;
  72377. var right = texture.readPixels(0);
  72378. var left = texture.readPixels(1);
  72379. var up;
  72380. var down;
  72381. if (texture.isRenderTarget) {
  72382. up = texture.readPixels(3);
  72383. down = texture.readPixels(2);
  72384. }
  72385. else {
  72386. up = texture.readPixels(2);
  72387. down = texture.readPixels(3);
  72388. }
  72389. var front = texture.readPixels(4);
  72390. var back = texture.readPixels(5);
  72391. var gammaSpace = texture.gammaSpace;
  72392. // Always read as RGBA.
  72393. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  72394. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  72395. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  72396. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  72397. }
  72398. var cubeInfo = {
  72399. size: size,
  72400. right: right,
  72401. left: left,
  72402. up: up,
  72403. down: down,
  72404. front: front,
  72405. back: back,
  72406. format: format,
  72407. type: type,
  72408. gammaSpace: gammaSpace,
  72409. };
  72410. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  72411. };
  72412. /**
  72413. * Converts a cubemap to the according Spherical Polynomial data.
  72414. * This extracts the first 3 orders only as they are the only one used in the lighting.
  72415. *
  72416. * @param cubeInfo The Cube map to extract the information from.
  72417. * @return The Spherical Polynomial data.
  72418. */
  72419. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  72420. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  72421. var totalSolidAngle = 0.0;
  72422. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  72423. var du = 2.0 / cubeInfo.size;
  72424. var dv = du;
  72425. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  72426. var minUV = du * 0.5 - 1.0;
  72427. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  72428. var fileFace = this.FileFaces[faceIndex];
  72429. var dataArray = cubeInfo[fileFace.name];
  72430. var v = minUV;
  72431. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  72432. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  72433. // Because SP is still linear, so summation is fine in that basis.
  72434. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  72435. for (var y = 0; y < cubeInfo.size; y++) {
  72436. var u = minUV;
  72437. for (var x = 0; x < cubeInfo.size; x++) {
  72438. // World direction (not normalised)
  72439. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  72440. worldDirection.normalize();
  72441. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  72442. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  72443. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  72444. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  72445. // Handle Integer types.
  72446. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  72447. r /= 255;
  72448. g /= 255;
  72449. b /= 255;
  72450. }
  72451. // Handle Gamma space textures.
  72452. if (cubeInfo.gammaSpace) {
  72453. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  72454. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  72455. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  72456. }
  72457. var color = new BABYLON.Color3(r, g, b);
  72458. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  72459. totalSolidAngle += deltaSolidAngle;
  72460. u += du;
  72461. }
  72462. v += dv;
  72463. }
  72464. }
  72465. // Solid angle for entire sphere is 4*pi
  72466. var sphereSolidAngle = 4.0 * Math.PI;
  72467. // Adjust the solid angle to allow for how many faces we processed.
  72468. var facesProcessed = 6.0;
  72469. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  72470. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  72471. // This is needed because the numerical integration over the cube uses a
  72472. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  72473. // and also to compensate for accumulative error due to float precision in the summation.
  72474. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  72475. sphericalHarmonics.scale(correctionFactor);
  72476. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  72477. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  72478. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  72479. };
  72480. CubeMapToSphericalPolynomialTools.FileFaces = [
  72481. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  72482. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  72483. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  72484. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  72485. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  72486. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  72487. ];
  72488. return CubeMapToSphericalPolynomialTools;
  72489. }());
  72490. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  72491. })(BABYLON || (BABYLON = {}));
  72492. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  72493. var BABYLON;
  72494. (function (BABYLON) {
  72495. /**
  72496. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  72497. */
  72498. var PanoramaToCubeMapTools = /** @class */ (function () {
  72499. function PanoramaToCubeMapTools() {
  72500. }
  72501. /**
  72502. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  72503. *
  72504. * @param float32Array The source data.
  72505. * @param inputWidth The width of the input panorama.
  72506. * @param inputhHeight The height of the input panorama.
  72507. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  72508. * @return The cubemap data
  72509. */
  72510. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  72511. if (!float32Array) {
  72512. throw "ConvertPanoramaToCubemap: input cannot be null";
  72513. }
  72514. if (float32Array.length != inputWidth * inputHeight * 3) {
  72515. throw "ConvertPanoramaToCubemap: input size is wrong";
  72516. }
  72517. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  72518. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  72519. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  72520. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  72521. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  72522. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  72523. return {
  72524. front: textureFront,
  72525. back: textureBack,
  72526. left: textureLeft,
  72527. right: textureRight,
  72528. up: textureUp,
  72529. down: textureDown,
  72530. size: size,
  72531. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  72532. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  72533. gammaSpace: false,
  72534. };
  72535. };
  72536. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  72537. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  72538. var textureArray = new Float32Array(buffer);
  72539. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  72540. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  72541. var dy = 1 / texSize;
  72542. var fy = 0;
  72543. for (var y = 0; y < texSize; y++) {
  72544. var xv1 = faceData[0];
  72545. var xv2 = faceData[2];
  72546. for (var x = 0; x < texSize; x++) {
  72547. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  72548. v.normalize();
  72549. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  72550. // 3 channels per pixels
  72551. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  72552. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  72553. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  72554. xv1 = xv1.add(rotDX1);
  72555. xv2 = xv2.add(rotDX2);
  72556. }
  72557. fy += dy;
  72558. }
  72559. return textureArray;
  72560. };
  72561. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  72562. var theta = Math.atan2(vDir.z, vDir.x);
  72563. var phi = Math.acos(vDir.y);
  72564. while (theta < -Math.PI)
  72565. theta += 2 * Math.PI;
  72566. while (theta > Math.PI)
  72567. theta -= 2 * Math.PI;
  72568. var dx = theta / Math.PI;
  72569. var dy = phi / Math.PI;
  72570. // recenter.
  72571. dx = dx * 0.5 + 0.5;
  72572. var px = Math.round(dx * inputWidth);
  72573. if (px < 0)
  72574. px = 0;
  72575. else if (px >= inputWidth)
  72576. px = inputWidth - 1;
  72577. var py = Math.round(dy * inputHeight);
  72578. if (py < 0)
  72579. py = 0;
  72580. else if (py >= inputHeight)
  72581. py = inputHeight - 1;
  72582. var inputY = (inputHeight - py - 1);
  72583. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  72584. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  72585. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  72586. return {
  72587. r: r,
  72588. g: g,
  72589. b: b
  72590. };
  72591. };
  72592. PanoramaToCubeMapTools.FACE_FRONT = [
  72593. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  72594. new BABYLON.Vector3(1.0, -1.0, -1.0),
  72595. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  72596. new BABYLON.Vector3(1.0, 1.0, -1.0)
  72597. ];
  72598. PanoramaToCubeMapTools.FACE_BACK = [
  72599. new BABYLON.Vector3(1.0, -1.0, 1.0),
  72600. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  72601. new BABYLON.Vector3(1.0, 1.0, 1.0),
  72602. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  72603. ];
  72604. PanoramaToCubeMapTools.FACE_RIGHT = [
  72605. new BABYLON.Vector3(1.0, -1.0, -1.0),
  72606. new BABYLON.Vector3(1.0, -1.0, 1.0),
  72607. new BABYLON.Vector3(1.0, 1.0, -1.0),
  72608. new BABYLON.Vector3(1.0, 1.0, 1.0)
  72609. ];
  72610. PanoramaToCubeMapTools.FACE_LEFT = [
  72611. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  72612. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  72613. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  72614. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  72615. ];
  72616. PanoramaToCubeMapTools.FACE_DOWN = [
  72617. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  72618. new BABYLON.Vector3(1.0, 1.0, -1.0),
  72619. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  72620. new BABYLON.Vector3(1.0, 1.0, 1.0)
  72621. ];
  72622. PanoramaToCubeMapTools.FACE_UP = [
  72623. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  72624. new BABYLON.Vector3(1.0, -1.0, 1.0),
  72625. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  72626. new BABYLON.Vector3(1.0, -1.0, -1.0)
  72627. ];
  72628. return PanoramaToCubeMapTools;
  72629. }());
  72630. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  72631. })(BABYLON || (BABYLON = {}));
  72632. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  72633. var BABYLON;
  72634. (function (BABYLON) {
  72635. ;
  72636. /**
  72637. * This groups tools to convert HDR texture to native colors array.
  72638. */
  72639. var HDRTools = /** @class */ (function () {
  72640. function HDRTools() {
  72641. }
  72642. HDRTools.Ldexp = function (mantissa, exponent) {
  72643. if (exponent > 1023) {
  72644. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  72645. }
  72646. if (exponent < -1074) {
  72647. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  72648. }
  72649. return mantissa * Math.pow(2, exponent);
  72650. };
  72651. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  72652. if (exponent > 0) {
  72653. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  72654. float32array[index + 0] = red * exponent;
  72655. float32array[index + 1] = green * exponent;
  72656. float32array[index + 2] = blue * exponent;
  72657. }
  72658. else {
  72659. float32array[index + 0] = 0;
  72660. float32array[index + 1] = 0;
  72661. float32array[index + 2] = 0;
  72662. }
  72663. };
  72664. HDRTools.readStringLine = function (uint8array, startIndex) {
  72665. var line = "";
  72666. var character = "";
  72667. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  72668. character = String.fromCharCode(uint8array[i]);
  72669. if (character == "\n") {
  72670. break;
  72671. }
  72672. line += character;
  72673. }
  72674. return line;
  72675. };
  72676. /**
  72677. * Reads header information from an RGBE texture stored in a native array.
  72678. * More information on this format are available here:
  72679. * https://en.wikipedia.org/wiki/RGBE_image_format
  72680. *
  72681. * @param uint8array The binary file stored in native array.
  72682. * @return The header information.
  72683. */
  72684. HDRTools.RGBE_ReadHeader = function (uint8array) {
  72685. var height = 0;
  72686. var width = 0;
  72687. var line = this.readStringLine(uint8array, 0);
  72688. if (line[0] != '#' || line[1] != '?') {
  72689. throw "Bad HDR Format.";
  72690. }
  72691. var endOfHeader = false;
  72692. var findFormat = false;
  72693. var lineIndex = 0;
  72694. do {
  72695. lineIndex += (line.length + 1);
  72696. line = this.readStringLine(uint8array, lineIndex);
  72697. if (line == "FORMAT=32-bit_rle_rgbe") {
  72698. findFormat = true;
  72699. }
  72700. else if (line.length == 0) {
  72701. endOfHeader = true;
  72702. }
  72703. } while (!endOfHeader);
  72704. if (!findFormat) {
  72705. throw "HDR Bad header format, unsupported FORMAT";
  72706. }
  72707. lineIndex += (line.length + 1);
  72708. line = this.readStringLine(uint8array, lineIndex);
  72709. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  72710. var match = sizeRegexp.exec(line);
  72711. // TODO. Support +Y and -X if needed.
  72712. if (!match || match.length < 3) {
  72713. throw "HDR Bad header format, no size";
  72714. }
  72715. width = parseInt(match[2]);
  72716. height = parseInt(match[1]);
  72717. if (width < 8 || width > 0x7fff) {
  72718. throw "HDR Bad header format, unsupported size";
  72719. }
  72720. lineIndex += (line.length + 1);
  72721. return {
  72722. height: height,
  72723. width: width,
  72724. dataPosition: lineIndex
  72725. };
  72726. };
  72727. /**
  72728. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  72729. * This RGBE texture needs to store the information as a panorama.
  72730. *
  72731. * More information on this format are available here:
  72732. * https://en.wikipedia.org/wiki/RGBE_image_format
  72733. *
  72734. * @param buffer The binary file stored in an array buffer.
  72735. * @param size The expected size of the extracted cubemap.
  72736. * @return The Cube Map information.
  72737. */
  72738. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  72739. var uint8array = new Uint8Array(buffer);
  72740. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  72741. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  72742. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  72743. return cubeMapData;
  72744. };
  72745. /**
  72746. * Returns the pixels data extracted from an RGBE texture.
  72747. * This pixels will be stored left to right up to down in the R G B order in one array.
  72748. *
  72749. * More information on this format are available here:
  72750. * https://en.wikipedia.org/wiki/RGBE_image_format
  72751. *
  72752. * @param uint8array The binary file stored in an array buffer.
  72753. * @param hdrInfo The header information of the file.
  72754. * @return The pixels data in RGB right to left up to down order.
  72755. */
  72756. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  72757. // Keep for multi format supports.
  72758. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  72759. };
  72760. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  72761. var num_scanlines = hdrInfo.height;
  72762. var scanline_width = hdrInfo.width;
  72763. var a, b, c, d, count;
  72764. var dataIndex = hdrInfo.dataPosition;
  72765. var index = 0, endIndex = 0, i = 0;
  72766. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  72767. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  72768. // 3 channels of 4 bytes per pixel in float.
  72769. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  72770. var resultArray = new Float32Array(resultBuffer);
  72771. // read in each successive scanline
  72772. while (num_scanlines > 0) {
  72773. a = uint8array[dataIndex++];
  72774. b = uint8array[dataIndex++];
  72775. c = uint8array[dataIndex++];
  72776. d = uint8array[dataIndex++];
  72777. if (a != 2 || b != 2 || (c & 0x80)) {
  72778. // this file is not run length encoded
  72779. throw "HDR Bad header format, not RLE";
  72780. }
  72781. if (((c << 8) | d) != scanline_width) {
  72782. throw "HDR Bad header format, wrong scan line width";
  72783. }
  72784. index = 0;
  72785. // read each of the four channels for the scanline into the buffer
  72786. for (i = 0; i < 4; i++) {
  72787. endIndex = (i + 1) * scanline_width;
  72788. while (index < endIndex) {
  72789. a = uint8array[dataIndex++];
  72790. b = uint8array[dataIndex++];
  72791. if (a > 128) {
  72792. // a run of the same value
  72793. count = a - 128;
  72794. if ((count == 0) || (count > endIndex - index)) {
  72795. throw "HDR Bad Format, bad scanline data (run)";
  72796. }
  72797. while (count-- > 0) {
  72798. scanLineArray[index++] = b;
  72799. }
  72800. }
  72801. else {
  72802. // a non-run
  72803. count = a;
  72804. if ((count == 0) || (count > endIndex - index)) {
  72805. throw "HDR Bad Format, bad scanline data (non-run)";
  72806. }
  72807. scanLineArray[index++] = b;
  72808. if (--count > 0) {
  72809. for (var j = 0; j < count; j++) {
  72810. scanLineArray[index++] = uint8array[dataIndex++];
  72811. }
  72812. }
  72813. }
  72814. }
  72815. }
  72816. // now convert data from buffer into floats
  72817. for (i = 0; i < scanline_width; i++) {
  72818. a = scanLineArray[i];
  72819. b = scanLineArray[i + scanline_width];
  72820. c = scanLineArray[i + 2 * scanline_width];
  72821. d = scanLineArray[i + 3 * scanline_width];
  72822. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  72823. }
  72824. num_scanlines--;
  72825. }
  72826. return resultArray;
  72827. };
  72828. return HDRTools;
  72829. }());
  72830. BABYLON.HDRTools = HDRTools;
  72831. })(BABYLON || (BABYLON = {}));
  72832. //# sourceMappingURL=babylon.hdr.js.map
  72833. var BABYLON;
  72834. (function (BABYLON) {
  72835. /**
  72836. * This represents a texture coming from an HDR input.
  72837. *
  72838. * The only supported format is currently panorama picture stored in RGBE format.
  72839. * Example of such files can be found on HDRLib: http://hdrlib.com/
  72840. */
  72841. var HDRCubeTexture = /** @class */ (function (_super) {
  72842. __extends(HDRCubeTexture, _super);
  72843. /**
  72844. * Instantiates an HDRTexture from the following parameters.
  72845. *
  72846. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  72847. * @param scene The scene the texture will be used in
  72848. * @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.
  72849. * @param noMipmap Forces to not generate the mipmap if true
  72850. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  72851. * @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)
  72852. * @param usePMREMGenerator Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  72853. */
  72854. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  72855. if (noMipmap === void 0) { noMipmap = false; }
  72856. if (generateHarmonics === void 0) { generateHarmonics = true; }
  72857. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  72858. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  72859. if (onLoad === void 0) { onLoad = null; }
  72860. if (onError === void 0) { onError = null; }
  72861. var _this = _super.call(this, scene) || this;
  72862. _this._useInGammaSpace = false;
  72863. _this._generateHarmonics = true;
  72864. _this._isBABYLONPreprocessed = false;
  72865. _this._onLoad = null;
  72866. _this._onError = null;
  72867. /**
  72868. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  72869. */
  72870. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  72871. /**
  72872. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  72873. * This is usefull at run time to apply the good shader.
  72874. */
  72875. _this.isPMREM = false;
  72876. _this._isBlocking = true;
  72877. /**
  72878. * Gets or sets the center of the bounding box associated with the cube texture
  72879. * It must define where the camera used to render the texture was set
  72880. */
  72881. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  72882. if (!url) {
  72883. return _this;
  72884. }
  72885. _this.name = url;
  72886. _this.url = url;
  72887. _this.hasAlpha = false;
  72888. _this.isCube = true;
  72889. _this._textureMatrix = BABYLON.Matrix.Identity();
  72890. _this._onLoad = onLoad;
  72891. _this._onError = onError;
  72892. _this.gammaSpace = false;
  72893. var caps = scene.getEngine().getCaps();
  72894. if (size) {
  72895. _this._isBABYLONPreprocessed = false;
  72896. _this._noMipmap = noMipmap;
  72897. _this._size = size;
  72898. _this._useInGammaSpace = useInGammaSpace;
  72899. _this._usePMREMGenerator = usePMREMGenerator &&
  72900. caps.textureLOD &&
  72901. caps.textureFloat &&
  72902. !_this._useInGammaSpace;
  72903. }
  72904. else {
  72905. _this._isBABYLONPreprocessed = true;
  72906. _this._noMipmap = false;
  72907. _this._useInGammaSpace = false;
  72908. _this._usePMREMGenerator = caps.textureLOD && caps.textureFloat &&
  72909. !_this._useInGammaSpace;
  72910. }
  72911. _this.isPMREM = _this._usePMREMGenerator;
  72912. _this._texture = _this._getFromCache(url, _this._noMipmap);
  72913. if (!_this._texture) {
  72914. if (!scene.useDelayedTextureLoading) {
  72915. _this.loadTexture();
  72916. }
  72917. else {
  72918. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  72919. }
  72920. }
  72921. return _this;
  72922. }
  72923. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  72924. /**
  72925. * Gets wether or not the texture is blocking during loading.
  72926. */
  72927. get: function () {
  72928. return this._isBlocking;
  72929. },
  72930. /**
  72931. * Sets wether or not the texture is blocking during loading.
  72932. */
  72933. set: function (value) {
  72934. this._isBlocking = value;
  72935. },
  72936. enumerable: true,
  72937. configurable: true
  72938. });
  72939. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  72940. get: function () {
  72941. return this._boundingBoxSize;
  72942. },
  72943. /**
  72944. * Gets or sets the size of the bounding box associated with the cube texture
  72945. * When defined, the cubemap will switch to local mode
  72946. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  72947. * @example https://www.babylonjs-playground.com/#RNASML
  72948. */
  72949. set: function (value) {
  72950. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  72951. return;
  72952. }
  72953. this._boundingBoxSize = value;
  72954. var scene = this.getScene();
  72955. if (scene) {
  72956. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  72957. }
  72958. },
  72959. enumerable: true,
  72960. configurable: true
  72961. });
  72962. /**
  72963. * Occurs when the file is a preprocessed .babylon.hdr file.
  72964. */
  72965. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  72966. var _this = this;
  72967. var mipLevels = 0;
  72968. var floatArrayView = null;
  72969. var scene = this.getScene();
  72970. var mipmapGenerator = (!this._useInGammaSpace && scene && scene.getEngine().getCaps().textureFloat) ? function (data) {
  72971. var mips = new Array();
  72972. if (!floatArrayView) {
  72973. return mips;
  72974. }
  72975. var startIndex = 30;
  72976. for (var level = 0; level < mipLevels; level++) {
  72977. mips.push([]);
  72978. // Fill each pixel of the mip level.
  72979. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  72980. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  72981. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  72982. mips[level].push(faceData);
  72983. startIndex += faceSize;
  72984. }
  72985. }
  72986. return mips;
  72987. } : null;
  72988. var callback = function (buffer) {
  72989. var scene = _this.getScene();
  72990. if (!scene) {
  72991. return null;
  72992. }
  72993. // Create Native Array Views
  72994. var intArrayView = new Int32Array(buffer);
  72995. floatArrayView = new Float32Array(buffer);
  72996. // Fill header.
  72997. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  72998. _this._size = intArrayView[1]; // CubeMap max mip face size.
  72999. // Update Texture Information.
  73000. if (!_this._texture) {
  73001. return null;
  73002. }
  73003. _this._texture.updateSize(_this._size, _this._size);
  73004. // Fill polynomial information.
  73005. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  73006. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  73007. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  73008. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  73009. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  73010. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  73011. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  73012. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  73013. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  73014. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  73015. _this.sphericalPolynomial = sphericalPolynomial;
  73016. // Fill pixel data.
  73017. mipLevels = intArrayView[29]; // Number of mip levels.
  73018. var startIndex = 30;
  73019. var data = [];
  73020. var faceSize = Math.pow(_this._size, 2) * 3;
  73021. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  73022. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  73023. startIndex += faceSize;
  73024. }
  73025. var results = [];
  73026. var byteArray = null;
  73027. // Push each faces.
  73028. for (var k = 0; k < 6; k++) {
  73029. var dataFace = null;
  73030. // To be deprecated.
  73031. if (version === 1) {
  73032. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  73033. dataFace = data[j];
  73034. }
  73035. // If special cases.
  73036. if (!mipmapGenerator && dataFace) {
  73037. if (!scene.getEngine().getCaps().textureFloat) {
  73038. // 3 channels of 1 bytes per pixel in bytes.
  73039. var byteBuffer = new ArrayBuffer(faceSize);
  73040. byteArray = new Uint8Array(byteBuffer);
  73041. }
  73042. for (var i = 0; i < _this._size * _this._size; i++) {
  73043. // Put in gamma space if requested.
  73044. if (_this._useInGammaSpace) {
  73045. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  73046. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  73047. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  73048. }
  73049. // Convert to int texture for fallback.
  73050. if (byteArray) {
  73051. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  73052. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  73053. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  73054. // May use luminance instead if the result is not accurate.
  73055. var max = Math.max(Math.max(r, g), b);
  73056. if (max > 255) {
  73057. var scale = 255 / max;
  73058. r *= scale;
  73059. g *= scale;
  73060. b *= scale;
  73061. }
  73062. byteArray[(i * 3) + 0] = r;
  73063. byteArray[(i * 3) + 1] = g;
  73064. byteArray[(i * 3) + 2] = b;
  73065. }
  73066. }
  73067. }
  73068. // Fill the array accordingly.
  73069. if (byteArray) {
  73070. results.push(byteArray);
  73071. }
  73072. else {
  73073. results.push(dataFace);
  73074. }
  73075. }
  73076. return results;
  73077. };
  73078. if (scene) {
  73079. 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);
  73080. }
  73081. };
  73082. /**
  73083. * Occurs when the file is raw .hdr file.
  73084. */
  73085. HDRCubeTexture.prototype.loadHDRTexture = function () {
  73086. var _this = this;
  73087. var callback = function (buffer) {
  73088. var scene = _this.getScene();
  73089. if (!scene) {
  73090. return null;
  73091. }
  73092. // Extract the raw linear data.
  73093. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  73094. // Generate harmonics if needed.
  73095. if (_this._generateHarmonics) {
  73096. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  73097. _this.sphericalPolynomial = sphericalPolynomial;
  73098. }
  73099. var results = [];
  73100. var byteArray = null;
  73101. // Push each faces.
  73102. for (var j = 0; j < 6; j++) {
  73103. // Create uintarray fallback.
  73104. if (!scene.getEngine().getCaps().textureFloat) {
  73105. // 3 channels of 1 bytes per pixel in bytes.
  73106. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  73107. byteArray = new Uint8Array(byteBuffer);
  73108. }
  73109. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  73110. // If special cases.
  73111. if (_this._useInGammaSpace || byteArray) {
  73112. for (var i = 0; i < _this._size * _this._size; i++) {
  73113. // Put in gamma space if requested.
  73114. if (_this._useInGammaSpace) {
  73115. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  73116. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  73117. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  73118. }
  73119. // Convert to int texture for fallback.
  73120. if (byteArray) {
  73121. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  73122. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  73123. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  73124. // May use luminance instead if the result is not accurate.
  73125. var max = Math.max(Math.max(r, g), b);
  73126. if (max > 255) {
  73127. var scale = 255 / max;
  73128. r *= scale;
  73129. g *= scale;
  73130. b *= scale;
  73131. }
  73132. byteArray[(i * 3) + 0] = r;
  73133. byteArray[(i * 3) + 1] = g;
  73134. byteArray[(i * 3) + 2] = b;
  73135. }
  73136. }
  73137. }
  73138. if (byteArray) {
  73139. results.push(byteArray);
  73140. }
  73141. else {
  73142. results.push(dataFace);
  73143. }
  73144. }
  73145. return results;
  73146. };
  73147. var mipmapGenerator = null;
  73148. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  73149. // if (!this._noMipmap &&
  73150. // this._usePMREMGenerator) {
  73151. // mipmapGenerator = (data: ArrayBufferView[]) => {
  73152. // // Custom setup of the generator matching with the PBR shader values.
  73153. // var generator = new BABYLON.PMREMGenerator(data,
  73154. // this._size,
  73155. // this._size,
  73156. // 0,
  73157. // 3,
  73158. // this.getScene().getEngine().getCaps().textureFloat,
  73159. // 2048,
  73160. // 0.25,
  73161. // false,
  73162. // true);
  73163. // return generator.filterCubeMap();
  73164. // };
  73165. // }
  73166. var scene = this.getScene();
  73167. if (scene) {
  73168. 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);
  73169. }
  73170. };
  73171. /**
  73172. * Starts the loading process of the texture.
  73173. */
  73174. HDRCubeTexture.prototype.loadTexture = function () {
  73175. if (this._isBABYLONPreprocessed) {
  73176. this.loadBabylonTexture();
  73177. }
  73178. else {
  73179. this.loadHDRTexture();
  73180. }
  73181. };
  73182. HDRCubeTexture.prototype.clone = function () {
  73183. var scene = this.getScene();
  73184. if (!scene) {
  73185. return this;
  73186. }
  73187. var size = (this._isBABYLONPreprocessed ? null : this._size);
  73188. var newTexture = new HDRCubeTexture(this.url, scene, size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  73189. // Base texture
  73190. newTexture.level = this.level;
  73191. newTexture.wrapU = this.wrapU;
  73192. newTexture.wrapV = this.wrapV;
  73193. newTexture.coordinatesIndex = this.coordinatesIndex;
  73194. newTexture.coordinatesMode = this.coordinatesMode;
  73195. return newTexture;
  73196. };
  73197. // Methods
  73198. HDRCubeTexture.prototype.delayLoad = function () {
  73199. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  73200. return;
  73201. }
  73202. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  73203. this._texture = this._getFromCache(this.url, this._noMipmap);
  73204. if (!this._texture) {
  73205. this.loadTexture();
  73206. }
  73207. };
  73208. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  73209. return this._textureMatrix;
  73210. };
  73211. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  73212. this._textureMatrix = value;
  73213. };
  73214. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  73215. var texture = null;
  73216. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  73217. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  73218. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  73219. texture.name = parsedTexture.name;
  73220. texture.hasAlpha = parsedTexture.hasAlpha;
  73221. texture.level = parsedTexture.level;
  73222. texture.coordinatesMode = parsedTexture.coordinatesMode;
  73223. texture.isBlocking = parsedTexture.isBlocking;
  73224. }
  73225. if (texture) {
  73226. if (parsedTexture.boundingBoxPosition) {
  73227. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  73228. }
  73229. if (parsedTexture.boundingBoxSize) {
  73230. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  73231. }
  73232. }
  73233. return texture;
  73234. };
  73235. HDRCubeTexture.prototype.serialize = function () {
  73236. if (!this.name) {
  73237. return null;
  73238. }
  73239. var serializationObject = {};
  73240. serializationObject.name = this.name;
  73241. serializationObject.hasAlpha = this.hasAlpha;
  73242. serializationObject.isCube = true;
  73243. serializationObject.level = this.level;
  73244. serializationObject.size = this._size;
  73245. serializationObject.coordinatesMode = this.coordinatesMode;
  73246. serializationObject.useInGammaSpace = this._useInGammaSpace;
  73247. serializationObject.generateHarmonics = this._generateHarmonics;
  73248. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  73249. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  73250. serializationObject.customType = "BABYLON.HDRCubeTexture";
  73251. serializationObject.noMipmap = this._noMipmap;
  73252. serializationObject.isBlocking = this._isBlocking;
  73253. return serializationObject;
  73254. };
  73255. /**
  73256. * Saves as a file the data contained in the texture in a binary format.
  73257. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  73258. * as the spherical used in the lighting.
  73259. * @param url The HDR file url.
  73260. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  73261. * @param onError Method called if any error happens during download.
  73262. * @return The packed binary data.
  73263. */
  73264. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  73265. if (onError === void 0) { onError = null; }
  73266. var callback = function (buffer) {
  73267. var data = new Blob([buffer], { type: 'application/octet-stream' });
  73268. // Returns a URL you can use as a href.
  73269. var objUrl = window.URL.createObjectURL(data);
  73270. // Simulates a link to it and click to dowload.
  73271. var a = document.createElement("a");
  73272. document.body.appendChild(a);
  73273. a.style.display = "none";
  73274. a.href = objUrl;
  73275. a.download = "envmap.babylon.hdr";
  73276. a.click();
  73277. };
  73278. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  73279. };
  73280. /**
  73281. * Serializes the data contained in the texture in a binary format.
  73282. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  73283. * as the spherical used in the lighting.
  73284. * @param url The HDR file url.
  73285. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  73286. * @param onError Method called if any error happens during download.
  73287. * @return The packed binary data.
  73288. */
  73289. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  73290. if (onError === void 0) { onError = null; }
  73291. // Needs the url tho create the texture.
  73292. if (!url) {
  73293. return;
  73294. }
  73295. // Check Power of two size.
  73296. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  73297. return;
  73298. }
  73299. // Coming Back in 3.x.
  73300. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.2.");
  73301. };
  73302. HDRCubeTexture._facesMapping = [
  73303. "right",
  73304. "left",
  73305. "up",
  73306. "down",
  73307. "front",
  73308. "back"
  73309. ];
  73310. return HDRCubeTexture;
  73311. }(BABYLON.BaseTexture));
  73312. BABYLON.HDRCubeTexture = HDRCubeTexture;
  73313. })(BABYLON || (BABYLON = {}));
  73314. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  73315. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  73316. // Huge respect for a such great lib.
  73317. // Earcut license:
  73318. // Copyright (c) 2016, Mapbox
  73319. //
  73320. // Permission to use, copy, modify, and/or distribute this software for any purpose
  73321. // with or without fee is hereby granted, provided that the above copyright notice
  73322. // and this permission notice appear in all copies.
  73323. //
  73324. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  73325. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  73326. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  73327. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  73328. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  73329. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  73330. // THIS SOFTWARE.
  73331. var Earcut;
  73332. (function (Earcut) {
  73333. /**
  73334. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  73335. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  73336. * @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).
  73337. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  73338. */
  73339. function earcut(data, holeIndices, dim) {
  73340. dim = dim || 2;
  73341. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = new Array();
  73342. if (!outerNode)
  73343. return triangles;
  73344. var minX = 0, minY = 0, maxX, maxY, x, y, size = 0;
  73345. if (hasHoles)
  73346. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  73347. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  73348. if (data.length > 80 * dim) {
  73349. minX = maxX = data[0];
  73350. minY = maxY = data[1];
  73351. for (var i = dim; i < outerLen; i += dim) {
  73352. x = data[i];
  73353. y = data[i + 1];
  73354. if (x < minX)
  73355. minX = x;
  73356. if (y < minY)
  73357. minY = y;
  73358. if (x > maxX)
  73359. maxX = x;
  73360. if (y > maxY)
  73361. maxY = y;
  73362. }
  73363. // minX, minY and size are later used to transform coords into integers for z-order calculation
  73364. size = Math.max(maxX - minX, maxY - minY);
  73365. }
  73366. earcutLinked(outerNode, triangles, dim, minX, minY, size, 0);
  73367. return triangles;
  73368. }
  73369. Earcut.earcut = earcut;
  73370. var Node = /** @class */ (function () {
  73371. function Node(i, x, y) {
  73372. this.i = i;
  73373. this.x = x;
  73374. this.y = y;
  73375. this.prev = null;
  73376. this.next = null;
  73377. this.z = null;
  73378. this.prevZ = null;
  73379. this.nextZ = null;
  73380. this.steiner = false;
  73381. }
  73382. return Node;
  73383. }());
  73384. // create a circular doubly linked list from polygon points in the specified winding order
  73385. function linkedList(data, start, end, dim, clockwise) {
  73386. var i, last = null;
  73387. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  73388. for (i = start; i < end; i += dim)
  73389. last = insertNode(i, data[i], data[i + 1], last);
  73390. }
  73391. else {
  73392. for (i = end - dim; i >= start; i -= dim)
  73393. last = insertNode(i, data[i], data[i + 1], last);
  73394. }
  73395. if (last && equals(last, last.next)) {
  73396. removeNode(last);
  73397. last = last.next;
  73398. }
  73399. return last;
  73400. }
  73401. // eliminate colinear or duplicate points
  73402. function filterPoints(start, end) {
  73403. if (!start)
  73404. return start;
  73405. if (!end)
  73406. end = start;
  73407. var p = start, again;
  73408. do {
  73409. again = false;
  73410. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  73411. removeNode(p);
  73412. p = end = p.prev;
  73413. if (p === p.next)
  73414. return undefined;
  73415. again = true;
  73416. }
  73417. else {
  73418. p = p.next;
  73419. }
  73420. } while (again || p !== end);
  73421. return end;
  73422. }
  73423. // main ear slicing loop which triangulates a polygon (given as a linked list)
  73424. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  73425. if (!ear)
  73426. return;
  73427. // interlink polygon nodes in z-order
  73428. if (!pass && size)
  73429. indexCurve(ear, minX, minY, size);
  73430. var stop = ear, prev, next;
  73431. // iterate through ears, slicing them one by one
  73432. while (ear.prev !== ear.next) {
  73433. prev = ear.prev;
  73434. next = ear.next;
  73435. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  73436. // cut off the triangle
  73437. triangles.push(prev.i / dim);
  73438. triangles.push(ear.i / dim);
  73439. triangles.push(next.i / dim);
  73440. removeNode(ear);
  73441. // skipping the next vertice leads to less sliver triangles
  73442. ear = next.next;
  73443. stop = next.next;
  73444. continue;
  73445. }
  73446. ear = next;
  73447. // if we looped through the whole remaining polygon and can't find any more ears
  73448. if (ear === stop) {
  73449. // try filtering points and slicing again
  73450. if (!pass) {
  73451. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  73452. // if this didn't work, try curing all small self-intersections locally
  73453. }
  73454. else if (pass === 1) {
  73455. ear = cureLocalIntersections(ear, triangles, dim);
  73456. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  73457. // as a last resort, try splitting the remaining polygon into two
  73458. }
  73459. else if (pass === 2) {
  73460. splitEarcut(ear, triangles, dim, minX, minY, size);
  73461. }
  73462. break;
  73463. }
  73464. }
  73465. }
  73466. // check whether a polygon node forms a valid ear with adjacent nodes
  73467. function isEar(ear) {
  73468. var a = ear.prev, b = ear, c = ear.next;
  73469. if (area(a, b, c) >= 0)
  73470. return false; // reflex, can't be an ear
  73471. // now make sure we don't have other points inside the potential ear
  73472. var p = ear.next.next;
  73473. while (p !== ear.prev) {
  73474. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  73475. area(p.prev, p, p.next) >= 0)
  73476. return false;
  73477. p = p.next;
  73478. }
  73479. return true;
  73480. }
  73481. function isEarHashed(ear, minX, minY, size) {
  73482. var a = ear.prev, b = ear, c = ear.next;
  73483. if (area(a, b, c) >= 0)
  73484. return false; // reflex, can't be an ear
  73485. // triangle bbox; min & max are calculated like this for speed
  73486. 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);
  73487. // z-order range for the current triangle bbox;
  73488. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  73489. // first look for points inside the triangle in increasing z-order
  73490. var p = ear.nextZ;
  73491. while (p && p.z <= maxZ) {
  73492. if (p !== ear.prev &&
  73493. p !== ear.next &&
  73494. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  73495. area(p.prev, p, p.next) >= 0)
  73496. return false;
  73497. p = p.nextZ;
  73498. }
  73499. // then look for points in decreasing z-order
  73500. p = ear.prevZ;
  73501. while (p && p.z >= minZ) {
  73502. if (p !== ear.prev &&
  73503. p !== ear.next &&
  73504. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  73505. area(p.prev, p, p.next) >= 0)
  73506. return false;
  73507. p = p.prevZ;
  73508. }
  73509. return true;
  73510. }
  73511. // go through all polygon nodes and cure small local self-intersections
  73512. function cureLocalIntersections(start, triangles, dim) {
  73513. var p = start;
  73514. do {
  73515. var a = p.prev, b = p.next.next;
  73516. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  73517. triangles.push(a.i / dim);
  73518. triangles.push(p.i / dim);
  73519. triangles.push(b.i / dim);
  73520. // remove two nodes involved
  73521. removeNode(p);
  73522. removeNode(p.next);
  73523. p = start = b;
  73524. }
  73525. p = p.next;
  73526. } while (p !== start);
  73527. return p;
  73528. }
  73529. // try splitting polygon into two and triangulate them independently
  73530. function splitEarcut(start, triangles, dim, minX, minY, size) {
  73531. // look for a valid diagonal that divides the polygon into two
  73532. var a = start;
  73533. do {
  73534. var b = a.next.next;
  73535. while (b !== a.prev) {
  73536. if (a.i !== b.i && isValidDiagonal(a, b)) {
  73537. // split the polygon in two by the diagonal
  73538. var c = splitPolygon(a, b);
  73539. // filter colinear points around the cuts
  73540. a = filterPoints(a, a.next);
  73541. c = filterPoints(c, c.next);
  73542. // run earcut on each half
  73543. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  73544. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  73545. return;
  73546. }
  73547. b = b.next;
  73548. }
  73549. a = a.next;
  73550. } while (a !== start);
  73551. }
  73552. // link every hole into the outer loop, producing a single-ring polygon without holes
  73553. function eliminateHoles(data, holeIndices, outerNode, dim) {
  73554. var queue = [], i, len, start, end, list;
  73555. for (i = 0, len = holeIndices.length; i < len; i++) {
  73556. start = holeIndices[i] * dim;
  73557. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  73558. list = linkedList(data, start, end, dim, false);
  73559. if (list === list.next)
  73560. list.steiner = true;
  73561. queue.push(getLeftmost(list));
  73562. }
  73563. queue.sort(compareX);
  73564. // process holes from left to right
  73565. for (i = 0; i < queue.length; i++) {
  73566. eliminateHole(queue[i], outerNode);
  73567. outerNode = filterPoints(outerNode, outerNode.next);
  73568. }
  73569. return outerNode;
  73570. }
  73571. function compareX(a, b) {
  73572. return a.x - b.x;
  73573. }
  73574. // find a bridge between vertices that connects hole with an outer ring and and link it
  73575. function eliminateHole(hole, outerNode) {
  73576. outerNode = findHoleBridge(hole, outerNode);
  73577. if (outerNode) {
  73578. var b = splitPolygon(outerNode, hole);
  73579. filterPoints(b, b.next);
  73580. }
  73581. }
  73582. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  73583. function findHoleBridge(hole, outerNode) {
  73584. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  73585. // find a segment intersected by a ray from the hole's leftmost point to the left;
  73586. // segment's endpoint with lesser x will be potential connection point
  73587. do {
  73588. if (hy <= p.y && hy >= p.next.y) {
  73589. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  73590. if (x <= hx && x > qx) {
  73591. qx = x;
  73592. if (x === hx) {
  73593. if (hy === p.y)
  73594. return p;
  73595. if (hy === p.next.y)
  73596. return p.next;
  73597. }
  73598. m = p.x < p.next.x ? p : p.next;
  73599. }
  73600. }
  73601. p = p.next;
  73602. } while (p !== outerNode);
  73603. if (!m)
  73604. return null;
  73605. if (hx === qx)
  73606. return m.prev; // hole touches outer segment; pick lower endpoint
  73607. // look for points inside the triangle of hole point, segment intersection and endpoint;
  73608. // if there are no points found, we have a valid connection;
  73609. // otherwise choose the point of the minimum angle with the ray as connection point
  73610. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  73611. p = m.next;
  73612. while (p !== stop) {
  73613. if (hx >= p.x &&
  73614. p.x >= mx &&
  73615. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  73616. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  73617. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  73618. m = p;
  73619. tanMin = tan;
  73620. }
  73621. }
  73622. p = p.next;
  73623. }
  73624. return m;
  73625. }
  73626. // interlink polygon nodes in z-order
  73627. function indexCurve(start, minX, minY, size) {
  73628. var p = start;
  73629. do {
  73630. if (p.z === null)
  73631. p.z = zOrder(p.x, p.y, minX, minY, size);
  73632. p.prevZ = p.prev;
  73633. p.nextZ = p.next;
  73634. p = p.next;
  73635. } while (p !== start);
  73636. p.prevZ.nextZ = null;
  73637. p.prevZ = null;
  73638. sortLinked(p);
  73639. }
  73640. // Simon Tatham's linked list merge sort algorithm
  73641. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  73642. function sortLinked(list) {
  73643. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  73644. do {
  73645. p = list;
  73646. list = null;
  73647. tail = null;
  73648. numMerges = 0;
  73649. while (p) {
  73650. numMerges++;
  73651. q = p;
  73652. pSize = 0;
  73653. for (i = 0; i < inSize; i++) {
  73654. pSize++;
  73655. q = q.nextZ;
  73656. if (!q)
  73657. break;
  73658. }
  73659. qSize = inSize;
  73660. while (pSize > 0 || (qSize > 0 && q)) {
  73661. if (pSize === 0) {
  73662. e = q;
  73663. q = q.nextZ;
  73664. qSize--;
  73665. }
  73666. else if (qSize === 0 || !q) {
  73667. e = p;
  73668. p = p.nextZ;
  73669. pSize--;
  73670. }
  73671. else if (p.z <= q.z) {
  73672. e = p;
  73673. p = p.nextZ;
  73674. pSize--;
  73675. }
  73676. else {
  73677. e = q;
  73678. q = q.nextZ;
  73679. qSize--;
  73680. }
  73681. if (tail)
  73682. tail.nextZ = e;
  73683. else
  73684. list = e;
  73685. e.prevZ = tail;
  73686. tail = e;
  73687. }
  73688. p = q;
  73689. }
  73690. tail.nextZ = null;
  73691. inSize *= 2;
  73692. } while (numMerges > 1);
  73693. return list;
  73694. }
  73695. // z-order of a point given coords and size of the data bounding box
  73696. function zOrder(x, y, minX, minY, size) {
  73697. // coords are transformed into non-negative 15-bit integer range
  73698. x = 32767 * (x - minX) / size;
  73699. y = 32767 * (y - minY) / size;
  73700. x = (x | (x << 8)) & 0x00FF00FF;
  73701. x = (x | (x << 4)) & 0x0F0F0F0F;
  73702. x = (x | (x << 2)) & 0x33333333;
  73703. x = (x | (x << 1)) & 0x55555555;
  73704. y = (y | (y << 8)) & 0x00FF00FF;
  73705. y = (y | (y << 4)) & 0x0F0F0F0F;
  73706. y = (y | (y << 2)) & 0x33333333;
  73707. y = (y | (y << 1)) & 0x55555555;
  73708. return x | (y << 1);
  73709. }
  73710. // find the leftmost node of a polygon ring
  73711. function getLeftmost(start) {
  73712. var p = start, leftmost = start;
  73713. do {
  73714. if (p.x < leftmost.x)
  73715. leftmost = p;
  73716. p = p.next;
  73717. } while (p !== start);
  73718. return leftmost;
  73719. }
  73720. // check if a point lies within a convex triangle
  73721. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  73722. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  73723. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  73724. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  73725. }
  73726. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  73727. function isValidDiagonal(a, b) {
  73728. return a.next.i !== b.i &&
  73729. a.prev.i !== b.i &&
  73730. !intersectsPolygon(a, b) &&
  73731. locallyInside(a, b) &&
  73732. locallyInside(b, a) &&
  73733. middleInside(a, b);
  73734. }
  73735. // signed area of a triangle
  73736. function area(p, q, r) {
  73737. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  73738. }
  73739. // check if two points are equal
  73740. function equals(p1, p2) {
  73741. return p1.x === p2.x && p1.y === p2.y;
  73742. }
  73743. // check if two segments intersect
  73744. function intersects(p1, q1, p2, q2) {
  73745. if ((equals(p1, q1) && equals(p2, q2)) ||
  73746. (equals(p1, q2) && equals(p2, q1)))
  73747. return true;
  73748. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  73749. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  73750. }
  73751. // check if a polygon diagonal intersects any polygon segments
  73752. function intersectsPolygon(a, b) {
  73753. var p = a;
  73754. do {
  73755. if (p.i !== a.i &&
  73756. p.next.i !== a.i &&
  73757. p.i !== b.i &&
  73758. p.next.i !== b.i &&
  73759. intersects(p, p.next, a, b))
  73760. return true;
  73761. p = p.next;
  73762. } while (p !== a);
  73763. return false;
  73764. }
  73765. // check if a polygon diagonal is locally inside the polygon
  73766. function locallyInside(a, b) {
  73767. return area(a.prev, a, a.next) < 0
  73768. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  73769. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  73770. }
  73771. // check if the middle point of a polygon diagonal is inside the polygon
  73772. function middleInside(a, b) {
  73773. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  73774. do {
  73775. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  73776. inside = !inside;
  73777. p = p.next;
  73778. } while (p !== a);
  73779. return inside;
  73780. }
  73781. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  73782. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  73783. function splitPolygon(a, b) {
  73784. 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;
  73785. a.next = b;
  73786. b.prev = a;
  73787. a2.next = an;
  73788. an.prev = a2;
  73789. b2.next = a2;
  73790. a2.prev = b2;
  73791. bp.next = b2;
  73792. b2.prev = bp;
  73793. return b2;
  73794. }
  73795. // create a node and optionally link it with previous one (in a circular doubly linked list)
  73796. function insertNode(i, x, y, last) {
  73797. var p = new Node(i, x, y);
  73798. if (!last) {
  73799. p.prev = p;
  73800. p.next = p;
  73801. }
  73802. else {
  73803. p.next = last.next;
  73804. p.prev = last;
  73805. last.next.prev = p;
  73806. last.next = p;
  73807. }
  73808. return p;
  73809. }
  73810. function removeNode(p) {
  73811. p.next.prev = p.prev;
  73812. p.prev.next = p.next;
  73813. if (p.prevZ)
  73814. p.prevZ.nextZ = p.nextZ;
  73815. if (p.nextZ)
  73816. p.nextZ.prevZ = p.prevZ;
  73817. }
  73818. /**
  73819. * return a percentage difference between the polygon area and its triangulation area;
  73820. * used to verify correctness of triangulation
  73821. */
  73822. function deviation(data, holeIndices, dim, triangles) {
  73823. var hasHoles = holeIndices && holeIndices.length;
  73824. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  73825. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  73826. if (hasHoles) {
  73827. for (var i = 0, len = holeIndices.length; i < len; i++) {
  73828. var start = holeIndices[i] * dim;
  73829. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  73830. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  73831. }
  73832. }
  73833. var trianglesArea = 0;
  73834. for (i = 0; i < triangles.length; i += 3) {
  73835. var a = triangles[i] * dim;
  73836. var b = triangles[i + 1] * dim;
  73837. var c = triangles[i + 2] * dim;
  73838. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  73839. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  73840. }
  73841. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  73842. }
  73843. Earcut.deviation = deviation;
  73844. ;
  73845. function signedArea(data, start, end, dim) {
  73846. var sum = 0;
  73847. for (var i = start, j = end - dim; i < end; i += dim) {
  73848. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  73849. j = i;
  73850. }
  73851. return sum;
  73852. }
  73853. /**
  73854. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  73855. */
  73856. function flatten(data) {
  73857. var dim = data[0][0].length, result = { vertices: new Array(), holes: new Array(), dimensions: dim }, holeIndex = 0;
  73858. for (var i = 0; i < data.length; i++) {
  73859. for (var j = 0; j < data[i].length; j++) {
  73860. for (var d = 0; d < dim; d++)
  73861. result.vertices.push(data[i][j][d]);
  73862. }
  73863. if (i > 0) {
  73864. holeIndex += data[i - 1].length;
  73865. result.holes.push(holeIndex);
  73866. }
  73867. }
  73868. return result;
  73869. }
  73870. Earcut.flatten = flatten;
  73871. ;
  73872. })(Earcut || (Earcut = {}));
  73873. //# sourceMappingURL=babylon.earcut.js.map
  73874. var BABYLON;
  73875. (function (BABYLON) {
  73876. var IndexedVector2 = /** @class */ (function (_super) {
  73877. __extends(IndexedVector2, _super);
  73878. function IndexedVector2(original, index) {
  73879. var _this = _super.call(this, original.x, original.y) || this;
  73880. _this.index = index;
  73881. return _this;
  73882. }
  73883. return IndexedVector2;
  73884. }(BABYLON.Vector2));
  73885. var PolygonPoints = /** @class */ (function () {
  73886. function PolygonPoints() {
  73887. this.elements = new Array();
  73888. }
  73889. PolygonPoints.prototype.add = function (originalPoints) {
  73890. var _this = this;
  73891. var result = new Array();
  73892. originalPoints.forEach(function (point) {
  73893. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  73894. var newPoint = new IndexedVector2(point, _this.elements.length);
  73895. result.push(newPoint);
  73896. _this.elements.push(newPoint);
  73897. }
  73898. });
  73899. return result;
  73900. };
  73901. PolygonPoints.prototype.computeBounds = function () {
  73902. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  73903. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  73904. this.elements.forEach(function (point) {
  73905. // x
  73906. if (point.x < lmin.x) {
  73907. lmin.x = point.x;
  73908. }
  73909. else if (point.x > lmax.x) {
  73910. lmax.x = point.x;
  73911. }
  73912. // y
  73913. if (point.y < lmin.y) {
  73914. lmin.y = point.y;
  73915. }
  73916. else if (point.y > lmax.y) {
  73917. lmax.y = point.y;
  73918. }
  73919. });
  73920. return {
  73921. min: lmin,
  73922. max: lmax,
  73923. width: lmax.x - lmin.x,
  73924. height: lmax.y - lmin.y
  73925. };
  73926. };
  73927. return PolygonPoints;
  73928. }());
  73929. var Polygon = /** @class */ (function () {
  73930. function Polygon() {
  73931. }
  73932. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  73933. return [
  73934. new BABYLON.Vector2(xmin, ymin),
  73935. new BABYLON.Vector2(xmax, ymin),
  73936. new BABYLON.Vector2(xmax, ymax),
  73937. new BABYLON.Vector2(xmin, ymax)
  73938. ];
  73939. };
  73940. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  73941. if (cx === void 0) { cx = 0; }
  73942. if (cy === void 0) { cy = 0; }
  73943. if (numberOfSides === void 0) { numberOfSides = 32; }
  73944. var result = new Array();
  73945. var angle = 0;
  73946. var increment = (Math.PI * 2) / numberOfSides;
  73947. for (var i = 0; i < numberOfSides; i++) {
  73948. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  73949. angle -= increment;
  73950. }
  73951. return result;
  73952. };
  73953. Polygon.Parse = function (input) {
  73954. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  73955. var i, result = [];
  73956. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  73957. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  73958. }
  73959. return result;
  73960. };
  73961. Polygon.StartingAt = function (x, y) {
  73962. return BABYLON.Path2.StartingAt(x, y);
  73963. };
  73964. return Polygon;
  73965. }());
  73966. BABYLON.Polygon = Polygon;
  73967. var PolygonMeshBuilder = /** @class */ (function () {
  73968. function PolygonMeshBuilder(name, contours, scene) {
  73969. this._points = new PolygonPoints();
  73970. this._outlinepoints = new PolygonPoints();
  73971. this._holes = new Array();
  73972. this._epoints = new Array();
  73973. this._eholes = new Array();
  73974. this._name = name;
  73975. this._scene = scene;
  73976. var points;
  73977. if (contours instanceof BABYLON.Path2) {
  73978. points = contours.getPoints();
  73979. }
  73980. else {
  73981. points = contours;
  73982. }
  73983. this._addToepoint(points);
  73984. this._points.add(points);
  73985. this._outlinepoints.add(points);
  73986. }
  73987. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  73988. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  73989. var p = points_1[_i];
  73990. this._epoints.push(p.x, p.y);
  73991. }
  73992. };
  73993. PolygonMeshBuilder.prototype.addHole = function (hole) {
  73994. this._points.add(hole);
  73995. var holepoints = new PolygonPoints();
  73996. holepoints.add(hole);
  73997. this._holes.push(holepoints);
  73998. this._eholes.push(this._epoints.length / 2);
  73999. this._addToepoint(hole);
  74000. return this;
  74001. };
  74002. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  74003. var _this = this;
  74004. if (updatable === void 0) { updatable = false; }
  74005. if (depth === void 0) { depth = 0; }
  74006. var result = new BABYLON.Mesh(this._name, this._scene);
  74007. var normals = new Array();
  74008. var positions = new Array();
  74009. var uvs = new Array();
  74010. var bounds = this._points.computeBounds();
  74011. this._points.elements.forEach(function (p) {
  74012. normals.push(0, 1.0, 0);
  74013. positions.push(p.x, 0, p.y);
  74014. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  74015. });
  74016. var indices = new Array();
  74017. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  74018. for (var i = 0; i < res.length; i++) {
  74019. indices.push(res[i]);
  74020. }
  74021. if (depth > 0) {
  74022. var positionscount = (positions.length / 3); //get the current pointcount
  74023. this._points.elements.forEach(function (p) {
  74024. normals.push(0, -1.0, 0);
  74025. positions.push(p.x, -depth, p.y);
  74026. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  74027. });
  74028. var totalCount = indices.length;
  74029. for (var i = 0; i < totalCount; i += 3) {
  74030. var i0 = indices[i + 0];
  74031. var i1 = indices[i + 1];
  74032. var i2 = indices[i + 2];
  74033. indices.push(i2 + positionscount);
  74034. indices.push(i1 + positionscount);
  74035. indices.push(i0 + positionscount);
  74036. }
  74037. //Add the sides
  74038. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  74039. this._holes.forEach(function (hole) {
  74040. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  74041. });
  74042. }
  74043. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  74044. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  74045. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  74046. result.setIndices(indices);
  74047. return result;
  74048. };
  74049. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  74050. var StartIndex = positions.length / 3;
  74051. var ulength = 0;
  74052. for (var i = 0; i < points.elements.length; i++) {
  74053. var p = points.elements[i];
  74054. var p1;
  74055. if ((i + 1) > points.elements.length - 1) {
  74056. p1 = points.elements[0];
  74057. }
  74058. else {
  74059. p1 = points.elements[i + 1];
  74060. }
  74061. positions.push(p.x, 0, p.y);
  74062. positions.push(p.x, -depth, p.y);
  74063. positions.push(p1.x, 0, p1.y);
  74064. positions.push(p1.x, -depth, p1.y);
  74065. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  74066. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  74067. var v3 = v2.subtract(v1);
  74068. var v4 = new BABYLON.Vector3(0, 1, 0);
  74069. var vn = BABYLON.Vector3.Cross(v3, v4);
  74070. vn = vn.normalize();
  74071. uvs.push(ulength / bounds.width, 0);
  74072. uvs.push(ulength / bounds.width, 1);
  74073. ulength += v3.length();
  74074. uvs.push((ulength / bounds.width), 0);
  74075. uvs.push((ulength / bounds.width), 1);
  74076. if (!flip) {
  74077. normals.push(-vn.x, -vn.y, -vn.z);
  74078. normals.push(-vn.x, -vn.y, -vn.z);
  74079. normals.push(-vn.x, -vn.y, -vn.z);
  74080. normals.push(-vn.x, -vn.y, -vn.z);
  74081. indices.push(StartIndex);
  74082. indices.push(StartIndex + 1);
  74083. indices.push(StartIndex + 2);
  74084. indices.push(StartIndex + 1);
  74085. indices.push(StartIndex + 3);
  74086. indices.push(StartIndex + 2);
  74087. }
  74088. else {
  74089. normals.push(vn.x, vn.y, vn.z);
  74090. normals.push(vn.x, vn.y, vn.z);
  74091. normals.push(vn.x, vn.y, vn.z);
  74092. normals.push(vn.x, vn.y, vn.z);
  74093. indices.push(StartIndex);
  74094. indices.push(StartIndex + 2);
  74095. indices.push(StartIndex + 1);
  74096. indices.push(StartIndex + 1);
  74097. indices.push(StartIndex + 2);
  74098. indices.push(StartIndex + 3);
  74099. }
  74100. StartIndex += 4;
  74101. }
  74102. ;
  74103. };
  74104. return PolygonMeshBuilder;
  74105. }());
  74106. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  74107. })(BABYLON || (BABYLON = {}));
  74108. //# sourceMappingURL=babylon.polygonMesh.js.map
  74109. var BABYLON;
  74110. (function (BABYLON) {
  74111. // Unique ID when we import meshes from Babylon to CSG
  74112. var currentCSGMeshId = 0;
  74113. // # class Vertex
  74114. // Represents a vertex of a polygon. Use your own vertex class instead of this
  74115. // one to provide additional features like texture coordinates and vertex
  74116. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  74117. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  74118. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  74119. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  74120. // is not used anywhere else.
  74121. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  74122. var Vertex = /** @class */ (function () {
  74123. function Vertex(pos, normal, uv) {
  74124. this.pos = pos;
  74125. this.normal = normal;
  74126. this.uv = uv;
  74127. }
  74128. Vertex.prototype.clone = function () {
  74129. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  74130. };
  74131. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  74132. // orientation of a polygon is flipped.
  74133. Vertex.prototype.flip = function () {
  74134. this.normal = this.normal.scale(-1);
  74135. };
  74136. // Create a new vertex between this vertex and `other` by linearly
  74137. // interpolating all properties using a parameter of `t`. Subclasses should
  74138. // override this to interpolate additional properties.
  74139. Vertex.prototype.interpolate = function (other, t) {
  74140. 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));
  74141. };
  74142. return Vertex;
  74143. }());
  74144. // # class Plane
  74145. // Represents a plane in 3D space.
  74146. var Plane = /** @class */ (function () {
  74147. function Plane(normal, w) {
  74148. this.normal = normal;
  74149. this.w = w;
  74150. }
  74151. Plane.FromPoints = function (a, b, c) {
  74152. var v0 = c.subtract(a);
  74153. var v1 = b.subtract(a);
  74154. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  74155. return null;
  74156. }
  74157. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  74158. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  74159. };
  74160. Plane.prototype.clone = function () {
  74161. return new Plane(this.normal.clone(), this.w);
  74162. };
  74163. Plane.prototype.flip = function () {
  74164. this.normal.scaleInPlace(-1);
  74165. this.w = -this.w;
  74166. };
  74167. // Split `polygon` by this plane if needed, then put the polygon or polygon
  74168. // fragments in the appropriate lists. Coplanar polygons go into either
  74169. // `coplanarFront` or `coplanarBack` depending on their orientation with
  74170. // respect to this plane. Polygons in front or in back of this plane go into
  74171. // either `front` or `back`.
  74172. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  74173. var COPLANAR = 0;
  74174. var FRONT = 1;
  74175. var BACK = 2;
  74176. var SPANNING = 3;
  74177. // Classify each point as well as the entire polygon into one of the above
  74178. // four classes.
  74179. var polygonType = 0;
  74180. var types = [];
  74181. var i;
  74182. var t;
  74183. for (i = 0; i < polygon.vertices.length; i++) {
  74184. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  74185. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  74186. polygonType |= type;
  74187. types.push(type);
  74188. }
  74189. // Put the polygon in the correct list, splitting it when necessary.
  74190. switch (polygonType) {
  74191. case COPLANAR:
  74192. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  74193. break;
  74194. case FRONT:
  74195. front.push(polygon);
  74196. break;
  74197. case BACK:
  74198. back.push(polygon);
  74199. break;
  74200. case SPANNING:
  74201. var f = [], b = [];
  74202. for (i = 0; i < polygon.vertices.length; i++) {
  74203. var j = (i + 1) % polygon.vertices.length;
  74204. var ti = types[i], tj = types[j];
  74205. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  74206. if (ti !== BACK)
  74207. f.push(vi);
  74208. if (ti !== FRONT)
  74209. b.push(ti !== BACK ? vi.clone() : vi);
  74210. if ((ti | tj) === SPANNING) {
  74211. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  74212. var v = vi.interpolate(vj, t);
  74213. f.push(v);
  74214. b.push(v.clone());
  74215. }
  74216. }
  74217. var poly;
  74218. if (f.length >= 3) {
  74219. poly = new Polygon(f, polygon.shared);
  74220. if (poly.plane)
  74221. front.push(poly);
  74222. }
  74223. if (b.length >= 3) {
  74224. poly = new Polygon(b, polygon.shared);
  74225. if (poly.plane)
  74226. back.push(poly);
  74227. }
  74228. break;
  74229. }
  74230. };
  74231. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  74232. // point is on the plane.
  74233. Plane.EPSILON = 1e-5;
  74234. return Plane;
  74235. }());
  74236. // # class Polygon
  74237. // Represents a convex polygon. The vertices used to initialize a polygon must
  74238. // be coplanar and form a convex loop.
  74239. //
  74240. // Each convex polygon has a `shared` property, which is shared between all
  74241. // polygons that are clones of each other or were split from the same polygon.
  74242. // This can be used to define per-polygon properties (such as surface color).
  74243. var Polygon = /** @class */ (function () {
  74244. function Polygon(vertices, shared) {
  74245. this.vertices = vertices;
  74246. this.shared = shared;
  74247. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  74248. }
  74249. Polygon.prototype.clone = function () {
  74250. var vertices = this.vertices.map(function (v) { return v.clone(); });
  74251. return new Polygon(vertices, this.shared);
  74252. };
  74253. Polygon.prototype.flip = function () {
  74254. this.vertices.reverse().map(function (v) { v.flip(); });
  74255. this.plane.flip();
  74256. };
  74257. return Polygon;
  74258. }());
  74259. // # class Node
  74260. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  74261. // by picking a polygon to split along. That polygon (and all other coplanar
  74262. // polygons) are added directly to that node and the other polygons are added to
  74263. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  74264. // no distinction between internal and leaf nodes.
  74265. var Node = /** @class */ (function () {
  74266. function Node(polygons) {
  74267. this.plane = null;
  74268. this.front = null;
  74269. this.back = null;
  74270. this.polygons = new Array();
  74271. if (polygons) {
  74272. this.build(polygons);
  74273. }
  74274. }
  74275. Node.prototype.clone = function () {
  74276. var node = new Node();
  74277. node.plane = this.plane && this.plane.clone();
  74278. node.front = this.front && this.front.clone();
  74279. node.back = this.back && this.back.clone();
  74280. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  74281. return node;
  74282. };
  74283. // Convert solid space to empty space and empty space to solid space.
  74284. Node.prototype.invert = function () {
  74285. for (var i = 0; i < this.polygons.length; i++) {
  74286. this.polygons[i].flip();
  74287. }
  74288. if (this.plane) {
  74289. this.plane.flip();
  74290. }
  74291. if (this.front) {
  74292. this.front.invert();
  74293. }
  74294. if (this.back) {
  74295. this.back.invert();
  74296. }
  74297. var temp = this.front;
  74298. this.front = this.back;
  74299. this.back = temp;
  74300. };
  74301. // Recursively remove all polygons in `polygons` that are inside this BSP
  74302. // tree.
  74303. Node.prototype.clipPolygons = function (polygons) {
  74304. if (!this.plane)
  74305. return polygons.slice();
  74306. var front = new Array(), back = new Array();
  74307. for (var i = 0; i < polygons.length; i++) {
  74308. this.plane.splitPolygon(polygons[i], front, back, front, back);
  74309. }
  74310. if (this.front) {
  74311. front = this.front.clipPolygons(front);
  74312. }
  74313. if (this.back) {
  74314. back = this.back.clipPolygons(back);
  74315. }
  74316. else {
  74317. back = [];
  74318. }
  74319. return front.concat(back);
  74320. };
  74321. // Remove all polygons in this BSP tree that are inside the other BSP tree
  74322. // `bsp`.
  74323. Node.prototype.clipTo = function (bsp) {
  74324. this.polygons = bsp.clipPolygons(this.polygons);
  74325. if (this.front)
  74326. this.front.clipTo(bsp);
  74327. if (this.back)
  74328. this.back.clipTo(bsp);
  74329. };
  74330. // Return a list of all polygons in this BSP tree.
  74331. Node.prototype.allPolygons = function () {
  74332. var polygons = this.polygons.slice();
  74333. if (this.front)
  74334. polygons = polygons.concat(this.front.allPolygons());
  74335. if (this.back)
  74336. polygons = polygons.concat(this.back.allPolygons());
  74337. return polygons;
  74338. };
  74339. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  74340. // new polygons are filtered down to the bottom of the tree and become new
  74341. // nodes there. Each set of polygons is partitioned using the first polygon
  74342. // (no heuristic is used to pick a good split).
  74343. Node.prototype.build = function (polygons) {
  74344. if (!polygons.length)
  74345. return;
  74346. if (!this.plane)
  74347. this.plane = polygons[0].plane.clone();
  74348. var front = new Array(), back = new Array();
  74349. for (var i = 0; i < polygons.length; i++) {
  74350. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  74351. }
  74352. if (front.length) {
  74353. if (!this.front)
  74354. this.front = new Node();
  74355. this.front.build(front);
  74356. }
  74357. if (back.length) {
  74358. if (!this.back)
  74359. this.back = new Node();
  74360. this.back.build(back);
  74361. }
  74362. };
  74363. return Node;
  74364. }());
  74365. var CSG = /** @class */ (function () {
  74366. function CSG() {
  74367. this.polygons = new Array();
  74368. }
  74369. // Convert BABYLON.Mesh to BABYLON.CSG
  74370. CSG.FromMesh = function (mesh) {
  74371. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  74372. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  74373. if (mesh instanceof BABYLON.Mesh) {
  74374. mesh.computeWorldMatrix(true);
  74375. matrix = mesh.getWorldMatrix();
  74376. meshPosition = mesh.position.clone();
  74377. meshRotation = mesh.rotation.clone();
  74378. if (mesh.rotationQuaternion) {
  74379. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  74380. }
  74381. meshScaling = mesh.scaling.clone();
  74382. }
  74383. else {
  74384. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  74385. }
  74386. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  74387. var subMeshes = mesh.subMeshes;
  74388. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  74389. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  74390. vertices = [];
  74391. for (var j = 0; j < 3; j++) {
  74392. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  74393. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  74394. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  74395. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  74396. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  74397. vertex = new Vertex(position, normal, uv);
  74398. vertices.push(vertex);
  74399. }
  74400. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  74401. // To handle the case of degenerated triangle
  74402. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  74403. if (polygon.plane)
  74404. polygons.push(polygon);
  74405. }
  74406. }
  74407. var csg = CSG.FromPolygons(polygons);
  74408. csg.matrix = matrix;
  74409. csg.position = meshPosition;
  74410. csg.rotation = meshRotation;
  74411. csg.scaling = meshScaling;
  74412. csg.rotationQuaternion = meshRotationQuaternion;
  74413. currentCSGMeshId++;
  74414. return csg;
  74415. };
  74416. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  74417. CSG.FromPolygons = function (polygons) {
  74418. var csg = new CSG();
  74419. csg.polygons = polygons;
  74420. return csg;
  74421. };
  74422. CSG.prototype.clone = function () {
  74423. var csg = new CSG();
  74424. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  74425. csg.copyTransformAttributes(this);
  74426. return csg;
  74427. };
  74428. CSG.prototype.union = function (csg) {
  74429. var a = new Node(this.clone().polygons);
  74430. var b = new Node(csg.clone().polygons);
  74431. a.clipTo(b);
  74432. b.clipTo(a);
  74433. b.invert();
  74434. b.clipTo(a);
  74435. b.invert();
  74436. a.build(b.allPolygons());
  74437. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  74438. };
  74439. CSG.prototype.unionInPlace = function (csg) {
  74440. var a = new Node(this.polygons);
  74441. var b = new Node(csg.polygons);
  74442. a.clipTo(b);
  74443. b.clipTo(a);
  74444. b.invert();
  74445. b.clipTo(a);
  74446. b.invert();
  74447. a.build(b.allPolygons());
  74448. this.polygons = a.allPolygons();
  74449. };
  74450. CSG.prototype.subtract = function (csg) {
  74451. var a = new Node(this.clone().polygons);
  74452. var b = new Node(csg.clone().polygons);
  74453. a.invert();
  74454. a.clipTo(b);
  74455. b.clipTo(a);
  74456. b.invert();
  74457. b.clipTo(a);
  74458. b.invert();
  74459. a.build(b.allPolygons());
  74460. a.invert();
  74461. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  74462. };
  74463. CSG.prototype.subtractInPlace = function (csg) {
  74464. var a = new Node(this.polygons);
  74465. var b = new Node(csg.polygons);
  74466. a.invert();
  74467. a.clipTo(b);
  74468. b.clipTo(a);
  74469. b.invert();
  74470. b.clipTo(a);
  74471. b.invert();
  74472. a.build(b.allPolygons());
  74473. a.invert();
  74474. this.polygons = a.allPolygons();
  74475. };
  74476. CSG.prototype.intersect = function (csg) {
  74477. var a = new Node(this.clone().polygons);
  74478. var b = new Node(csg.clone().polygons);
  74479. a.invert();
  74480. b.clipTo(a);
  74481. b.invert();
  74482. a.clipTo(b);
  74483. b.clipTo(a);
  74484. a.build(b.allPolygons());
  74485. a.invert();
  74486. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  74487. };
  74488. CSG.prototype.intersectInPlace = function (csg) {
  74489. var a = new Node(this.polygons);
  74490. var b = new Node(csg.polygons);
  74491. a.invert();
  74492. b.clipTo(a);
  74493. b.invert();
  74494. a.clipTo(b);
  74495. b.clipTo(a);
  74496. a.build(b.allPolygons());
  74497. a.invert();
  74498. this.polygons = a.allPolygons();
  74499. };
  74500. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  74501. // not modified.
  74502. CSG.prototype.inverse = function () {
  74503. var csg = this.clone();
  74504. csg.inverseInPlace();
  74505. return csg;
  74506. };
  74507. CSG.prototype.inverseInPlace = function () {
  74508. this.polygons.map(function (p) { p.flip(); });
  74509. };
  74510. // This is used to keep meshes transformations so they can be restored
  74511. // when we build back a Babylon Mesh
  74512. // NB : All CSG operations are performed in world coordinates
  74513. CSG.prototype.copyTransformAttributes = function (csg) {
  74514. this.matrix = csg.matrix;
  74515. this.position = csg.position;
  74516. this.rotation = csg.rotation;
  74517. this.scaling = csg.scaling;
  74518. this.rotationQuaternion = csg.rotationQuaternion;
  74519. return this;
  74520. };
  74521. // Build Raw mesh from CSG
  74522. // Coordinates here are in world space
  74523. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  74524. var matrix = this.matrix.clone();
  74525. matrix.invert();
  74526. 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;
  74527. if (keepSubMeshes) {
  74528. // Sort Polygons, since subMeshes are indices range
  74529. polygons.sort(function (a, b) {
  74530. if (a.shared.meshId === b.shared.meshId) {
  74531. return a.shared.subMeshId - b.shared.subMeshId;
  74532. }
  74533. else {
  74534. return a.shared.meshId - b.shared.meshId;
  74535. }
  74536. });
  74537. }
  74538. for (var i = 0, il = polygons.length; i < il; i++) {
  74539. polygon = polygons[i];
  74540. // Building SubMeshes
  74541. if (!subMesh_dict[polygon.shared.meshId]) {
  74542. subMesh_dict[polygon.shared.meshId] = {};
  74543. }
  74544. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  74545. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  74546. indexStart: +Infinity,
  74547. indexEnd: -Infinity,
  74548. materialIndex: polygon.shared.materialIndex
  74549. };
  74550. }
  74551. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  74552. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  74553. polygonIndices[0] = 0;
  74554. polygonIndices[1] = j - 1;
  74555. polygonIndices[2] = j;
  74556. for (var k = 0; k < 3; k++) {
  74557. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  74558. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  74559. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  74560. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  74561. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  74562. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  74563. // Check if 2 points can be merged
  74564. if (!(typeof vertex_idx !== 'undefined' &&
  74565. normals[vertex_idx * 3] === localNormal.x &&
  74566. normals[vertex_idx * 3 + 1] === localNormal.y &&
  74567. normals[vertex_idx * 3 + 2] === localNormal.z &&
  74568. uvs[vertex_idx * 2] === uv.x &&
  74569. uvs[vertex_idx * 2 + 1] === uv.y)) {
  74570. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  74571. uvs.push(uv.x, uv.y);
  74572. normals.push(normal.x, normal.y, normal.z);
  74573. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  74574. }
  74575. indices.push(vertex_idx);
  74576. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  74577. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  74578. currentIndex++;
  74579. }
  74580. }
  74581. }
  74582. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  74583. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  74584. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  74585. mesh.setIndices(indices, null);
  74586. if (keepSubMeshes) {
  74587. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  74588. var materialIndexOffset = 0, materialMaxIndex;
  74589. mesh.subMeshes = new Array();
  74590. for (var m in subMesh_dict) {
  74591. materialMaxIndex = -1;
  74592. for (var sm in subMesh_dict[m]) {
  74593. subMesh_obj = subMesh_dict[m][sm];
  74594. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  74595. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  74596. }
  74597. materialIndexOffset += ++materialMaxIndex;
  74598. }
  74599. }
  74600. return mesh;
  74601. };
  74602. // Build Mesh from CSG taking material and transforms into account
  74603. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  74604. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  74605. mesh.material = material;
  74606. mesh.position.copyFrom(this.position);
  74607. mesh.rotation.copyFrom(this.rotation);
  74608. if (this.rotationQuaternion) {
  74609. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  74610. }
  74611. mesh.scaling.copyFrom(this.scaling);
  74612. mesh.computeWorldMatrix(true);
  74613. return mesh;
  74614. };
  74615. return CSG;
  74616. }());
  74617. BABYLON.CSG = CSG;
  74618. })(BABYLON || (BABYLON = {}));
  74619. //# sourceMappingURL=babylon.csg.js.map
  74620. var BABYLON;
  74621. (function (BABYLON) {
  74622. var LensFlare = /** @class */ (function () {
  74623. function LensFlare(size, position, color, imgUrl, system) {
  74624. this.size = size;
  74625. this.position = position;
  74626. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  74627. this.color = color || new BABYLON.Color3(1, 1, 1);
  74628. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  74629. this._system = system;
  74630. system.lensFlares.push(this);
  74631. }
  74632. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  74633. return new LensFlare(size, position, color, imgUrl, system);
  74634. };
  74635. LensFlare.prototype.dispose = function () {
  74636. if (this.texture) {
  74637. this.texture.dispose();
  74638. }
  74639. // Remove from scene
  74640. var index = this._system.lensFlares.indexOf(this);
  74641. this._system.lensFlares.splice(index, 1);
  74642. };
  74643. ;
  74644. return LensFlare;
  74645. }());
  74646. BABYLON.LensFlare = LensFlare;
  74647. })(BABYLON || (BABYLON = {}));
  74648. //# sourceMappingURL=babylon.lensFlare.js.map
  74649. var BABYLON;
  74650. (function (BABYLON) {
  74651. var LensFlareSystem = /** @class */ (function () {
  74652. function LensFlareSystem(name, emitter, scene) {
  74653. this.name = name;
  74654. this.lensFlares = new Array();
  74655. this.borderLimit = 300;
  74656. this.viewportBorder = 0;
  74657. this.layerMask = 0x0FFFFFFF;
  74658. this._vertexBuffers = {};
  74659. this._isEnabled = true;
  74660. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  74661. this._emitter = emitter;
  74662. this.id = name;
  74663. scene.lensFlareSystems.push(this);
  74664. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  74665. var engine = scene.getEngine();
  74666. // VBO
  74667. var vertices = [];
  74668. vertices.push(1, 1);
  74669. vertices.push(-1, 1);
  74670. vertices.push(-1, -1);
  74671. vertices.push(1, -1);
  74672. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  74673. // Indices
  74674. var indices = [];
  74675. indices.push(0);
  74676. indices.push(1);
  74677. indices.push(2);
  74678. indices.push(0);
  74679. indices.push(2);
  74680. indices.push(3);
  74681. this._indexBuffer = engine.createIndexBuffer(indices);
  74682. // Effects
  74683. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  74684. }
  74685. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  74686. get: function () {
  74687. return this._isEnabled;
  74688. },
  74689. set: function (value) {
  74690. this._isEnabled = value;
  74691. },
  74692. enumerable: true,
  74693. configurable: true
  74694. });
  74695. LensFlareSystem.prototype.getScene = function () {
  74696. return this._scene;
  74697. };
  74698. LensFlareSystem.prototype.getEmitter = function () {
  74699. return this._emitter;
  74700. };
  74701. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  74702. this._emitter = newEmitter;
  74703. };
  74704. LensFlareSystem.prototype.getEmitterPosition = function () {
  74705. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  74706. };
  74707. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  74708. var position = this.getEmitterPosition();
  74709. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  74710. this._positionX = position.x;
  74711. this._positionY = position.y;
  74712. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  74713. if (this.viewportBorder > 0) {
  74714. globalViewport.x -= this.viewportBorder;
  74715. globalViewport.y -= this.viewportBorder;
  74716. globalViewport.width += this.viewportBorder * 2;
  74717. globalViewport.height += this.viewportBorder * 2;
  74718. position.x += this.viewportBorder;
  74719. position.y += this.viewportBorder;
  74720. this._positionX += this.viewportBorder;
  74721. this._positionY += this.viewportBorder;
  74722. }
  74723. if (position.z > 0) {
  74724. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  74725. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  74726. return true;
  74727. }
  74728. return true;
  74729. }
  74730. return false;
  74731. };
  74732. LensFlareSystem.prototype._isVisible = function () {
  74733. if (!this._isEnabled || !this._scene.activeCamera) {
  74734. return false;
  74735. }
  74736. var emitterPosition = this.getEmitterPosition();
  74737. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  74738. var distance = direction.length();
  74739. direction.normalize();
  74740. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  74741. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  74742. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  74743. };
  74744. LensFlareSystem.prototype.render = function () {
  74745. if (!this._effect.isReady() || !this._scene.activeCamera)
  74746. return false;
  74747. var engine = this._scene.getEngine();
  74748. var viewport = this._scene.activeCamera.viewport;
  74749. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  74750. // Position
  74751. if (!this.computeEffectivePosition(globalViewport)) {
  74752. return false;
  74753. }
  74754. // Visibility
  74755. if (!this._isVisible()) {
  74756. return false;
  74757. }
  74758. // Intensity
  74759. var awayX;
  74760. var awayY;
  74761. if (this._positionX < this.borderLimit + globalViewport.x) {
  74762. awayX = this.borderLimit + globalViewport.x - this._positionX;
  74763. }
  74764. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  74765. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  74766. }
  74767. else {
  74768. awayX = 0;
  74769. }
  74770. if (this._positionY < this.borderLimit + globalViewport.y) {
  74771. awayY = this.borderLimit + globalViewport.y - this._positionY;
  74772. }
  74773. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  74774. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  74775. }
  74776. else {
  74777. awayY = 0;
  74778. }
  74779. var away = (awayX > awayY) ? awayX : awayY;
  74780. away -= this.viewportBorder;
  74781. if (away > this.borderLimit) {
  74782. away = this.borderLimit;
  74783. }
  74784. var intensity = 1.0 - (away / this.borderLimit);
  74785. if (intensity < 0) {
  74786. return false;
  74787. }
  74788. if (intensity > 1.0) {
  74789. intensity = 1.0;
  74790. }
  74791. if (this.viewportBorder > 0) {
  74792. globalViewport.x += this.viewportBorder;
  74793. globalViewport.y += this.viewportBorder;
  74794. globalViewport.width -= this.viewportBorder * 2;
  74795. globalViewport.height -= this.viewportBorder * 2;
  74796. this._positionX -= this.viewportBorder;
  74797. this._positionY -= this.viewportBorder;
  74798. }
  74799. // Position
  74800. var centerX = globalViewport.x + globalViewport.width / 2;
  74801. var centerY = globalViewport.y + globalViewport.height / 2;
  74802. var distX = centerX - this._positionX;
  74803. var distY = centerY - this._positionY;
  74804. // Effects
  74805. engine.enableEffect(this._effect);
  74806. engine.setState(false);
  74807. engine.setDepthBuffer(false);
  74808. // VBOs
  74809. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  74810. // Flares
  74811. for (var index = 0; index < this.lensFlares.length; index++) {
  74812. var flare = this.lensFlares[index];
  74813. engine.setAlphaMode(flare.alphaMode);
  74814. var x = centerX - (distX * flare.position);
  74815. var y = centerY - (distY * flare.position);
  74816. var cw = flare.size;
  74817. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  74818. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  74819. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  74820. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  74821. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  74822. // Texture
  74823. this._effect.setTexture("textureSampler", flare.texture);
  74824. // Color
  74825. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  74826. // Draw order
  74827. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  74828. }
  74829. engine.setDepthBuffer(true);
  74830. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  74831. return true;
  74832. };
  74833. LensFlareSystem.prototype.dispose = function () {
  74834. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  74835. if (vertexBuffer) {
  74836. vertexBuffer.dispose();
  74837. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  74838. }
  74839. if (this._indexBuffer) {
  74840. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  74841. this._indexBuffer = null;
  74842. }
  74843. while (this.lensFlares.length) {
  74844. this.lensFlares[0].dispose();
  74845. }
  74846. // Remove from scene
  74847. var index = this._scene.lensFlareSystems.indexOf(this);
  74848. this._scene.lensFlareSystems.splice(index, 1);
  74849. };
  74850. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  74851. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  74852. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  74853. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  74854. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  74855. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  74856. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  74857. var parsedFlare = parsedLensFlareSystem.flares[index];
  74858. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  74859. }
  74860. return lensFlareSystem;
  74861. };
  74862. LensFlareSystem.prototype.serialize = function () {
  74863. var serializationObject = {};
  74864. serializationObject.id = this.id;
  74865. serializationObject.name = this.name;
  74866. serializationObject.emitterId = this.getEmitter().id;
  74867. serializationObject.borderLimit = this.borderLimit;
  74868. serializationObject.flares = [];
  74869. for (var index = 0; index < this.lensFlares.length; index++) {
  74870. var flare = this.lensFlares[index];
  74871. serializationObject.flares.push({
  74872. size: flare.size,
  74873. position: flare.position,
  74874. color: flare.color.asArray(),
  74875. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  74876. });
  74877. }
  74878. return serializationObject;
  74879. };
  74880. return LensFlareSystem;
  74881. }());
  74882. BABYLON.LensFlareSystem = LensFlareSystem;
  74883. })(BABYLON || (BABYLON = {}));
  74884. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  74885. var BABYLON;
  74886. (function (BABYLON) {
  74887. /**
  74888. * This is a holder class for the physics joint created by the physics plugin.
  74889. * It holds a set of functions to control the underlying joint.
  74890. */
  74891. var PhysicsJoint = /** @class */ (function () {
  74892. function PhysicsJoint(type, jointData) {
  74893. this.type = type;
  74894. this.jointData = jointData;
  74895. jointData.nativeParams = jointData.nativeParams || {};
  74896. }
  74897. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  74898. get: function () {
  74899. return this._physicsJoint;
  74900. },
  74901. set: function (newJoint) {
  74902. if (this._physicsJoint) {
  74903. //remove from the wolrd
  74904. }
  74905. this._physicsJoint = newJoint;
  74906. },
  74907. enumerable: true,
  74908. configurable: true
  74909. });
  74910. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  74911. set: function (physicsPlugin) {
  74912. this._physicsPlugin = physicsPlugin;
  74913. },
  74914. enumerable: true,
  74915. configurable: true
  74916. });
  74917. /**
  74918. * Execute a function that is physics-plugin specific.
  74919. * @param {Function} func the function that will be executed.
  74920. * It accepts two parameters: the physics world and the physics joint.
  74921. */
  74922. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  74923. func(this._physicsPlugin.world, this._physicsJoint);
  74924. };
  74925. //TODO check if the native joints are the same
  74926. //Joint Types
  74927. PhysicsJoint.DistanceJoint = 0;
  74928. PhysicsJoint.HingeJoint = 1;
  74929. PhysicsJoint.BallAndSocketJoint = 2;
  74930. PhysicsJoint.WheelJoint = 3;
  74931. PhysicsJoint.SliderJoint = 4;
  74932. //OIMO
  74933. PhysicsJoint.PrismaticJoint = 5;
  74934. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  74935. PhysicsJoint.UniversalJoint = 6;
  74936. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  74937. //Cannon
  74938. //Similar to a Ball-Joint. Different in params
  74939. PhysicsJoint.PointToPointJoint = 8;
  74940. //Cannon only at the moment
  74941. PhysicsJoint.SpringJoint = 9;
  74942. PhysicsJoint.LockJoint = 10;
  74943. return PhysicsJoint;
  74944. }());
  74945. BABYLON.PhysicsJoint = PhysicsJoint;
  74946. /**
  74947. * A class representing a physics distance joint.
  74948. */
  74949. var DistanceJoint = /** @class */ (function (_super) {
  74950. __extends(DistanceJoint, _super);
  74951. function DistanceJoint(jointData) {
  74952. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  74953. }
  74954. /**
  74955. * Update the predefined distance.
  74956. */
  74957. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  74958. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  74959. };
  74960. return DistanceJoint;
  74961. }(PhysicsJoint));
  74962. BABYLON.DistanceJoint = DistanceJoint;
  74963. var MotorEnabledJoint = /** @class */ (function (_super) {
  74964. __extends(MotorEnabledJoint, _super);
  74965. function MotorEnabledJoint(type, jointData) {
  74966. return _super.call(this, type, jointData) || this;
  74967. }
  74968. /**
  74969. * Set the motor values.
  74970. * Attention, this function is plugin specific. Engines won't react 100% the same.
  74971. * @param {number} force the force to apply
  74972. * @param {number} maxForce max force for this motor.
  74973. */
  74974. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  74975. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  74976. };
  74977. /**
  74978. * Set the motor's limits.
  74979. * Attention, this function is plugin specific. Engines won't react 100% the same.
  74980. */
  74981. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  74982. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  74983. };
  74984. return MotorEnabledJoint;
  74985. }(PhysicsJoint));
  74986. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  74987. /**
  74988. * This class represents a single hinge physics joint
  74989. */
  74990. var HingeJoint = /** @class */ (function (_super) {
  74991. __extends(HingeJoint, _super);
  74992. function HingeJoint(jointData) {
  74993. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  74994. }
  74995. /**
  74996. * Set the motor values.
  74997. * Attention, this function is plugin specific. Engines won't react 100% the same.
  74998. * @param {number} force the force to apply
  74999. * @param {number} maxForce max force for this motor.
  75000. */
  75001. HingeJoint.prototype.setMotor = function (force, maxForce) {
  75002. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  75003. };
  75004. /**
  75005. * Set the motor's limits.
  75006. * Attention, this function is plugin specific. Engines won't react 100% the same.
  75007. */
  75008. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  75009. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  75010. };
  75011. return HingeJoint;
  75012. }(MotorEnabledJoint));
  75013. BABYLON.HingeJoint = HingeJoint;
  75014. /**
  75015. * This class represents a dual hinge physics joint (same as wheel joint)
  75016. */
  75017. var Hinge2Joint = /** @class */ (function (_super) {
  75018. __extends(Hinge2Joint, _super);
  75019. function Hinge2Joint(jointData) {
  75020. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  75021. }
  75022. /**
  75023. * Set the motor values.
  75024. * Attention, this function is plugin specific. Engines won't react 100% the same.
  75025. * @param {number} force the force to apply
  75026. * @param {number} maxForce max force for this motor.
  75027. * @param {motorIndex} the motor's index, 0 or 1.
  75028. */
  75029. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  75030. if (motorIndex === void 0) { motorIndex = 0; }
  75031. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  75032. };
  75033. /**
  75034. * Set the motor limits.
  75035. * Attention, this function is plugin specific. Engines won't react 100% the same.
  75036. * @param {number} upperLimit the upper limit
  75037. * @param {number} lowerLimit lower limit
  75038. * @param {motorIndex} the motor's index, 0 or 1.
  75039. */
  75040. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  75041. if (motorIndex === void 0) { motorIndex = 0; }
  75042. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  75043. };
  75044. return Hinge2Joint;
  75045. }(MotorEnabledJoint));
  75046. BABYLON.Hinge2Joint = Hinge2Joint;
  75047. })(BABYLON || (BABYLON = {}));
  75048. //# sourceMappingURL=babylon.physicsJoint.js.map
  75049. var BABYLON;
  75050. (function (BABYLON) {
  75051. var PhysicsImpostor = /** @class */ (function () {
  75052. function PhysicsImpostor(object, type, _options, _scene) {
  75053. if (_options === void 0) { _options = { mass: 0 }; }
  75054. var _this = this;
  75055. this.object = object;
  75056. this.type = type;
  75057. this._options = _options;
  75058. this._scene = _scene;
  75059. this._bodyUpdateRequired = false;
  75060. this._onBeforePhysicsStepCallbacks = new Array();
  75061. this._onAfterPhysicsStepCallbacks = new Array();
  75062. this._onPhysicsCollideCallbacks = [];
  75063. this._deltaPosition = BABYLON.Vector3.Zero();
  75064. this._isDisposed = false;
  75065. //temp variables for parent rotation calculations
  75066. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  75067. this._tmpQuat = new BABYLON.Quaternion();
  75068. this._tmpQuat2 = new BABYLON.Quaternion();
  75069. /**
  75070. * this function is executed by the physics engine.
  75071. */
  75072. this.beforeStep = function () {
  75073. if (!_this._physicsEngine) {
  75074. return;
  75075. }
  75076. _this.object.translate(_this._deltaPosition, -1);
  75077. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  75078. _this.object.computeWorldMatrix(false);
  75079. if (_this.object.parent && _this.object.rotationQuaternion) {
  75080. _this.getParentsRotation();
  75081. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  75082. }
  75083. else {
  75084. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  75085. }
  75086. if (!_this._options.disableBidirectionalTransformation) {
  75087. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  75088. }
  75089. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  75090. func(_this);
  75091. });
  75092. };
  75093. /**
  75094. * this function is executed by the physics engine.
  75095. */
  75096. this.afterStep = function () {
  75097. if (!_this._physicsEngine) {
  75098. return;
  75099. }
  75100. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  75101. func(_this);
  75102. });
  75103. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  75104. // object has now its world rotation. needs to be converted to local.
  75105. if (_this.object.parent && _this.object.rotationQuaternion) {
  75106. _this.getParentsRotation();
  75107. _this._tmpQuat.conjugateInPlace();
  75108. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  75109. }
  75110. // take the position set and make it the absolute position of this object.
  75111. _this.object.setAbsolutePosition(_this.object.position);
  75112. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  75113. _this.object.translate(_this._deltaPosition, 1);
  75114. };
  75115. /**
  75116. * Legacy collision detection event support
  75117. */
  75118. this.onCollideEvent = null;
  75119. //event and body object due to cannon's event-based architecture.
  75120. this.onCollide = function (e) {
  75121. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  75122. return;
  75123. }
  75124. if (!_this._physicsEngine) {
  75125. return;
  75126. }
  75127. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  75128. if (otherImpostor) {
  75129. // Legacy collision detection event support
  75130. if (_this.onCollideEvent) {
  75131. _this.onCollideEvent(_this, otherImpostor);
  75132. }
  75133. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  75134. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  75135. }).forEach(function (obj) {
  75136. obj.callback(_this, otherImpostor);
  75137. });
  75138. }
  75139. };
  75140. //sanity check!
  75141. if (!this.object) {
  75142. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  75143. return;
  75144. }
  75145. //legacy support for old syntax.
  75146. if (!this._scene && object.getScene) {
  75147. this._scene = object.getScene();
  75148. }
  75149. if (!this._scene) {
  75150. return;
  75151. }
  75152. this._physicsEngine = this._scene.getPhysicsEngine();
  75153. if (!this._physicsEngine) {
  75154. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  75155. }
  75156. else {
  75157. //set the object's quaternion, if not set
  75158. if (!this.object.rotationQuaternion) {
  75159. if (this.object.rotation) {
  75160. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  75161. }
  75162. else {
  75163. this.object.rotationQuaternion = new BABYLON.Quaternion();
  75164. }
  75165. }
  75166. //default options params
  75167. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  75168. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  75169. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  75170. this._joints = [];
  75171. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  75172. if (!this.object.parent || this._options.ignoreParent) {
  75173. this._init();
  75174. }
  75175. else if (this.object.parent.physicsImpostor) {
  75176. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  75177. }
  75178. }
  75179. }
  75180. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  75181. get: function () {
  75182. return this._isDisposed;
  75183. },
  75184. enumerable: true,
  75185. configurable: true
  75186. });
  75187. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  75188. get: function () {
  75189. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  75190. },
  75191. set: function (value) {
  75192. this.setMass(value);
  75193. },
  75194. enumerable: true,
  75195. configurable: true
  75196. });
  75197. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  75198. get: function () {
  75199. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  75200. },
  75201. set: function (value) {
  75202. if (!this._physicsEngine) {
  75203. return;
  75204. }
  75205. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  75206. },
  75207. enumerable: true,
  75208. configurable: true
  75209. });
  75210. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  75211. get: function () {
  75212. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  75213. },
  75214. set: function (value) {
  75215. if (!this._physicsEngine) {
  75216. return;
  75217. }
  75218. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  75219. },
  75220. enumerable: true,
  75221. configurable: true
  75222. });
  75223. /**
  75224. * This function will completly initialize this impostor.
  75225. * It will create a new body - but only if this mesh has no parent.
  75226. * If it has, this impostor will not be used other than to define the impostor
  75227. * of the child mesh.
  75228. */
  75229. PhysicsImpostor.prototype._init = function () {
  75230. if (!this._physicsEngine) {
  75231. return;
  75232. }
  75233. this._physicsEngine.removeImpostor(this);
  75234. this.physicsBody = null;
  75235. this._parent = this._parent || this._getPhysicsParent();
  75236. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  75237. this._physicsEngine.addImpostor(this);
  75238. }
  75239. };
  75240. PhysicsImpostor.prototype._getPhysicsParent = function () {
  75241. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  75242. var parentMesh = this.object.parent;
  75243. return parentMesh.physicsImpostor;
  75244. }
  75245. return null;
  75246. };
  75247. /**
  75248. * Should a new body be generated.
  75249. */
  75250. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  75251. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  75252. };
  75253. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  75254. this.forceUpdate();
  75255. };
  75256. /**
  75257. * Force a regeneration of this or the parent's impostor's body.
  75258. * Use under cautious - This will remove all joints already implemented.
  75259. */
  75260. PhysicsImpostor.prototype.forceUpdate = function () {
  75261. this._init();
  75262. if (this.parent && !this._options.ignoreParent) {
  75263. this.parent.forceUpdate();
  75264. }
  75265. };
  75266. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  75267. /*public get mesh(): AbstractMesh {
  75268. return this._mesh;
  75269. }*/
  75270. /**
  75271. * Gets the body that holds this impostor. Either its own, or its parent.
  75272. */
  75273. get: function () {
  75274. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  75275. },
  75276. /**
  75277. * Set the physics body. Used mainly by the physics engine/plugin
  75278. */
  75279. set: function (physicsBody) {
  75280. if (this._physicsBody && this._physicsEngine) {
  75281. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  75282. }
  75283. this._physicsBody = physicsBody;
  75284. this.resetUpdateFlags();
  75285. },
  75286. enumerable: true,
  75287. configurable: true
  75288. });
  75289. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  75290. get: function () {
  75291. return !this._options.ignoreParent && this._parent ? this._parent : null;
  75292. },
  75293. set: function (value) {
  75294. this._parent = value;
  75295. },
  75296. enumerable: true,
  75297. configurable: true
  75298. });
  75299. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  75300. this._bodyUpdateRequired = false;
  75301. };
  75302. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  75303. if (this.object.getBoundingInfo) {
  75304. var q = this.object.rotationQuaternion;
  75305. //reset rotation
  75306. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  75307. //calculate the world matrix with no rotation
  75308. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  75309. var boundingInfo = this.object.getBoundingInfo();
  75310. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  75311. //bring back the rotation
  75312. this.object.rotationQuaternion = q;
  75313. //calculate the world matrix with the new rotation
  75314. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  75315. return size;
  75316. }
  75317. else {
  75318. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  75319. }
  75320. };
  75321. PhysicsImpostor.prototype.getObjectCenter = function () {
  75322. if (this.object.getBoundingInfo) {
  75323. var boundingInfo = this.object.getBoundingInfo();
  75324. return boundingInfo.boundingBox.centerWorld;
  75325. }
  75326. else {
  75327. return this.object.position;
  75328. }
  75329. };
  75330. /**
  75331. * Get a specific parametes from the options parameter.
  75332. */
  75333. PhysicsImpostor.prototype.getParam = function (paramName) {
  75334. return this._options[paramName];
  75335. };
  75336. /**
  75337. * Sets a specific parameter in the options given to the physics plugin
  75338. */
  75339. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  75340. this._options[paramName] = value;
  75341. this._bodyUpdateRequired = true;
  75342. };
  75343. /**
  75344. * Specifically change the body's mass option. Won't recreate the physics body object
  75345. */
  75346. PhysicsImpostor.prototype.setMass = function (mass) {
  75347. if (this.getParam("mass") !== mass) {
  75348. this.setParam("mass", mass);
  75349. }
  75350. if (this._physicsEngine) {
  75351. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  75352. }
  75353. };
  75354. PhysicsImpostor.prototype.getLinearVelocity = function () {
  75355. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  75356. };
  75357. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  75358. if (this._physicsEngine) {
  75359. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  75360. }
  75361. };
  75362. PhysicsImpostor.prototype.getAngularVelocity = function () {
  75363. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  75364. };
  75365. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  75366. if (this._physicsEngine) {
  75367. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  75368. }
  75369. };
  75370. /**
  75371. * Execute a function with the physics plugin native code.
  75372. * Provide a function the will have two variables - the world object and the physics body object.
  75373. */
  75374. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  75375. if (this._physicsEngine) {
  75376. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  75377. }
  75378. };
  75379. /**
  75380. * Register a function that will be executed before the physics world is stepping forward.
  75381. */
  75382. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  75383. this._onBeforePhysicsStepCallbacks.push(func);
  75384. };
  75385. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  75386. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  75387. if (index > -1) {
  75388. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  75389. }
  75390. else {
  75391. BABYLON.Tools.Warn("Function to remove was not found");
  75392. }
  75393. };
  75394. /**
  75395. * Register a function that will be executed after the physics step
  75396. */
  75397. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  75398. this._onAfterPhysicsStepCallbacks.push(func);
  75399. };
  75400. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  75401. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  75402. if (index > -1) {
  75403. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  75404. }
  75405. else {
  75406. BABYLON.Tools.Warn("Function to remove was not found");
  75407. }
  75408. };
  75409. /**
  75410. * register a function that will be executed when this impostor collides against a different body.
  75411. */
  75412. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  75413. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  75414. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  75415. };
  75416. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  75417. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  75418. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  75419. if (index > -1) {
  75420. this._onPhysicsCollideCallbacks.splice(index, 1);
  75421. }
  75422. else {
  75423. BABYLON.Tools.Warn("Function to remove was not found");
  75424. }
  75425. };
  75426. PhysicsImpostor.prototype.getParentsRotation = function () {
  75427. var parent = this.object.parent;
  75428. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  75429. while (parent) {
  75430. if (parent.rotationQuaternion) {
  75431. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  75432. }
  75433. else {
  75434. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  75435. }
  75436. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  75437. parent = parent.parent;
  75438. }
  75439. return this._tmpQuat;
  75440. };
  75441. /**
  75442. * Apply a force
  75443. */
  75444. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  75445. if (this._physicsEngine) {
  75446. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  75447. }
  75448. return this;
  75449. };
  75450. /**
  75451. * Apply an impulse
  75452. */
  75453. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  75454. if (this._physicsEngine) {
  75455. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  75456. }
  75457. return this;
  75458. };
  75459. /**
  75460. * A help function to create a joint.
  75461. */
  75462. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  75463. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  75464. this.addJoint(otherImpostor, joint);
  75465. return this;
  75466. };
  75467. /**
  75468. * Add a joint to this impostor with a different impostor.
  75469. */
  75470. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  75471. this._joints.push({
  75472. otherImpostor: otherImpostor,
  75473. joint: joint
  75474. });
  75475. if (this._physicsEngine) {
  75476. this._physicsEngine.addJoint(this, otherImpostor, joint);
  75477. }
  75478. return this;
  75479. };
  75480. /**
  75481. * Will keep this body still, in a sleep mode.
  75482. */
  75483. PhysicsImpostor.prototype.sleep = function () {
  75484. if (this._physicsEngine) {
  75485. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  75486. }
  75487. return this;
  75488. };
  75489. /**
  75490. * Wake the body up.
  75491. */
  75492. PhysicsImpostor.prototype.wakeUp = function () {
  75493. if (this._physicsEngine) {
  75494. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  75495. }
  75496. return this;
  75497. };
  75498. PhysicsImpostor.prototype.clone = function (newObject) {
  75499. if (!newObject)
  75500. return null;
  75501. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  75502. };
  75503. PhysicsImpostor.prototype.dispose = function () {
  75504. var _this = this;
  75505. //no dispose if no physics engine is available.
  75506. if (!this._physicsEngine) {
  75507. return;
  75508. }
  75509. this._joints.forEach(function (j) {
  75510. if (_this._physicsEngine) {
  75511. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  75512. }
  75513. });
  75514. //dispose the physics body
  75515. this._physicsEngine.removeImpostor(this);
  75516. if (this.parent) {
  75517. this.parent.forceUpdate();
  75518. }
  75519. else {
  75520. /*this._object.getChildMeshes().forEach(function(mesh) {
  75521. if (mesh.physicsImpostor) {
  75522. if (disposeChildren) {
  75523. mesh.physicsImpostor.dispose();
  75524. mesh.physicsImpostor = null;
  75525. }
  75526. }
  75527. })*/
  75528. }
  75529. this._isDisposed = true;
  75530. };
  75531. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  75532. this._deltaPosition.copyFrom(position);
  75533. };
  75534. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  75535. if (!this._deltaRotation) {
  75536. this._deltaRotation = new BABYLON.Quaternion();
  75537. }
  75538. this._deltaRotation.copyFrom(rotation);
  75539. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  75540. };
  75541. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  75542. if (this._physicsEngine) {
  75543. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  75544. }
  75545. return this;
  75546. };
  75547. PhysicsImpostor.prototype.getRadius = function () {
  75548. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  75549. };
  75550. /**
  75551. * Sync a bone with this impostor
  75552. * @param bone The bone to sync to the impostor.
  75553. * @param boneMesh The mesh that the bone is influencing.
  75554. * @param jointPivot The pivot of the joint / bone in local space.
  75555. * @param distToJoint Optional distance from the impostor to the joint.
  75556. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  75557. */
  75558. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  75559. var tempVec = PhysicsImpostor._tmpVecs[0];
  75560. var mesh = this.object;
  75561. if (mesh.rotationQuaternion) {
  75562. if (adjustRotation) {
  75563. var tempQuat = PhysicsImpostor._tmpQuat;
  75564. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  75565. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  75566. }
  75567. else {
  75568. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  75569. }
  75570. }
  75571. tempVec.x = 0;
  75572. tempVec.y = 0;
  75573. tempVec.z = 0;
  75574. if (jointPivot) {
  75575. tempVec.x = jointPivot.x;
  75576. tempVec.y = jointPivot.y;
  75577. tempVec.z = jointPivot.z;
  75578. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  75579. if (distToJoint === undefined || distToJoint === null) {
  75580. distToJoint = jointPivot.length();
  75581. }
  75582. tempVec.x *= distToJoint;
  75583. tempVec.y *= distToJoint;
  75584. tempVec.z *= distToJoint;
  75585. }
  75586. if (bone.getParent()) {
  75587. tempVec.addInPlace(mesh.getAbsolutePosition());
  75588. bone.setAbsolutePosition(tempVec, boneMesh);
  75589. }
  75590. else {
  75591. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  75592. boneMesh.position.x -= tempVec.x;
  75593. boneMesh.position.y -= tempVec.y;
  75594. boneMesh.position.z -= tempVec.z;
  75595. }
  75596. };
  75597. /**
  75598. * Sync impostor to a bone
  75599. * @param bone The bone that the impostor will be synced to.
  75600. * @param boneMesh The mesh that the bone is influencing.
  75601. * @param jointPivot The pivot of the joint / bone in local space.
  75602. * @param distToJoint Optional distance from the impostor to the joint.
  75603. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  75604. * @param boneAxis Optional vector3 axis the bone is aligned with
  75605. */
  75606. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  75607. var mesh = this.object;
  75608. if (mesh.rotationQuaternion) {
  75609. if (adjustRotation) {
  75610. var tempQuat = PhysicsImpostor._tmpQuat;
  75611. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  75612. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  75613. }
  75614. else {
  75615. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  75616. }
  75617. }
  75618. var pos = PhysicsImpostor._tmpVecs[0];
  75619. var boneDir = PhysicsImpostor._tmpVecs[1];
  75620. if (!boneAxis) {
  75621. boneAxis = PhysicsImpostor._tmpVecs[2];
  75622. boneAxis.x = 0;
  75623. boneAxis.y = 1;
  75624. boneAxis.z = 0;
  75625. }
  75626. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  75627. bone.getAbsolutePositionToRef(boneMesh, pos);
  75628. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  75629. distToJoint = jointPivot.length();
  75630. }
  75631. if (distToJoint !== undefined && distToJoint !== null) {
  75632. pos.x += boneDir.x * distToJoint;
  75633. pos.y += boneDir.y * distToJoint;
  75634. pos.z += boneDir.z * distToJoint;
  75635. }
  75636. mesh.setAbsolutePosition(pos);
  75637. };
  75638. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  75639. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  75640. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  75641. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  75642. //Impostor types
  75643. PhysicsImpostor.NoImpostor = 0;
  75644. PhysicsImpostor.SphereImpostor = 1;
  75645. PhysicsImpostor.BoxImpostor = 2;
  75646. PhysicsImpostor.PlaneImpostor = 3;
  75647. PhysicsImpostor.MeshImpostor = 4;
  75648. PhysicsImpostor.CylinderImpostor = 7;
  75649. PhysicsImpostor.ParticleImpostor = 8;
  75650. PhysicsImpostor.HeightmapImpostor = 9;
  75651. return PhysicsImpostor;
  75652. }());
  75653. BABYLON.PhysicsImpostor = PhysicsImpostor;
  75654. })(BABYLON || (BABYLON = {}));
  75655. //# sourceMappingURL=babylon.physicsImpostor.js.map
  75656. var BABYLON;
  75657. (function (BABYLON) {
  75658. var PhysicsEngine = /** @class */ (function () {
  75659. function PhysicsEngine(gravity, _physicsPlugin) {
  75660. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  75661. this._physicsPlugin = _physicsPlugin;
  75662. //new methods and parameters
  75663. this._impostors = [];
  75664. this._joints = [];
  75665. if (!this._physicsPlugin.isSupported()) {
  75666. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  75667. + "Please make sure it is included.");
  75668. }
  75669. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  75670. this.setGravity(gravity);
  75671. this.setTimeStep();
  75672. }
  75673. PhysicsEngine.prototype.setGravity = function (gravity) {
  75674. this.gravity = gravity;
  75675. this._physicsPlugin.setGravity(this.gravity);
  75676. };
  75677. /**
  75678. * Set the time step of the physics engine.
  75679. * default is 1/60.
  75680. * To slow it down, enter 1/600 for example.
  75681. * To speed it up, 1/30
  75682. * @param {number} newTimeStep the new timestep to apply to this world.
  75683. */
  75684. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  75685. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  75686. this._physicsPlugin.setTimeStep(newTimeStep);
  75687. };
  75688. /**
  75689. * Get the time step of the physics engine.
  75690. */
  75691. PhysicsEngine.prototype.getTimeStep = function () {
  75692. return this._physicsPlugin.getTimeStep();
  75693. };
  75694. PhysicsEngine.prototype.dispose = function () {
  75695. this._impostors.forEach(function (impostor) {
  75696. impostor.dispose();
  75697. });
  75698. this._physicsPlugin.dispose();
  75699. };
  75700. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  75701. return this._physicsPlugin.name;
  75702. };
  75703. /**
  75704. * Adding a new impostor for the impostor tracking.
  75705. * This will be done by the impostor itself.
  75706. * @param {PhysicsImpostor} impostor the impostor to add
  75707. */
  75708. PhysicsEngine.prototype.addImpostor = function (impostor) {
  75709. impostor.uniqueId = this._impostors.push(impostor);
  75710. //if no parent, generate the body
  75711. if (!impostor.parent) {
  75712. this._physicsPlugin.generatePhysicsBody(impostor);
  75713. }
  75714. };
  75715. /**
  75716. * Remove an impostor from the engine.
  75717. * This impostor and its mesh will not longer be updated by the physics engine.
  75718. * @param {PhysicsImpostor} impostor the impostor to remove
  75719. */
  75720. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  75721. var index = this._impostors.indexOf(impostor);
  75722. if (index > -1) {
  75723. var removed = this._impostors.splice(index, 1);
  75724. //Is it needed?
  75725. if (removed.length) {
  75726. //this will also remove it from the world.
  75727. removed[0].physicsBody = null;
  75728. }
  75729. }
  75730. };
  75731. /**
  75732. * Add a joint to the physics engine
  75733. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  75734. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  75735. * @param {PhysicsJoint} the joint that will connect both impostors.
  75736. */
  75737. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  75738. var impostorJoint = {
  75739. mainImpostor: mainImpostor,
  75740. connectedImpostor: connectedImpostor,
  75741. joint: joint
  75742. };
  75743. joint.physicsPlugin = this._physicsPlugin;
  75744. this._joints.push(impostorJoint);
  75745. this._physicsPlugin.generateJoint(impostorJoint);
  75746. };
  75747. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  75748. var matchingJoints = this._joints.filter(function (impostorJoint) {
  75749. return (impostorJoint.connectedImpostor === connectedImpostor
  75750. && impostorJoint.joint === joint
  75751. && impostorJoint.mainImpostor === mainImpostor);
  75752. });
  75753. if (matchingJoints.length) {
  75754. this._physicsPlugin.removeJoint(matchingJoints[0]);
  75755. //TODO remove it from the list as well
  75756. }
  75757. };
  75758. /**
  75759. * Called by the scene. no need to call it.
  75760. */
  75761. PhysicsEngine.prototype._step = function (delta) {
  75762. var _this = this;
  75763. //check if any mesh has no body / requires an update
  75764. this._impostors.forEach(function (impostor) {
  75765. if (impostor.isBodyInitRequired()) {
  75766. _this._physicsPlugin.generatePhysicsBody(impostor);
  75767. }
  75768. });
  75769. if (delta > 0.1) {
  75770. delta = 0.1;
  75771. }
  75772. else if (delta <= 0) {
  75773. delta = 1.0 / 60.0;
  75774. }
  75775. this._physicsPlugin.executeStep(delta, this._impostors);
  75776. };
  75777. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  75778. return this._physicsPlugin;
  75779. };
  75780. PhysicsEngine.prototype.getImpostors = function () {
  75781. return this._impostors;
  75782. };
  75783. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  75784. for (var i = 0; i < this._impostors.length; ++i) {
  75785. if (this._impostors[i].object === object) {
  75786. return this._impostors[i];
  75787. }
  75788. }
  75789. return null;
  75790. };
  75791. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  75792. for (var i = 0; i < this._impostors.length; ++i) {
  75793. if (this._impostors[i].physicsBody === body) {
  75794. return this._impostors[i];
  75795. }
  75796. }
  75797. return null;
  75798. };
  75799. // Statics
  75800. PhysicsEngine.Epsilon = 0.001;
  75801. return PhysicsEngine;
  75802. }());
  75803. BABYLON.PhysicsEngine = PhysicsEngine;
  75804. })(BABYLON || (BABYLON = {}));
  75805. //# sourceMappingURL=babylon.physicsEngine.js.map
  75806. var BABYLON;
  75807. (function (BABYLON) {
  75808. var PhysicsHelper = /** @class */ (function () {
  75809. function PhysicsHelper(scene) {
  75810. this._scene = scene;
  75811. this._physicsEngine = this._scene.getPhysicsEngine();
  75812. if (!this._physicsEngine) {
  75813. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  75814. }
  75815. }
  75816. /**
  75817. * @param {Vector3} origin the origin of the explosion
  75818. * @param {number} radius the explosion radius
  75819. * @param {number} strength the explosion strength
  75820. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  75821. */
  75822. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  75823. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  75824. if (!this._physicsEngine) {
  75825. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  75826. return null;
  75827. }
  75828. var impostors = this._physicsEngine.getImpostors();
  75829. if (impostors.length === 0) {
  75830. return null;
  75831. }
  75832. var event = new PhysicsRadialExplosionEvent(this._scene);
  75833. impostors.forEach(function (impostor) {
  75834. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  75835. if (!impostorForceAndContactPoint) {
  75836. return;
  75837. }
  75838. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  75839. });
  75840. event.dispose(false);
  75841. return event;
  75842. };
  75843. /**
  75844. * @param {Vector3} origin the origin of the explosion
  75845. * @param {number} radius the explosion radius
  75846. * @param {number} strength the explosion strength
  75847. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  75848. */
  75849. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  75850. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  75851. if (!this._physicsEngine) {
  75852. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  75853. return null;
  75854. }
  75855. var impostors = this._physicsEngine.getImpostors();
  75856. if (impostors.length === 0) {
  75857. return null;
  75858. }
  75859. var event = new PhysicsRadialExplosionEvent(this._scene);
  75860. impostors.forEach(function (impostor) {
  75861. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  75862. if (!impostorForceAndContactPoint) {
  75863. return;
  75864. }
  75865. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  75866. });
  75867. event.dispose(false);
  75868. return event;
  75869. };
  75870. /**
  75871. * @param {Vector3} origin the origin of the explosion
  75872. * @param {number} radius the explosion radius
  75873. * @param {number} strength the explosion strength
  75874. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  75875. */
  75876. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  75877. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  75878. if (!this._physicsEngine) {
  75879. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  75880. return null;
  75881. }
  75882. var impostors = this._physicsEngine.getImpostors();
  75883. if (impostors.length === 0) {
  75884. return null;
  75885. }
  75886. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  75887. event.dispose(false);
  75888. return event;
  75889. };
  75890. /**
  75891. * @param {Vector3} origin the origin of the updraft
  75892. * @param {number} radius the radius of the updraft
  75893. * @param {number} strength the strength of the updraft
  75894. * @param {number} height the height of the updraft
  75895. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  75896. */
  75897. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  75898. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  75899. if (!this._physicsEngine) {
  75900. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  75901. return null;
  75902. }
  75903. if (this._physicsEngine.getImpostors().length === 0) {
  75904. return null;
  75905. }
  75906. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  75907. event.dispose(false);
  75908. return event;
  75909. };
  75910. /**
  75911. * @param {Vector3} origin the of the vortex
  75912. * @param {number} radius the radius of the vortex
  75913. * @param {number} strength the strength of the vortex
  75914. * @param {number} height the height of the vortex
  75915. */
  75916. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  75917. if (!this._physicsEngine) {
  75918. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  75919. return null;
  75920. }
  75921. if (this._physicsEngine.getImpostors().length === 0) {
  75922. return null;
  75923. }
  75924. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  75925. event.dispose(false);
  75926. return event;
  75927. };
  75928. return PhysicsHelper;
  75929. }());
  75930. BABYLON.PhysicsHelper = PhysicsHelper;
  75931. /***** Radial explosion *****/
  75932. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  75933. function PhysicsRadialExplosionEvent(scene) {
  75934. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  75935. this._rays = [];
  75936. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  75937. this._scene = scene;
  75938. }
  75939. /**
  75940. * Returns the data related to the radial explosion event (sphere & rays).
  75941. * @returns {PhysicsRadialExplosionEventData}
  75942. */
  75943. PhysicsRadialExplosionEvent.prototype.getData = function () {
  75944. this._dataFetched = true;
  75945. return {
  75946. sphere: this._sphere,
  75947. rays: this._rays,
  75948. };
  75949. };
  75950. /**
  75951. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  75952. * @param impostor
  75953. * @param {Vector3} origin the origin of the explosion
  75954. * @param {number} radius the explosion radius
  75955. * @param {number} strength the explosion strength
  75956. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  75957. * @returns {Nullable<PhysicsForceAndContactPoint>}
  75958. */
  75959. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  75960. if (impostor.mass === 0) {
  75961. return null;
  75962. }
  75963. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  75964. return null;
  75965. }
  75966. if (impostor.object.getClassName() !== 'Mesh') {
  75967. return null;
  75968. }
  75969. var impostorObject = impostor.object;
  75970. var impostorObjectCenter = impostor.getObjectCenter();
  75971. var direction = impostorObjectCenter.subtract(origin);
  75972. var ray = new BABYLON.Ray(origin, direction, radius);
  75973. this._rays.push(ray);
  75974. var hit = ray.intersectsMesh(impostorObject);
  75975. var contactPoint = hit.pickedPoint;
  75976. if (!contactPoint) {
  75977. return null;
  75978. }
  75979. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  75980. if (distanceFromOrigin > radius) {
  75981. return null;
  75982. }
  75983. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  75984. ? strength
  75985. : strength * (1 - (distanceFromOrigin / radius));
  75986. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  75987. return { force: force, contactPoint: contactPoint };
  75988. };
  75989. /**
  75990. * Disposes the sphere.
  75991. * @param {bolean} force
  75992. */
  75993. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  75994. var _this = this;
  75995. if (force === void 0) { force = true; }
  75996. if (force) {
  75997. this._sphere.dispose();
  75998. }
  75999. else {
  76000. setTimeout(function () {
  76001. if (!_this._dataFetched) {
  76002. _this._sphere.dispose();
  76003. }
  76004. }, 0);
  76005. }
  76006. };
  76007. /*** Helpers ***/
  76008. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  76009. if (!this._sphere) {
  76010. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  76011. this._sphere.isVisible = false;
  76012. }
  76013. };
  76014. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  76015. var impostorObject = impostor.object;
  76016. this._prepareSphere();
  76017. this._sphere.position = origin;
  76018. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  76019. this._sphere._updateBoundingInfo();
  76020. this._sphere.computeWorldMatrix(true);
  76021. return this._sphere.intersectsMesh(impostorObject, true);
  76022. };
  76023. return PhysicsRadialExplosionEvent;
  76024. }());
  76025. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  76026. /***** Gravitational Field *****/
  76027. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  76028. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  76029. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  76030. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  76031. this._physicsHelper = physicsHelper;
  76032. this._scene = scene;
  76033. this._origin = origin;
  76034. this._radius = radius;
  76035. this._strength = strength;
  76036. this._falloff = falloff;
  76037. this._tickCallback = this._tick.bind(this);
  76038. }
  76039. /**
  76040. * Returns the data related to the gravitational field event (sphere).
  76041. * @returns {PhysicsGravitationalFieldEventData}
  76042. */
  76043. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  76044. this._dataFetched = true;
  76045. return {
  76046. sphere: this._sphere,
  76047. };
  76048. };
  76049. /**
  76050. * Enables the gravitational field.
  76051. */
  76052. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  76053. this._tickCallback.call(this);
  76054. this._scene.registerBeforeRender(this._tickCallback);
  76055. };
  76056. /**
  76057. * Disables the gravitational field.
  76058. */
  76059. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  76060. this._scene.unregisterBeforeRender(this._tickCallback);
  76061. };
  76062. /**
  76063. * Disposes the sphere.
  76064. * @param {bolean} force
  76065. */
  76066. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  76067. var _this = this;
  76068. if (force === void 0) { force = true; }
  76069. if (force) {
  76070. this._sphere.dispose();
  76071. }
  76072. else {
  76073. setTimeout(function () {
  76074. if (!_this._dataFetched) {
  76075. _this._sphere.dispose();
  76076. }
  76077. }, 0);
  76078. }
  76079. };
  76080. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  76081. // Since the params won't change, we fetch the event only once
  76082. if (this._sphere) {
  76083. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  76084. }
  76085. else {
  76086. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  76087. if (radialExplosionEvent) {
  76088. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  76089. }
  76090. }
  76091. };
  76092. return PhysicsGravitationalFieldEvent;
  76093. }());
  76094. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  76095. /***** Updraft *****/
  76096. var PhysicsUpdraftEvent = /** @class */ (function () {
  76097. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  76098. this._scene = _scene;
  76099. this._origin = _origin;
  76100. this._radius = _radius;
  76101. this._strength = _strength;
  76102. this._height = _height;
  76103. this._updraftMode = _updraftMode;
  76104. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  76105. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  76106. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  76107. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  76108. this._physicsEngine = this._scene.getPhysicsEngine();
  76109. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  76110. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  76111. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  76112. this._originDirection = this._origin.subtract(this._originTop).normalize();
  76113. }
  76114. this._tickCallback = this._tick.bind(this);
  76115. }
  76116. /**
  76117. * Returns the data related to the updraft event (cylinder).
  76118. * @returns {PhysicsUpdraftEventData}
  76119. */
  76120. PhysicsUpdraftEvent.prototype.getData = function () {
  76121. this._dataFetched = true;
  76122. return {
  76123. cylinder: this._cylinder,
  76124. };
  76125. };
  76126. /**
  76127. * Enables the updraft.
  76128. */
  76129. PhysicsUpdraftEvent.prototype.enable = function () {
  76130. this._tickCallback.call(this);
  76131. this._scene.registerBeforeRender(this._tickCallback);
  76132. };
  76133. /**
  76134. * Disables the cortex.
  76135. */
  76136. PhysicsUpdraftEvent.prototype.disable = function () {
  76137. this._scene.unregisterBeforeRender(this._tickCallback);
  76138. };
  76139. /**
  76140. * Disposes the sphere.
  76141. * @param {bolean} force
  76142. */
  76143. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  76144. var _this = this;
  76145. if (force === void 0) { force = true; }
  76146. if (force) {
  76147. this._cylinder.dispose();
  76148. }
  76149. else {
  76150. setTimeout(function () {
  76151. if (!_this._dataFetched) {
  76152. _this._cylinder.dispose();
  76153. }
  76154. }, 0);
  76155. }
  76156. };
  76157. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  76158. if (impostor.mass === 0) {
  76159. return null;
  76160. }
  76161. if (!this._intersectsWithCylinder(impostor)) {
  76162. return null;
  76163. }
  76164. var impostorObjectCenter = impostor.getObjectCenter();
  76165. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  76166. var direction = this._originDirection;
  76167. }
  76168. else {
  76169. var direction = impostorObjectCenter.subtract(this._originTop);
  76170. }
  76171. var multiplier = this._strength * -1;
  76172. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  76173. return { force: force, contactPoint: impostorObjectCenter };
  76174. };
  76175. PhysicsUpdraftEvent.prototype._tick = function () {
  76176. var _this = this;
  76177. this._physicsEngine.getImpostors().forEach(function (impostor) {
  76178. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  76179. if (!impostorForceAndContactPoint) {
  76180. return;
  76181. }
  76182. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  76183. });
  76184. };
  76185. /*** Helpers ***/
  76186. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  76187. if (!this._cylinder) {
  76188. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  76189. height: this._height,
  76190. diameter: this._radius * 2,
  76191. }, this._scene);
  76192. this._cylinder.isVisible = false;
  76193. }
  76194. };
  76195. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  76196. var impostorObject = impostor.object;
  76197. this._prepareCylinder();
  76198. this._cylinder.position = this._cylinderPosition;
  76199. return this._cylinder.intersectsMesh(impostorObject, true);
  76200. };
  76201. return PhysicsUpdraftEvent;
  76202. }());
  76203. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  76204. /***** Vortex *****/
  76205. var PhysicsVortexEvent = /** @class */ (function () {
  76206. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  76207. this._scene = _scene;
  76208. this._origin = _origin;
  76209. this._radius = _radius;
  76210. this._strength = _strength;
  76211. this._height = _height;
  76212. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  76213. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  76214. this._updraftMultiplier = 0.02;
  76215. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  76216. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  76217. this._physicsEngine = this._scene.getPhysicsEngine();
  76218. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  76219. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  76220. this._tickCallback = this._tick.bind(this);
  76221. }
  76222. /**
  76223. * Returns the data related to the vortex event (cylinder).
  76224. * @returns {PhysicsVortexEventData}
  76225. */
  76226. PhysicsVortexEvent.prototype.getData = function () {
  76227. this._dataFetched = true;
  76228. return {
  76229. cylinder: this._cylinder,
  76230. };
  76231. };
  76232. /**
  76233. * Enables the vortex.
  76234. */
  76235. PhysicsVortexEvent.prototype.enable = function () {
  76236. this._tickCallback.call(this);
  76237. this._scene.registerBeforeRender(this._tickCallback);
  76238. };
  76239. /**
  76240. * Disables the cortex.
  76241. */
  76242. PhysicsVortexEvent.prototype.disable = function () {
  76243. this._scene.unregisterBeforeRender(this._tickCallback);
  76244. };
  76245. /**
  76246. * Disposes the sphere.
  76247. * @param {bolean} force
  76248. */
  76249. PhysicsVortexEvent.prototype.dispose = function (force) {
  76250. var _this = this;
  76251. if (force === void 0) { force = true; }
  76252. if (force) {
  76253. this._cylinder.dispose();
  76254. }
  76255. else {
  76256. setTimeout(function () {
  76257. if (!_this._dataFetched) {
  76258. _this._cylinder.dispose();
  76259. }
  76260. }, 0);
  76261. }
  76262. };
  76263. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  76264. if (impostor.mass === 0) {
  76265. return null;
  76266. }
  76267. if (!this._intersectsWithCylinder(impostor)) {
  76268. return null;
  76269. }
  76270. if (impostor.object.getClassName() !== 'Mesh') {
  76271. return null;
  76272. }
  76273. var impostorObject = impostor.object;
  76274. var impostorObjectCenter = impostor.getObjectCenter();
  76275. var originOnPlane = new BABYLON.Vector3(this._origin.x, impostorObjectCenter.y, this._origin.z); // the distance to the origin as if both objects were on a plane (Y-axis)
  76276. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  76277. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  76278. var hit = ray.intersectsMesh(impostorObject);
  76279. var contactPoint = hit.pickedPoint;
  76280. if (!contactPoint) {
  76281. return null;
  76282. }
  76283. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  76284. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  76285. var directionToOrigin = contactPoint.normalize();
  76286. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  76287. directionToOrigin = directionToOrigin.negate();
  76288. }
  76289. // TODO: find a more physically based solution
  76290. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  76291. var forceX = directionToOrigin.x * this._strength / 8;
  76292. var forceY = directionToOrigin.y * this._updraftMultiplier;
  76293. var forceZ = directionToOrigin.z * this._strength / 8;
  76294. }
  76295. else {
  76296. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  76297. var forceY = this._originTop.y * this._updraftMultiplier;
  76298. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  76299. }
  76300. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  76301. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  76302. return { force: force, contactPoint: impostorObjectCenter };
  76303. };
  76304. PhysicsVortexEvent.prototype._tick = function () {
  76305. var _this = this;
  76306. this._physicsEngine.getImpostors().forEach(function (impostor) {
  76307. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  76308. if (!impostorForceAndContactPoint) {
  76309. return;
  76310. }
  76311. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  76312. });
  76313. };
  76314. /*** Helpers ***/
  76315. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  76316. if (!this._cylinder) {
  76317. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  76318. height: this._height,
  76319. diameter: this._radius * 2,
  76320. }, this._scene);
  76321. this._cylinder.isVisible = false;
  76322. }
  76323. };
  76324. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  76325. var impostorObject = impostor.object;
  76326. this._prepareCylinder();
  76327. this._cylinder.position = this._cylinderPosition;
  76328. return this._cylinder.intersectsMesh(impostorObject, true);
  76329. };
  76330. return PhysicsVortexEvent;
  76331. }());
  76332. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  76333. /***** Enums *****/
  76334. /**
  76335. * The strenght of the force in correspondence to the distance of the affected object
  76336. */
  76337. var PhysicsRadialImpulseFalloff;
  76338. (function (PhysicsRadialImpulseFalloff) {
  76339. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  76340. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear"; // impulse gets weaker if it's further from the origin
  76341. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  76342. /**
  76343. * The strenght of the force in correspondence to the distance of the affected object
  76344. */
  76345. var PhysicsUpdraftMode;
  76346. (function (PhysicsUpdraftMode) {
  76347. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  76348. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular"; // once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder
  76349. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  76350. })(BABYLON || (BABYLON = {}));
  76351. //# sourceMappingURL=babylon.physicsHelper.js.map
  76352. var BABYLON;
  76353. (function (BABYLON) {
  76354. var CannonJSPlugin = /** @class */ (function () {
  76355. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  76356. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  76357. if (iterations === void 0) { iterations = 10; }
  76358. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  76359. this.name = "CannonJSPlugin";
  76360. this._physicsMaterials = new Array();
  76361. this._fixedTimeStep = 1 / 60;
  76362. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  76363. this.BJSCANNON = typeof CANNON !== 'undefined' ? CANNON : ( true ? __webpack_require__(17) : undefined);
  76364. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  76365. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  76366. this._tmpPosition = BABYLON.Vector3.Zero();
  76367. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  76368. this._tmpUnityRotation = new BABYLON.Quaternion();
  76369. if (!this.isSupported()) {
  76370. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  76371. return;
  76372. }
  76373. this._extendNamespace();
  76374. this.world = new this.BJSCANNON.World();
  76375. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  76376. this.world.solver.iterations = iterations;
  76377. }
  76378. CannonJSPlugin.prototype.setGravity = function (gravity) {
  76379. this.world.gravity.copy(gravity);
  76380. };
  76381. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  76382. this._fixedTimeStep = timeStep;
  76383. };
  76384. CannonJSPlugin.prototype.getTimeStep = function () {
  76385. return this._fixedTimeStep;
  76386. };
  76387. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  76388. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  76389. };
  76390. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  76391. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  76392. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  76393. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  76394. };
  76395. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  76396. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  76397. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  76398. impostor.physicsBody.applyForce(impulse, worldPoint);
  76399. };
  76400. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  76401. //parent-child relationship. Does this impostor has a parent impostor?
  76402. if (impostor.parent) {
  76403. if (impostor.physicsBody) {
  76404. this.removePhysicsBody(impostor);
  76405. //TODO is that needed?
  76406. impostor.forceUpdate();
  76407. }
  76408. return;
  76409. }
  76410. //should a new body be created for this impostor?
  76411. if (impostor.isBodyInitRequired()) {
  76412. var shape = this._createShape(impostor);
  76413. //unregister events, if body is being changed
  76414. var oldBody = impostor.physicsBody;
  76415. if (oldBody) {
  76416. this.removePhysicsBody(impostor);
  76417. }
  76418. //create the body and material
  76419. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  76420. var bodyCreationObject = {
  76421. mass: impostor.getParam("mass"),
  76422. material: material
  76423. };
  76424. // A simple extend, in case native options were used.
  76425. var nativeOptions = impostor.getParam("nativeOptions");
  76426. for (var key in nativeOptions) {
  76427. if (nativeOptions.hasOwnProperty(key)) {
  76428. bodyCreationObject[key] = nativeOptions[key];
  76429. }
  76430. }
  76431. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  76432. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  76433. this.world.addEventListener("preStep", impostor.beforeStep);
  76434. this.world.addEventListener("postStep", impostor.afterStep);
  76435. impostor.physicsBody.addShape(shape);
  76436. this.world.add(impostor.physicsBody);
  76437. //try to keep the body moving in the right direction by taking old properties.
  76438. //Should be tested!
  76439. if (oldBody) {
  76440. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  76441. impostor.physicsBody[param].copy(oldBody[param]);
  76442. });
  76443. }
  76444. this._processChildMeshes(impostor);
  76445. }
  76446. //now update the body's transformation
  76447. this._updatePhysicsBodyTransformation(impostor);
  76448. };
  76449. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  76450. var _this = this;
  76451. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  76452. var currentRotation = mainImpostor.object.rotationQuaternion;
  76453. if (meshChildren.length) {
  76454. var processMesh = function (localPosition, mesh) {
  76455. if (!currentRotation || !mesh.rotationQuaternion) {
  76456. return;
  76457. }
  76458. var childImpostor = mesh.getPhysicsImpostor();
  76459. if (childImpostor) {
  76460. var parent = childImpostor.parent;
  76461. if (parent !== mainImpostor) {
  76462. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  76463. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  76464. if (childImpostor.physicsBody) {
  76465. _this.removePhysicsBody(childImpostor);
  76466. childImpostor.physicsBody = null;
  76467. }
  76468. childImpostor.parent = mainImpostor;
  76469. childImpostor.resetUpdateFlags();
  76470. 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));
  76471. //Add the mass of the children.
  76472. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  76473. }
  76474. }
  76475. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  76476. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  76477. };
  76478. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  76479. }
  76480. };
  76481. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  76482. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  76483. this.world.removeEventListener("preStep", impostor.beforeStep);
  76484. this.world.removeEventListener("postStep", impostor.afterStep);
  76485. this.world.remove(impostor.physicsBody);
  76486. };
  76487. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  76488. var mainBody = impostorJoint.mainImpostor.physicsBody;
  76489. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  76490. if (!mainBody || !connectedBody) {
  76491. return;
  76492. }
  76493. var constraint;
  76494. var jointData = impostorJoint.joint.jointData;
  76495. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  76496. var constraintData = {
  76497. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  76498. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  76499. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  76500. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  76501. maxForce: jointData.nativeParams.maxForce,
  76502. collideConnected: !!jointData.collision
  76503. };
  76504. switch (impostorJoint.joint.type) {
  76505. case BABYLON.PhysicsJoint.HingeJoint:
  76506. case BABYLON.PhysicsJoint.Hinge2Joint:
  76507. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  76508. break;
  76509. case BABYLON.PhysicsJoint.DistanceJoint:
  76510. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  76511. break;
  76512. case BABYLON.PhysicsJoint.SpringJoint:
  76513. var springData = jointData;
  76514. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  76515. restLength: springData.length,
  76516. stiffness: springData.stiffness,
  76517. damping: springData.damping,
  76518. localAnchorA: constraintData.pivotA,
  76519. localAnchorB: constraintData.pivotB
  76520. });
  76521. break;
  76522. case BABYLON.PhysicsJoint.LockJoint:
  76523. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  76524. break;
  76525. case BABYLON.PhysicsJoint.PointToPointJoint:
  76526. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  76527. default:
  76528. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  76529. break;
  76530. }
  76531. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  76532. constraint.collideConnected = !!jointData.collision;
  76533. impostorJoint.joint.physicsJoint = constraint;
  76534. //don't add spring as constraint, as it is not one.
  76535. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  76536. this.world.addConstraint(constraint);
  76537. }
  76538. else {
  76539. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  76540. constraint.applyForce();
  76541. });
  76542. }
  76543. };
  76544. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  76545. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  76546. };
  76547. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  76548. var index;
  76549. var mat;
  76550. for (index = 0; index < this._physicsMaterials.length; index++) {
  76551. mat = this._physicsMaterials[index];
  76552. if (mat.friction === friction && mat.restitution === restitution) {
  76553. return mat;
  76554. }
  76555. }
  76556. var currentMat = new this.BJSCANNON.Material(name);
  76557. currentMat.friction = friction;
  76558. currentMat.restitution = restitution;
  76559. this._physicsMaterials.push(currentMat);
  76560. return currentMat;
  76561. };
  76562. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  76563. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  76564. };
  76565. CannonJSPlugin.prototype._createShape = function (impostor) {
  76566. var object = impostor.object;
  76567. var returnValue;
  76568. var extendSize = impostor.getObjectExtendSize();
  76569. switch (impostor.type) {
  76570. case BABYLON.PhysicsImpostor.SphereImpostor:
  76571. var radiusX = extendSize.x;
  76572. var radiusY = extendSize.y;
  76573. var radiusZ = extendSize.z;
  76574. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  76575. break;
  76576. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  76577. case BABYLON.PhysicsImpostor.CylinderImpostor:
  76578. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  76579. break;
  76580. case BABYLON.PhysicsImpostor.BoxImpostor:
  76581. var box = extendSize.scale(0.5);
  76582. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  76583. break;
  76584. case BABYLON.PhysicsImpostor.PlaneImpostor:
  76585. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  76586. returnValue = new this.BJSCANNON.Plane();
  76587. break;
  76588. case BABYLON.PhysicsImpostor.MeshImpostor:
  76589. // should transform the vertex data to world coordinates!!
  76590. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  76591. var rawFaces = object.getIndices ? object.getIndices() : [];
  76592. if (!rawVerts)
  76593. return;
  76594. // get only scale! so the object could transform correctly.
  76595. var oldPosition = object.position.clone();
  76596. var oldRotation = object.rotation && object.rotation.clone();
  76597. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  76598. object.position.copyFromFloats(0, 0, 0);
  76599. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  76600. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  76601. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  76602. var transform = object.computeWorldMatrix(true);
  76603. // convert rawVerts to object space
  76604. var temp = new Array();
  76605. var index;
  76606. for (index = 0; index < rawVerts.length; index += 3) {
  76607. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  76608. }
  76609. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  76610. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  76611. //now set back the transformation!
  76612. object.position.copyFrom(oldPosition);
  76613. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  76614. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  76615. break;
  76616. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  76617. var oldPosition2 = object.position.clone();
  76618. var oldRotation2 = object.rotation && object.rotation.clone();
  76619. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  76620. object.position.copyFromFloats(0, 0, 0);
  76621. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  76622. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  76623. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  76624. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  76625. returnValue = this._createHeightmap(object);
  76626. object.position.copyFrom(oldPosition2);
  76627. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  76628. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  76629. object.computeWorldMatrix(true);
  76630. break;
  76631. case BABYLON.PhysicsImpostor.ParticleImpostor:
  76632. returnValue = new this.BJSCANNON.Particle();
  76633. break;
  76634. }
  76635. return returnValue;
  76636. };
  76637. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  76638. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  76639. var transform = object.computeWorldMatrix(true);
  76640. // convert rawVerts to object space
  76641. var temp = new Array();
  76642. var index;
  76643. for (index = 0; index < pos.length; index += 3) {
  76644. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  76645. }
  76646. pos = temp;
  76647. var matrix = new Array();
  76648. //For now pointDepth will not be used and will be automatically calculated.
  76649. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  76650. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  76651. var boundingInfo = object.getBoundingInfo();
  76652. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  76653. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  76654. var elementSize = dim * 2 / arraySize;
  76655. for (var i = 0; i < pos.length; i = i + 3) {
  76656. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  76657. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  76658. var y = -pos[i + 2] + minY;
  76659. if (!matrix[x]) {
  76660. matrix[x] = [];
  76661. }
  76662. if (!matrix[x][z]) {
  76663. matrix[x][z] = y;
  76664. }
  76665. matrix[x][z] = Math.max(y, matrix[x][z]);
  76666. }
  76667. for (var x = 0; x <= arraySize; ++x) {
  76668. if (!matrix[x]) {
  76669. var loc = 1;
  76670. while (!matrix[(x + loc) % arraySize]) {
  76671. loc++;
  76672. }
  76673. matrix[x] = matrix[(x + loc) % arraySize].slice();
  76674. //console.log("missing x", x);
  76675. }
  76676. for (var z = 0; z <= arraySize; ++z) {
  76677. if (!matrix[x][z]) {
  76678. var loc = 1;
  76679. var newValue;
  76680. while (newValue === undefined) {
  76681. newValue = matrix[x][(z + loc++) % arraySize];
  76682. }
  76683. matrix[x][z] = newValue;
  76684. }
  76685. }
  76686. }
  76687. var shape = new this.BJSCANNON.Heightfield(matrix, {
  76688. elementSize: elementSize
  76689. });
  76690. //For future reference, needed for body transformation
  76691. shape.minY = minY;
  76692. return shape;
  76693. };
  76694. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  76695. var object = impostor.object;
  76696. //make sure it is updated...
  76697. object.computeWorldMatrix && object.computeWorldMatrix(true);
  76698. // The delta between the mesh position and the mesh bounding box center
  76699. var bInfo = object.getBoundingInfo();
  76700. if (!bInfo)
  76701. return;
  76702. var center = impostor.getObjectCenter();
  76703. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  76704. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  76705. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  76706. this._tmpPosition.copyFrom(center);
  76707. var quaternion = object.rotationQuaternion;
  76708. if (!quaternion) {
  76709. return;
  76710. }
  76711. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  76712. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  76713. //-90 DEG in X, precalculated
  76714. quaternion = quaternion.multiply(this._minus90X);
  76715. //Invert! (Precalculated, 90 deg in X)
  76716. //No need to clone. this will never change.
  76717. impostor.setDeltaRotation(this._plus90X);
  76718. }
  76719. //If it is a heightfield, if should be centered.
  76720. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  76721. var mesh = object;
  76722. var boundingInfo = mesh.getBoundingInfo();
  76723. //calculate the correct body position:
  76724. var rotationQuaternion = mesh.rotationQuaternion;
  76725. mesh.rotationQuaternion = this._tmpUnityRotation;
  76726. mesh.computeWorldMatrix(true);
  76727. //get original center with no rotation
  76728. var c = center.clone();
  76729. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  76730. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  76731. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  76732. mesh.setPreTransformMatrix(p);
  76733. mesh.computeWorldMatrix(true);
  76734. //calculate the translation
  76735. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  76736. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  76737. //add it inverted to the delta
  76738. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  76739. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  76740. //rotation is back
  76741. mesh.rotationQuaternion = rotationQuaternion;
  76742. mesh.setPreTransformMatrix(oldPivot);
  76743. mesh.computeWorldMatrix(true);
  76744. }
  76745. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  76746. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  76747. //this._tmpPosition.copyFrom(object.position);
  76748. }
  76749. impostor.setDeltaPosition(this._tmpDeltaPosition);
  76750. //Now update the impostor object
  76751. impostor.physicsBody.position.copy(this._tmpPosition);
  76752. impostor.physicsBody.quaternion.copy(quaternion);
  76753. };
  76754. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  76755. impostor.object.position.copyFrom(impostor.physicsBody.position);
  76756. if (impostor.object.rotationQuaternion) {
  76757. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  76758. }
  76759. };
  76760. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  76761. impostor.physicsBody.position.copy(newPosition);
  76762. impostor.physicsBody.quaternion.copy(newRotation);
  76763. };
  76764. CannonJSPlugin.prototype.isSupported = function () {
  76765. return this.BJSCANNON !== undefined;
  76766. };
  76767. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  76768. impostor.physicsBody.velocity.copy(velocity);
  76769. };
  76770. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  76771. impostor.physicsBody.angularVelocity.copy(velocity);
  76772. };
  76773. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  76774. var v = impostor.physicsBody.velocity;
  76775. if (!v) {
  76776. return null;
  76777. }
  76778. return new BABYLON.Vector3(v.x, v.y, v.z);
  76779. };
  76780. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  76781. var v = impostor.physicsBody.angularVelocity;
  76782. if (!v) {
  76783. return null;
  76784. }
  76785. return new BABYLON.Vector3(v.x, v.y, v.z);
  76786. };
  76787. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  76788. impostor.physicsBody.mass = mass;
  76789. impostor.physicsBody.updateMassProperties();
  76790. };
  76791. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  76792. return impostor.physicsBody.mass;
  76793. };
  76794. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  76795. return impostor.physicsBody.material.friction;
  76796. };
  76797. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  76798. impostor.physicsBody.material.friction = friction;
  76799. };
  76800. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  76801. return impostor.physicsBody.material.restitution;
  76802. };
  76803. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  76804. impostor.physicsBody.material.restitution = restitution;
  76805. };
  76806. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  76807. impostor.physicsBody.sleep();
  76808. };
  76809. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  76810. impostor.physicsBody.wakeUp();
  76811. };
  76812. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  76813. joint.physicsJoint.distance = maxDistance;
  76814. };
  76815. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  76816. // if (!motorIndex) {
  76817. // joint.physicsJoint.enableMotor();
  76818. // }
  76819. // }
  76820. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  76821. // if (!motorIndex) {
  76822. // joint.physicsJoint.disableMotor();
  76823. // }
  76824. // }
  76825. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  76826. if (!motorIndex) {
  76827. joint.physicsJoint.enableMotor();
  76828. joint.physicsJoint.setMotorSpeed(speed);
  76829. if (maxForce) {
  76830. this.setLimit(joint, maxForce);
  76831. }
  76832. }
  76833. };
  76834. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  76835. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  76836. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  76837. };
  76838. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  76839. var body = impostor.physicsBody;
  76840. mesh.position.x = body.position.x;
  76841. mesh.position.y = body.position.y;
  76842. mesh.position.z = body.position.z;
  76843. if (mesh.rotationQuaternion) {
  76844. mesh.rotationQuaternion.x = body.quaternion.x;
  76845. mesh.rotationQuaternion.y = body.quaternion.y;
  76846. mesh.rotationQuaternion.z = body.quaternion.z;
  76847. mesh.rotationQuaternion.w = body.quaternion.w;
  76848. }
  76849. };
  76850. CannonJSPlugin.prototype.getRadius = function (impostor) {
  76851. var shape = impostor.physicsBody.shapes[0];
  76852. return shape.boundingSphereRadius;
  76853. };
  76854. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  76855. var shape = impostor.physicsBody.shapes[0];
  76856. result.x = shape.halfExtents.x * 2;
  76857. result.y = shape.halfExtents.y * 2;
  76858. result.z = shape.halfExtents.z * 2;
  76859. };
  76860. CannonJSPlugin.prototype.dispose = function () {
  76861. };
  76862. CannonJSPlugin.prototype._extendNamespace = function () {
  76863. //this will force cannon to execute at least one step when using interpolation
  76864. var step_tmp1 = new this.BJSCANNON.Vec3();
  76865. var Engine = this.BJSCANNON;
  76866. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  76867. maxSubSteps = maxSubSteps || 10;
  76868. timeSinceLastCalled = timeSinceLastCalled || 0;
  76869. if (timeSinceLastCalled === 0) {
  76870. this.internalStep(dt);
  76871. this.time += dt;
  76872. }
  76873. else {
  76874. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  76875. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  76876. var t0 = performance.now();
  76877. for (var i = 0; i !== internalSteps; i++) {
  76878. this.internalStep(dt);
  76879. if (performance.now() - t0 > dt * 1000) {
  76880. break;
  76881. }
  76882. }
  76883. this.time += timeSinceLastCalled;
  76884. var h = this.time % dt;
  76885. var h_div_dt = h / dt;
  76886. var interpvelo = step_tmp1;
  76887. var bodies = this.bodies;
  76888. for (var j = 0; j !== bodies.length; j++) {
  76889. var b = bodies[j];
  76890. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  76891. b.position.vsub(b.previousPosition, interpvelo);
  76892. interpvelo.scale(h_div_dt, interpvelo);
  76893. b.position.vadd(interpvelo, b.interpolatedPosition);
  76894. }
  76895. else {
  76896. b.interpolatedPosition.copy(b.position);
  76897. b.interpolatedQuaternion.copy(b.quaternion);
  76898. }
  76899. }
  76900. }
  76901. };
  76902. };
  76903. return CannonJSPlugin;
  76904. }());
  76905. BABYLON.CannonJSPlugin = CannonJSPlugin;
  76906. })(BABYLON || (BABYLON = {}));
  76907. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  76908. var BABYLON;
  76909. (function (BABYLON) {
  76910. var OimoJSPlugin = /** @class */ (function () {
  76911. function OimoJSPlugin(iterations) {
  76912. this.name = "OimoJSPlugin";
  76913. this._tmpImpostorsArray = [];
  76914. this._tmpPositionVector = BABYLON.Vector3.Zero();
  76915. this.BJSOIMO = typeof OIMO !== 'undefined' ? OIMO : ( true ? __webpack_require__(18) : undefined);
  76916. this.world = new this.BJSOIMO.World(1 / 60, 2, iterations, true);
  76917. this.world.worldscale(1);
  76918. this.world.clear();
  76919. //making sure no stats are calculated
  76920. this.world.isNoStat = true;
  76921. }
  76922. OimoJSPlugin.prototype.setGravity = function (gravity) {
  76923. this.world.gravity.copy(gravity);
  76924. };
  76925. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  76926. this.world.timeStep = timeStep;
  76927. };
  76928. OimoJSPlugin.prototype.getTimeStep = function () {
  76929. return this.world.timeStep;
  76930. };
  76931. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  76932. var _this = this;
  76933. impostors.forEach(function (impostor) {
  76934. impostor.beforeStep();
  76935. });
  76936. this.world.step();
  76937. impostors.forEach(function (impostor) {
  76938. impostor.afterStep();
  76939. //update the ordered impostors array
  76940. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  76941. });
  76942. //check for collisions
  76943. var contact = this.world.contacts;
  76944. while (contact !== null) {
  76945. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  76946. contact = contact.next;
  76947. continue;
  76948. }
  76949. //is this body colliding with any other? get the impostor
  76950. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  76951. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  76952. if (!mainImpostor || !collidingImpostor) {
  76953. contact = contact.next;
  76954. continue;
  76955. }
  76956. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  76957. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  76958. contact = contact.next;
  76959. }
  76960. };
  76961. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  76962. var mass = impostor.physicsBody.massInfo.mass;
  76963. impostor.physicsBody.applyImpulse(contactPoint.scale(this.BJSOIMO.INV_SCALE), force.scale(this.BJSOIMO.INV_SCALE * mass));
  76964. };
  76965. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  76966. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  76967. this.applyImpulse(impostor, force, contactPoint);
  76968. };
  76969. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  76970. var _this = this;
  76971. //parent-child relationship. Does this impostor has a parent impostor?
  76972. if (impostor.parent) {
  76973. if (impostor.physicsBody) {
  76974. this.removePhysicsBody(impostor);
  76975. //TODO is that needed?
  76976. impostor.forceUpdate();
  76977. }
  76978. return;
  76979. }
  76980. if (impostor.isBodyInitRequired()) {
  76981. var bodyConfig = {
  76982. name: impostor.uniqueId,
  76983. //Oimo must have mass, also for static objects.
  76984. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  76985. size: [],
  76986. type: [],
  76987. pos: [],
  76988. rot: [],
  76989. move: impostor.getParam("mass") !== 0,
  76990. //Supporting older versions of Oimo
  76991. world: this.world
  76992. };
  76993. var impostors = [impostor];
  76994. var addToArray = function (parent) {
  76995. if (!parent.getChildMeshes)
  76996. return;
  76997. parent.getChildMeshes().forEach(function (m) {
  76998. if (m.physicsImpostor) {
  76999. impostors.push(m.physicsImpostor);
  77000. //m.physicsImpostor._init();
  77001. }
  77002. });
  77003. };
  77004. addToArray(impostor.object);
  77005. var checkWithEpsilon_1 = function (value) {
  77006. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  77007. };
  77008. impostors.forEach(function (i) {
  77009. if (!impostor.object.rotationQuaternion) {
  77010. return;
  77011. }
  77012. //get the correct bounding box
  77013. var oldQuaternion = i.object.rotationQuaternion;
  77014. var rot = new _this.BJSOIMO.Euler().setFromQuaternion({
  77015. x: impostor.object.rotationQuaternion.x,
  77016. y: impostor.object.rotationQuaternion.y,
  77017. z: impostor.object.rotationQuaternion.z,
  77018. s: impostor.object.rotationQuaternion.w
  77019. });
  77020. var extendSize = i.getObjectExtendSize();
  77021. if (i === impostor) {
  77022. var center = impostor.getObjectCenter();
  77023. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  77024. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  77025. //Can also use Array.prototype.push.apply
  77026. bodyConfig.pos.push(center.x);
  77027. bodyConfig.pos.push(center.y);
  77028. bodyConfig.pos.push(center.z);
  77029. //tmp solution
  77030. bodyConfig.rot.push(rot.x / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  77031. bodyConfig.rot.push(rot.y / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  77032. bodyConfig.rot.push(rot.z / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  77033. }
  77034. else {
  77035. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  77036. bodyConfig.pos.push(localPosition.x);
  77037. bodyConfig.pos.push(localPosition.y);
  77038. bodyConfig.pos.push(localPosition.z);
  77039. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  77040. bodyConfig.rot.push(0);
  77041. bodyConfig.rot.push(0);
  77042. bodyConfig.rot.push(0);
  77043. }
  77044. // register mesh
  77045. switch (i.type) {
  77046. case BABYLON.PhysicsImpostor.ParticleImpostor:
  77047. BABYLON.Tools.Warn("No Particle support in this.BJSOIMO.js. using SphereImpostor instead");
  77048. case BABYLON.PhysicsImpostor.SphereImpostor:
  77049. var radiusX = extendSize.x;
  77050. var radiusY = extendSize.y;
  77051. var radiusZ = extendSize.z;
  77052. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  77053. bodyConfig.type.push('sphere');
  77054. //due to the way oimo works with compounds, add 3 times
  77055. bodyConfig.size.push(size);
  77056. bodyConfig.size.push(size);
  77057. bodyConfig.size.push(size);
  77058. break;
  77059. case BABYLON.PhysicsImpostor.CylinderImpostor:
  77060. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  77061. var sizeY = checkWithEpsilon_1(extendSize.y);
  77062. bodyConfig.type.push('cylinder');
  77063. bodyConfig.size.push(sizeX);
  77064. bodyConfig.size.push(sizeY);
  77065. //due to the way oimo works with compounds, add one more value.
  77066. bodyConfig.size.push(sizeY);
  77067. break;
  77068. case BABYLON.PhysicsImpostor.PlaneImpostor:
  77069. case BABYLON.PhysicsImpostor.BoxImpostor:
  77070. default:
  77071. var sizeX = checkWithEpsilon_1(extendSize.x);
  77072. var sizeY = checkWithEpsilon_1(extendSize.y);
  77073. var sizeZ = checkWithEpsilon_1(extendSize.z);
  77074. bodyConfig.type.push('box');
  77075. bodyConfig.size.push(sizeX);
  77076. bodyConfig.size.push(sizeY);
  77077. bodyConfig.size.push(sizeZ);
  77078. break;
  77079. }
  77080. //actually not needed, but hey...
  77081. i.object.rotationQuaternion = oldQuaternion;
  77082. });
  77083. impostor.physicsBody = new this.BJSOIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  77084. }
  77085. else {
  77086. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  77087. }
  77088. impostor.setDeltaPosition(this._tmpPositionVector);
  77089. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  77090. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  77091. };
  77092. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  77093. //impostor.physicsBody.dispose();
  77094. //Same as : (older oimo versions)
  77095. this.world.removeRigidBody(impostor.physicsBody);
  77096. };
  77097. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  77098. var mainBody = impostorJoint.mainImpostor.physicsBody;
  77099. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  77100. if (!mainBody || !connectedBody) {
  77101. return;
  77102. }
  77103. var jointData = impostorJoint.joint.jointData;
  77104. var options = jointData.nativeParams || {};
  77105. var type;
  77106. var nativeJointData = {
  77107. body1: mainBody,
  77108. body2: connectedBody,
  77109. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  77110. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  77111. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  77112. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  77113. min: options.min,
  77114. max: options.max,
  77115. collision: options.collision || jointData.collision,
  77116. spring: options.spring,
  77117. //supporting older version of Oimo
  77118. world: this.world
  77119. };
  77120. switch (impostorJoint.joint.type) {
  77121. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  77122. type = "jointBall";
  77123. break;
  77124. case BABYLON.PhysicsJoint.SpringJoint:
  77125. BABYLON.Tools.Warn("this.BJSOIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  77126. var springData = jointData;
  77127. nativeJointData.min = springData.length || nativeJointData.min;
  77128. //Max should also be set, just make sure it is at least min
  77129. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  77130. case BABYLON.PhysicsJoint.DistanceJoint:
  77131. type = "jointDistance";
  77132. nativeJointData.max = jointData.maxDistance;
  77133. break;
  77134. case BABYLON.PhysicsJoint.PrismaticJoint:
  77135. type = "jointPrisme";
  77136. break;
  77137. case BABYLON.PhysicsJoint.SliderJoint:
  77138. type = "jointSlide";
  77139. break;
  77140. case BABYLON.PhysicsJoint.WheelJoint:
  77141. type = "jointWheel";
  77142. break;
  77143. case BABYLON.PhysicsJoint.HingeJoint:
  77144. default:
  77145. type = "jointHinge";
  77146. break;
  77147. }
  77148. nativeJointData.type = type;
  77149. impostorJoint.joint.physicsJoint = new this.BJSOIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  77150. };
  77151. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  77152. //Bug in Oimo prevents us from disposing a joint in the playground
  77153. //joint.joint.physicsJoint.dispose();
  77154. //So we will bruteforce it!
  77155. try {
  77156. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  77157. }
  77158. catch (e) {
  77159. BABYLON.Tools.Warn(e);
  77160. }
  77161. };
  77162. OimoJSPlugin.prototype.isSupported = function () {
  77163. return this.BJSOIMO !== undefined;
  77164. };
  77165. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  77166. if (!impostor.physicsBody.sleeping) {
  77167. //TODO check that
  77168. if (impostor.physicsBody.shapes.next) {
  77169. var parentShape = this._getLastShape(impostor.physicsBody);
  77170. impostor.object.position.x = parentShape.position.x * this.BJSOIMO.WORLD_SCALE;
  77171. impostor.object.position.y = parentShape.position.y * this.BJSOIMO.WORLD_SCALE;
  77172. impostor.object.position.z = parentShape.position.z * this.BJSOIMO.WORLD_SCALE;
  77173. }
  77174. else {
  77175. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  77176. }
  77177. if (impostor.object.rotationQuaternion) {
  77178. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  77179. impostor.object.rotationQuaternion.normalize();
  77180. }
  77181. }
  77182. };
  77183. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  77184. var body = impostor.physicsBody;
  77185. body.position.init(newPosition.x * this.BJSOIMO.INV_SCALE, newPosition.y * this.BJSOIMO.INV_SCALE, newPosition.z * this.BJSOIMO.INV_SCALE);
  77186. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  77187. body.syncShapes();
  77188. body.awake();
  77189. };
  77190. OimoJSPlugin.prototype._getLastShape = function (body) {
  77191. var lastShape = body.shapes;
  77192. while (lastShape.next) {
  77193. lastShape = lastShape.next;
  77194. }
  77195. return lastShape;
  77196. };
  77197. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  77198. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  77199. };
  77200. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  77201. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  77202. };
  77203. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  77204. var v = impostor.physicsBody.linearVelocity;
  77205. if (!v) {
  77206. return null;
  77207. }
  77208. return new BABYLON.Vector3(v.x, v.y, v.z);
  77209. };
  77210. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  77211. var v = impostor.physicsBody.angularVelocity;
  77212. if (!v) {
  77213. return null;
  77214. }
  77215. return new BABYLON.Vector3(v.x, v.y, v.z);
  77216. };
  77217. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  77218. var staticBody = mass === 0;
  77219. //this will actually set the body's density and not its mass.
  77220. //But this is how oimo treats the mass variable.
  77221. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  77222. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  77223. };
  77224. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  77225. return impostor.physicsBody.shapes.density;
  77226. };
  77227. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  77228. return impostor.physicsBody.shapes.friction;
  77229. };
  77230. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  77231. impostor.physicsBody.shapes.friction = friction;
  77232. };
  77233. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  77234. return impostor.physicsBody.shapes.restitution;
  77235. };
  77236. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  77237. impostor.physicsBody.shapes.restitution = restitution;
  77238. };
  77239. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  77240. impostor.physicsBody.sleep();
  77241. };
  77242. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  77243. impostor.physicsBody.awake();
  77244. };
  77245. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  77246. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  77247. if (minDistance !== void 0) {
  77248. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  77249. }
  77250. };
  77251. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  77252. //TODO separate rotational and transational motors.
  77253. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  77254. if (motor) {
  77255. motor.setMotor(speed, maxForce);
  77256. }
  77257. };
  77258. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  77259. //TODO separate rotational and transational motors.
  77260. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  77261. if (motor) {
  77262. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  77263. }
  77264. };
  77265. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  77266. var body = impostor.physicsBody;
  77267. mesh.position.x = body.position.x;
  77268. mesh.position.y = body.position.y;
  77269. mesh.position.z = body.position.z;
  77270. if (mesh.rotationQuaternion) {
  77271. mesh.rotationQuaternion.x = body.orientation.x;
  77272. mesh.rotationQuaternion.y = body.orientation.y;
  77273. mesh.rotationQuaternion.z = body.orientation.z;
  77274. mesh.rotationQuaternion.w = body.orientation.s;
  77275. }
  77276. };
  77277. OimoJSPlugin.prototype.getRadius = function (impostor) {
  77278. return impostor.physicsBody.shapes.radius;
  77279. };
  77280. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  77281. var shape = impostor.physicsBody.shapes;
  77282. result.x = shape.halfWidth * 2;
  77283. result.y = shape.halfHeight * 2;
  77284. result.z = shape.halfDepth * 2;
  77285. };
  77286. OimoJSPlugin.prototype.dispose = function () {
  77287. this.world.clear();
  77288. };
  77289. return OimoJSPlugin;
  77290. }());
  77291. BABYLON.OimoJSPlugin = OimoJSPlugin;
  77292. })(BABYLON || (BABYLON = {}));
  77293. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  77294. var BABYLON;
  77295. (function (BABYLON) {
  77296. /*
  77297. * Based on jsTGALoader - Javascript loader for TGA file
  77298. * By Vincent Thibault
  77299. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  77300. */
  77301. var TGATools = /** @class */ (function () {
  77302. function TGATools() {
  77303. }
  77304. TGATools.GetTGAHeader = function (data) {
  77305. var offset = 0;
  77306. var header = {
  77307. id_length: data[offset++],
  77308. colormap_type: data[offset++],
  77309. image_type: data[offset++],
  77310. colormap_index: data[offset++] | data[offset++] << 8,
  77311. colormap_length: data[offset++] | data[offset++] << 8,
  77312. colormap_size: data[offset++],
  77313. origin: [
  77314. data[offset++] | data[offset++] << 8,
  77315. data[offset++] | data[offset++] << 8
  77316. ],
  77317. width: data[offset++] | data[offset++] << 8,
  77318. height: data[offset++] | data[offset++] << 8,
  77319. pixel_size: data[offset++],
  77320. flags: data[offset++]
  77321. };
  77322. return header;
  77323. };
  77324. TGATools.UploadContent = function (gl, data) {
  77325. // Not enough data to contain header ?
  77326. if (data.length < 19) {
  77327. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  77328. return;
  77329. }
  77330. // Read Header
  77331. var offset = 18;
  77332. var header = TGATools.GetTGAHeader(data);
  77333. // Assume it's a valid Targa file.
  77334. if (header.id_length + offset > data.length) {
  77335. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  77336. return;
  77337. }
  77338. // Skip not needed data
  77339. offset += header.id_length;
  77340. var use_rle = false;
  77341. var use_pal = false;
  77342. var use_grey = false;
  77343. // Get some informations.
  77344. switch (header.image_type) {
  77345. case TGATools._TYPE_RLE_INDEXED:
  77346. use_rle = true;
  77347. case TGATools._TYPE_INDEXED:
  77348. use_pal = true;
  77349. break;
  77350. case TGATools._TYPE_RLE_RGB:
  77351. use_rle = true;
  77352. case TGATools._TYPE_RGB:
  77353. // use_rgb = true;
  77354. break;
  77355. case TGATools._TYPE_RLE_GREY:
  77356. use_rle = true;
  77357. case TGATools._TYPE_GREY:
  77358. use_grey = true;
  77359. break;
  77360. }
  77361. var pixel_data;
  77362. // var numAlphaBits = header.flags & 0xf;
  77363. var pixel_size = header.pixel_size >> 3;
  77364. var pixel_total = header.width * header.height * pixel_size;
  77365. // Read palettes
  77366. var palettes;
  77367. if (use_pal) {
  77368. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  77369. }
  77370. // Read LRE
  77371. if (use_rle) {
  77372. pixel_data = new Uint8Array(pixel_total);
  77373. var c, count, i;
  77374. var localOffset = 0;
  77375. var pixels = new Uint8Array(pixel_size);
  77376. while (offset < pixel_total && localOffset < pixel_total) {
  77377. c = data[offset++];
  77378. count = (c & 0x7f) + 1;
  77379. // RLE pixels
  77380. if (c & 0x80) {
  77381. // Bind pixel tmp array
  77382. for (i = 0; i < pixel_size; ++i) {
  77383. pixels[i] = data[offset++];
  77384. }
  77385. // Copy pixel array
  77386. for (i = 0; i < count; ++i) {
  77387. pixel_data.set(pixels, localOffset + i * pixel_size);
  77388. }
  77389. localOffset += pixel_size * count;
  77390. }
  77391. else {
  77392. count *= pixel_size;
  77393. for (i = 0; i < count; ++i) {
  77394. pixel_data[localOffset + i] = data[offset++];
  77395. }
  77396. localOffset += count;
  77397. }
  77398. }
  77399. }
  77400. else {
  77401. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  77402. }
  77403. // Load to texture
  77404. var x_start, y_start, x_step, y_step, y_end, x_end;
  77405. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  77406. default:
  77407. case TGATools._ORIGIN_UL:
  77408. x_start = 0;
  77409. x_step = 1;
  77410. x_end = header.width;
  77411. y_start = 0;
  77412. y_step = 1;
  77413. y_end = header.height;
  77414. break;
  77415. case TGATools._ORIGIN_BL:
  77416. x_start = 0;
  77417. x_step = 1;
  77418. x_end = header.width;
  77419. y_start = header.height - 1;
  77420. y_step = -1;
  77421. y_end = -1;
  77422. break;
  77423. case TGATools._ORIGIN_UR:
  77424. x_start = header.width - 1;
  77425. x_step = -1;
  77426. x_end = -1;
  77427. y_start = 0;
  77428. y_step = 1;
  77429. y_end = header.height;
  77430. break;
  77431. case TGATools._ORIGIN_BR:
  77432. x_start = header.width - 1;
  77433. x_step = -1;
  77434. x_end = -1;
  77435. y_start = header.height - 1;
  77436. y_step = -1;
  77437. y_end = -1;
  77438. break;
  77439. }
  77440. // Load the specify method
  77441. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  77442. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  77443. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  77444. };
  77445. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  77446. var image = pixel_data, colormap = palettes;
  77447. var width = header.width, height = header.height;
  77448. var color, i = 0, x, y;
  77449. var imageData = new Uint8Array(width * height * 4);
  77450. for (y = y_start; y !== y_end; y += y_step) {
  77451. for (x = x_start; x !== x_end; x += x_step, i++) {
  77452. color = image[i];
  77453. imageData[(x + width * y) * 4 + 3] = 255;
  77454. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  77455. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  77456. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  77457. }
  77458. }
  77459. return imageData;
  77460. };
  77461. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  77462. var image = pixel_data;
  77463. var width = header.width, height = header.height;
  77464. var color, i = 0, x, y;
  77465. var imageData = new Uint8Array(width * height * 4);
  77466. for (y = y_start; y !== y_end; y += y_step) {
  77467. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  77468. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  77469. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  77470. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  77471. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  77472. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  77473. }
  77474. }
  77475. return imageData;
  77476. };
  77477. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  77478. var image = pixel_data;
  77479. var width = header.width, height = header.height;
  77480. var i = 0, x, y;
  77481. var imageData = new Uint8Array(width * height * 4);
  77482. for (y = y_start; y !== y_end; y += y_step) {
  77483. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  77484. imageData[(x + width * y) * 4 + 3] = 255;
  77485. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  77486. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  77487. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  77488. }
  77489. }
  77490. return imageData;
  77491. };
  77492. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  77493. var image = pixel_data;
  77494. var width = header.width, height = header.height;
  77495. var i = 0, x, y;
  77496. var imageData = new Uint8Array(width * height * 4);
  77497. for (y = y_start; y !== y_end; y += y_step) {
  77498. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  77499. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  77500. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  77501. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  77502. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  77503. }
  77504. }
  77505. return imageData;
  77506. };
  77507. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  77508. var image = pixel_data;
  77509. var width = header.width, height = header.height;
  77510. var color, i = 0, x, y;
  77511. var imageData = new Uint8Array(width * height * 4);
  77512. for (y = y_start; y !== y_end; y += y_step) {
  77513. for (x = x_start; x !== x_end; x += x_step, i++) {
  77514. color = image[i];
  77515. imageData[(x + width * y) * 4 + 0] = color;
  77516. imageData[(x + width * y) * 4 + 1] = color;
  77517. imageData[(x + width * y) * 4 + 2] = color;
  77518. imageData[(x + width * y) * 4 + 3] = 255;
  77519. }
  77520. }
  77521. return imageData;
  77522. };
  77523. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  77524. var image = pixel_data;
  77525. var width = header.width, height = header.height;
  77526. var i = 0, x, y;
  77527. var imageData = new Uint8Array(width * height * 4);
  77528. for (y = y_start; y !== y_end; y += y_step) {
  77529. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  77530. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  77531. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  77532. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  77533. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  77534. }
  77535. }
  77536. return imageData;
  77537. };
  77538. //private static _TYPE_NO_DATA = 0;
  77539. TGATools._TYPE_INDEXED = 1;
  77540. TGATools._TYPE_RGB = 2;
  77541. TGATools._TYPE_GREY = 3;
  77542. TGATools._TYPE_RLE_INDEXED = 9;
  77543. TGATools._TYPE_RLE_RGB = 10;
  77544. TGATools._TYPE_RLE_GREY = 11;
  77545. TGATools._ORIGIN_MASK = 0x30;
  77546. TGATools._ORIGIN_SHIFT = 0x04;
  77547. TGATools._ORIGIN_BL = 0x00;
  77548. TGATools._ORIGIN_BR = 0x01;
  77549. TGATools._ORIGIN_UL = 0x02;
  77550. TGATools._ORIGIN_UR = 0x03;
  77551. return TGATools;
  77552. }());
  77553. BABYLON.TGATools = TGATools;
  77554. })(BABYLON || (BABYLON = {}));
  77555. //# sourceMappingURL=babylon.tga.js.map
  77556. var BABYLON;
  77557. (function (BABYLON) {
  77558. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  77559. // All values and structures referenced from:
  77560. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  77561. var DDS_MAGIC = 0x20534444;
  77562. var
  77563. //DDSD_CAPS = 0x1,
  77564. //DDSD_HEIGHT = 0x2,
  77565. //DDSD_WIDTH = 0x4,
  77566. //DDSD_PITCH = 0x8,
  77567. //DDSD_PIXELFORMAT = 0x1000,
  77568. DDSD_MIPMAPCOUNT = 0x20000;
  77569. //DDSD_LINEARSIZE = 0x80000,
  77570. //DDSD_DEPTH = 0x800000;
  77571. // var DDSCAPS_COMPLEX = 0x8,
  77572. // DDSCAPS_MIPMAP = 0x400000,
  77573. // DDSCAPS_TEXTURE = 0x1000;
  77574. var DDSCAPS2_CUBEMAP = 0x200;
  77575. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  77576. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  77577. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  77578. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  77579. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  77580. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  77581. // DDSCAPS2_VOLUME = 0x200000;
  77582. var
  77583. //DDPF_ALPHAPIXELS = 0x1,
  77584. //DDPF_ALPHA = 0x2,
  77585. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  77586. //DDPF_YUV = 0x200,
  77587. DDPF_LUMINANCE = 0x20000;
  77588. function FourCCToInt32(value) {
  77589. return value.charCodeAt(0) +
  77590. (value.charCodeAt(1) << 8) +
  77591. (value.charCodeAt(2) << 16) +
  77592. (value.charCodeAt(3) << 24);
  77593. }
  77594. function Int32ToFourCC(value) {
  77595. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  77596. }
  77597. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  77598. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  77599. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  77600. var FOURCC_DX10 = FourCCToInt32("DX10");
  77601. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  77602. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  77603. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  77604. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  77605. var headerLengthInt = 31; // The header length in 32 bit ints
  77606. // Offsets into the header array
  77607. var off_magic = 0;
  77608. var off_size = 1;
  77609. var off_flags = 2;
  77610. var off_height = 3;
  77611. var off_width = 4;
  77612. var off_mipmapCount = 7;
  77613. var off_pfFlags = 20;
  77614. var off_pfFourCC = 21;
  77615. var off_RGBbpp = 22;
  77616. var off_RMask = 23;
  77617. var off_GMask = 24;
  77618. var off_BMask = 25;
  77619. var off_AMask = 26;
  77620. // var off_caps1 = 27;
  77621. var off_caps2 = 28;
  77622. // var off_caps3 = 29;
  77623. // var off_caps4 = 30;
  77624. var off_dxgiFormat = 32;
  77625. ;
  77626. var DDSTools = /** @class */ (function () {
  77627. function DDSTools() {
  77628. }
  77629. DDSTools.GetDDSInfo = function (arrayBuffer) {
  77630. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  77631. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  77632. var mipmapCount = 1;
  77633. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  77634. mipmapCount = Math.max(1, header[off_mipmapCount]);
  77635. }
  77636. var fourCC = header[off_pfFourCC];
  77637. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  77638. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  77639. switch (fourCC) {
  77640. case FOURCC_D3DFMT_R16G16B16A16F:
  77641. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  77642. break;
  77643. case FOURCC_D3DFMT_R32G32B32A32F:
  77644. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  77645. break;
  77646. case FOURCC_DX10:
  77647. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  77648. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  77649. break;
  77650. }
  77651. }
  77652. return {
  77653. width: header[off_width],
  77654. height: header[off_height],
  77655. mipmapCount: mipmapCount,
  77656. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  77657. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  77658. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  77659. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  77660. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  77661. dxgiFormat: dxgiFormat,
  77662. textureType: textureType
  77663. };
  77664. };
  77665. DDSTools._ToHalfFloat = function (value) {
  77666. if (!DDSTools._FloatView) {
  77667. DDSTools._FloatView = new Float32Array(1);
  77668. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  77669. }
  77670. DDSTools._FloatView[0] = value;
  77671. var x = DDSTools._Int32View[0];
  77672. var bits = (x >> 16) & 0x8000; /* Get the sign */
  77673. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  77674. var e = (x >> 23) & 0xff; /* Using int is faster here */
  77675. /* If zero, or denormal, or exponent underflows too much for a denormal
  77676. * half, return signed zero. */
  77677. if (e < 103) {
  77678. return bits;
  77679. }
  77680. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  77681. if (e > 142) {
  77682. bits |= 0x7c00;
  77683. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  77684. * not Inf, so make sure we set one mantissa bit too. */
  77685. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  77686. return bits;
  77687. }
  77688. /* If exponent underflows but not too much, return a denormal */
  77689. if (e < 113) {
  77690. m |= 0x0800;
  77691. /* Extra rounding may overflow and set mantissa to 0 and exponent
  77692. * to 1, which is OK. */
  77693. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  77694. return bits;
  77695. }
  77696. bits |= ((e - 112) << 10) | (m >> 1);
  77697. bits += m & 1;
  77698. return bits;
  77699. };
  77700. DDSTools._FromHalfFloat = function (value) {
  77701. var s = (value & 0x8000) >> 15;
  77702. var e = (value & 0x7C00) >> 10;
  77703. var f = value & 0x03FF;
  77704. if (e === 0) {
  77705. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  77706. }
  77707. else if (e == 0x1F) {
  77708. return f ? NaN : ((s ? -1 : 1) * Infinity);
  77709. }
  77710. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  77711. };
  77712. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  77713. var destArray = new Float32Array(dataLength);
  77714. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  77715. var index = 0;
  77716. for (var y = 0; y < height; y++) {
  77717. for (var x = 0; x < width; x++) {
  77718. var srcPos = (x + y * width) * 4;
  77719. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  77720. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  77721. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  77722. if (DDSTools.StoreLODInAlphaChannel) {
  77723. destArray[index + 3] = lod;
  77724. }
  77725. else {
  77726. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  77727. }
  77728. index += 4;
  77729. }
  77730. }
  77731. return destArray;
  77732. };
  77733. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  77734. if (DDSTools.StoreLODInAlphaChannel) {
  77735. var destArray = new Uint16Array(dataLength);
  77736. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  77737. var index = 0;
  77738. for (var y = 0; y < height; y++) {
  77739. for (var x = 0; x < width; x++) {
  77740. var srcPos = (x + y * width) * 4;
  77741. destArray[index] = srcData[srcPos];
  77742. destArray[index + 1] = srcData[srcPos + 1];
  77743. destArray[index + 2] = srcData[srcPos + 2];
  77744. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  77745. index += 4;
  77746. }
  77747. }
  77748. return destArray;
  77749. }
  77750. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  77751. };
  77752. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  77753. if (DDSTools.StoreLODInAlphaChannel) {
  77754. var destArray = new Float32Array(dataLength);
  77755. var srcData = new Float32Array(arrayBuffer, dataOffset);
  77756. var index = 0;
  77757. for (var y = 0; y < height; y++) {
  77758. for (var x = 0; x < width; x++) {
  77759. var srcPos = (x + y * width) * 4;
  77760. destArray[index] = srcData[srcPos];
  77761. destArray[index + 1] = srcData[srcPos + 1];
  77762. destArray[index + 2] = srcData[srcPos + 2];
  77763. destArray[index + 3] = lod;
  77764. index += 4;
  77765. }
  77766. }
  77767. return destArray;
  77768. }
  77769. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  77770. };
  77771. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  77772. var destArray = new Uint8Array(dataLength);
  77773. var srcData = new Float32Array(arrayBuffer, dataOffset);
  77774. var index = 0;
  77775. for (var y = 0; y < height; y++) {
  77776. for (var x = 0; x < width; x++) {
  77777. var srcPos = (x + y * width) * 4;
  77778. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  77779. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  77780. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  77781. if (DDSTools.StoreLODInAlphaChannel) {
  77782. destArray[index + 3] = lod;
  77783. }
  77784. else {
  77785. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  77786. }
  77787. index += 4;
  77788. }
  77789. }
  77790. return destArray;
  77791. };
  77792. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  77793. var destArray = new Uint8Array(dataLength);
  77794. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  77795. var index = 0;
  77796. for (var y = 0; y < height; y++) {
  77797. for (var x = 0; x < width; x++) {
  77798. var srcPos = (x + y * width) * 4;
  77799. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  77800. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  77801. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  77802. if (DDSTools.StoreLODInAlphaChannel) {
  77803. destArray[index + 3] = lod;
  77804. }
  77805. else {
  77806. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  77807. }
  77808. index += 4;
  77809. }
  77810. }
  77811. return destArray;
  77812. };
  77813. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  77814. var byteArray = new Uint8Array(dataLength);
  77815. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  77816. var index = 0;
  77817. for (var y = 0; y < height; y++) {
  77818. for (var x = 0; x < width; x++) {
  77819. var srcPos = (x + y * width) * 4;
  77820. byteArray[index] = srcData[srcPos + rOffset];
  77821. byteArray[index + 1] = srcData[srcPos + gOffset];
  77822. byteArray[index + 2] = srcData[srcPos + bOffset];
  77823. byteArray[index + 3] = srcData[srcPos + aOffset];
  77824. index += 4;
  77825. }
  77826. }
  77827. return byteArray;
  77828. };
  77829. DDSTools._ExtractLongWordOrder = function (value) {
  77830. if (value === 0 || value === 255 || value === -16777216) {
  77831. return 0;
  77832. }
  77833. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  77834. };
  77835. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  77836. var byteArray = new Uint8Array(dataLength);
  77837. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  77838. var index = 0;
  77839. for (var y = 0; y < height; y++) {
  77840. for (var x = 0; x < width; x++) {
  77841. var srcPos = (x + y * width) * 3;
  77842. byteArray[index] = srcData[srcPos + rOffset];
  77843. byteArray[index + 1] = srcData[srcPos + gOffset];
  77844. byteArray[index + 2] = srcData[srcPos + bOffset];
  77845. index += 3;
  77846. }
  77847. }
  77848. return byteArray;
  77849. };
  77850. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  77851. var byteArray = new Uint8Array(dataLength);
  77852. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  77853. var index = 0;
  77854. for (var y = 0; y < height; y++) {
  77855. for (var x = 0; x < width; x++) {
  77856. var srcPos = (x + y * width);
  77857. byteArray[index] = srcData[srcPos];
  77858. index++;
  77859. }
  77860. }
  77861. return byteArray;
  77862. };
  77863. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  77864. if (lodIndex === void 0) { lodIndex = -1; }
  77865. var ext = engine.getCaps().s3tc;
  77866. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  77867. var fourCC, width, height, dataLength = 0, dataOffset;
  77868. var byteArray, mipmapCount, mip;
  77869. var internalFormat = 0;
  77870. var format = 0;
  77871. var blockBytes = 1;
  77872. if (header[off_magic] !== DDS_MAGIC) {
  77873. BABYLON.Tools.Error("Invalid magic number in DDS header");
  77874. return;
  77875. }
  77876. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  77877. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  77878. return;
  77879. }
  77880. if (info.isCompressed && !ext) {
  77881. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  77882. return;
  77883. }
  77884. var bpp = header[off_RGBbpp];
  77885. dataOffset = header[off_size] + 4;
  77886. var computeFormats = false;
  77887. if (info.isFourCC) {
  77888. fourCC = header[off_pfFourCC];
  77889. switch (fourCC) {
  77890. case FOURCC_DXT1:
  77891. blockBytes = 8;
  77892. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  77893. break;
  77894. case FOURCC_DXT3:
  77895. blockBytes = 16;
  77896. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  77897. break;
  77898. case FOURCC_DXT5:
  77899. blockBytes = 16;
  77900. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  77901. break;
  77902. case FOURCC_D3DFMT_R16G16B16A16F:
  77903. computeFormats = true;
  77904. break;
  77905. case FOURCC_D3DFMT_R32G32B32A32F:
  77906. computeFormats = true;
  77907. break;
  77908. case FOURCC_DX10:
  77909. // There is an additionnal header so dataOffset need to be changed
  77910. dataOffset += 5 * 4; // 5 uints
  77911. var supported = false;
  77912. switch (info.dxgiFormat) {
  77913. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  77914. computeFormats = true;
  77915. supported = true;
  77916. break;
  77917. case DXGI_FORMAT_B8G8R8X8_UNORM:
  77918. info.isRGB = true;
  77919. info.isFourCC = false;
  77920. bpp = 32;
  77921. supported = true;
  77922. break;
  77923. }
  77924. if (supported) {
  77925. break;
  77926. }
  77927. default:
  77928. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  77929. return;
  77930. }
  77931. }
  77932. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  77933. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  77934. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  77935. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  77936. if (computeFormats) {
  77937. format = engine._getWebGLTextureType(info.textureType);
  77938. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  77939. }
  77940. mipmapCount = 1;
  77941. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  77942. mipmapCount = Math.max(1, header[off_mipmapCount]);
  77943. }
  77944. for (var face = 0; face < faces; face++) {
  77945. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  77946. width = header[off_width];
  77947. height = header[off_height];
  77948. for (mip = 0; mip < mipmapCount; ++mip) {
  77949. if (lodIndex === -1 || lodIndex === mip) {
  77950. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  77951. var i = (lodIndex === -1) ? mip : 0;
  77952. if (!info.isCompressed && info.isFourCC) {
  77953. dataLength = width * height * 4;
  77954. var floatArray = null;
  77955. if (engine.badOS || engine.badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) {
  77956. if (bpp === 128) {
  77957. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  77958. }
  77959. else if (bpp === 64) {
  77960. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  77961. }
  77962. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  77963. format = engine._getWebGLTextureType(info.textureType);
  77964. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  77965. }
  77966. else {
  77967. if (bpp === 128) {
  77968. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  77969. }
  77970. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  77971. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  77972. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  77973. format = engine._getWebGLTextureType(info.textureType);
  77974. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  77975. }
  77976. else {
  77977. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  77978. }
  77979. }
  77980. if (floatArray) {
  77981. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  77982. }
  77983. }
  77984. else if (info.isRGB) {
  77985. if (bpp === 24) {
  77986. dataLength = width * height * 3;
  77987. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  77988. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  77989. }
  77990. else {
  77991. dataLength = width * height * 4;
  77992. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  77993. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  77994. }
  77995. }
  77996. else if (info.isLuminance) {
  77997. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  77998. var unpaddedRowSize = width;
  77999. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  78000. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  78001. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  78002. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  78003. }
  78004. else {
  78005. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  78006. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  78007. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  78008. }
  78009. }
  78010. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  78011. width *= 0.5;
  78012. height *= 0.5;
  78013. width = Math.max(1.0, width);
  78014. height = Math.max(1.0, height);
  78015. }
  78016. if (currentFace !== undefined) {
  78017. // Loading a single face
  78018. break;
  78019. }
  78020. }
  78021. };
  78022. DDSTools.StoreLODInAlphaChannel = false;
  78023. return DDSTools;
  78024. }());
  78025. BABYLON.DDSTools = DDSTools;
  78026. })(BABYLON || (BABYLON = {}));
  78027. //# sourceMappingURL=babylon.dds.js.map
  78028. var BABYLON;
  78029. (function (BABYLON) {
  78030. /**
  78031. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  78032. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  78033. */
  78034. var KhronosTextureContainer = /** @class */ (function () {
  78035. /**
  78036. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  78037. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  78038. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  78039. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  78040. */
  78041. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  78042. this.arrayBuffer = arrayBuffer;
  78043. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  78044. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  78045. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  78046. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  78047. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  78048. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  78049. BABYLON.Tools.Error("texture missing KTX identifier");
  78050. return;
  78051. }
  78052. // load the reset of the header in native 32 bit int
  78053. var header = new Int32Array(this.arrayBuffer, 12, 13);
  78054. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  78055. var oppositeEndianess = header[0] === 0x01020304;
  78056. // read all the header elements in order they exist in the file, without modification (sans endainness)
  78057. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  78058. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  78059. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  78060. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  78061. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  78062. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  78063. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  78064. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  78065. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  78066. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  78067. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  78068. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  78069. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  78070. if (this.glType !== 0) {
  78071. BABYLON.Tools.Error("only compressed formats currently supported");
  78072. return;
  78073. }
  78074. else {
  78075. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  78076. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  78077. }
  78078. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  78079. BABYLON.Tools.Error("only 2D textures currently supported");
  78080. return;
  78081. }
  78082. if (this.numberOfArrayElements !== 0) {
  78083. BABYLON.Tools.Error("texture arrays not currently supported");
  78084. return;
  78085. }
  78086. if (this.numberOfFaces !== facesExpected) {
  78087. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  78088. return;
  78089. }
  78090. // we now have a completely validated file, so could use existence of loadType as success
  78091. // would need to make this more elaborate & adjust checks above to support more than one load type
  78092. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  78093. }
  78094. // not as fast hardware based, but will probably never need to use
  78095. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  78096. return ((val & 0xFF) << 24)
  78097. | ((val & 0xFF00) << 8)
  78098. | ((val >> 8) & 0xFF00)
  78099. | ((val >> 24) & 0xFF);
  78100. };
  78101. /**
  78102. * It is assumed that the texture has already been created & is currently bound
  78103. */
  78104. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  78105. switch (this.loadType) {
  78106. case KhronosTextureContainer.COMPRESSED_2D:
  78107. this._upload2DCompressedLevels(gl, loadMipmaps);
  78108. break;
  78109. case KhronosTextureContainer.TEX_2D:
  78110. case KhronosTextureContainer.COMPRESSED_3D:
  78111. case KhronosTextureContainer.TEX_3D:
  78112. }
  78113. };
  78114. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  78115. // initialize width & height for level 1
  78116. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  78117. var width = this.pixelWidth;
  78118. var height = this.pixelHeight;
  78119. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  78120. for (var level = 0; level < mipmapCount; level++) {
  78121. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  78122. for (var face = 0; face < this.numberOfFaces; face++) {
  78123. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  78124. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  78125. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  78126. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  78127. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  78128. }
  78129. width = Math.max(1.0, width * 0.5);
  78130. height = Math.max(1.0, height * 0.5);
  78131. }
  78132. };
  78133. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  78134. // load types
  78135. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  78136. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  78137. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  78138. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  78139. return KhronosTextureContainer;
  78140. }());
  78141. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  78142. })(BABYLON || (BABYLON = {}));
  78143. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  78144. var BABYLON;
  78145. (function (BABYLON) {
  78146. var Debug = /** @class */ (function () {
  78147. function Debug() {
  78148. }
  78149. Debug.AxesViewer = /** @class */ (function () {
  78150. function AxesViewer(scene, scaleLines) {
  78151. if (scaleLines === void 0) { scaleLines = 1; }
  78152. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  78153. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  78154. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  78155. this.scaleLines = 1;
  78156. this.scaleLines = scaleLines;
  78157. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  78158. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  78159. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  78160. this._xmesh.renderingGroupId = 2;
  78161. this._ymesh.renderingGroupId = 2;
  78162. this._zmesh.renderingGroupId = 2;
  78163. this._xmesh.material.checkReadyOnlyOnce = true;
  78164. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  78165. this._ymesh.material.checkReadyOnlyOnce = true;
  78166. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  78167. this._zmesh.material.checkReadyOnlyOnce = true;
  78168. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  78169. this.scene = scene;
  78170. }
  78171. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  78172. var scaleLines = this.scaleLines;
  78173. if (this._xmesh) {
  78174. this._xmesh.position.copyFrom(position);
  78175. }
  78176. if (this._ymesh) {
  78177. this._ymesh.position.copyFrom(position);
  78178. }
  78179. if (this._zmesh) {
  78180. this._zmesh.position.copyFrom(position);
  78181. }
  78182. var point2 = this._xline[1];
  78183. point2.x = xaxis.x * scaleLines;
  78184. point2.y = xaxis.y * scaleLines;
  78185. point2.z = xaxis.z * scaleLines;
  78186. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  78187. point2 = this._yline[1];
  78188. point2.x = yaxis.x * scaleLines;
  78189. point2.y = yaxis.y * scaleLines;
  78190. point2.z = yaxis.z * scaleLines;
  78191. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  78192. point2 = this._zline[1];
  78193. point2.x = zaxis.x * scaleLines;
  78194. point2.y = zaxis.y * scaleLines;
  78195. point2.z = zaxis.z * scaleLines;
  78196. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  78197. };
  78198. AxesViewer.prototype.dispose = function () {
  78199. if (this._xmesh) {
  78200. this._xmesh.dispose();
  78201. }
  78202. if (this._ymesh) {
  78203. this._ymesh.dispose();
  78204. }
  78205. if (this._zmesh) {
  78206. this._zmesh.dispose();
  78207. }
  78208. this._xmesh = null;
  78209. this._ymesh = null;
  78210. this._zmesh = null;
  78211. this.scene = null;
  78212. };
  78213. return AxesViewer;
  78214. }());
  78215. Debug.BoneAxesViewer = /** @class */ (function (_super) {
  78216. __extends(BoneAxesViewer, _super);
  78217. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  78218. if (scaleLines === void 0) { scaleLines = 1; }
  78219. var _this = _super.call(this, scene, scaleLines) || this;
  78220. _this.pos = BABYLON.Vector3.Zero();
  78221. _this.xaxis = BABYLON.Vector3.Zero();
  78222. _this.yaxis = BABYLON.Vector3.Zero();
  78223. _this.zaxis = BABYLON.Vector3.Zero();
  78224. _this.mesh = mesh;
  78225. _this.bone = bone;
  78226. return _this;
  78227. }
  78228. BoneAxesViewer.prototype.update = function () {
  78229. if (!this.mesh || !this.bone) {
  78230. return;
  78231. }
  78232. var bone = this.bone;
  78233. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  78234. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  78235. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  78236. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  78237. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  78238. };
  78239. BoneAxesViewer.prototype.dispose = function () {
  78240. if (this.mesh) {
  78241. this.mesh = null;
  78242. this.bone = null;
  78243. _super.prototype.dispose.call(this);
  78244. }
  78245. };
  78246. return BoneAxesViewer;
  78247. }(Debug.AxesViewer));
  78248. Debug.PhysicsViewer = /** @class */ (function () {
  78249. function PhysicsViewer(scene) {
  78250. this._impostors = [];
  78251. this._meshes = [];
  78252. this._numMeshes = 0;
  78253. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  78254. var physicEngine = this._scene.getPhysicsEngine();
  78255. if (physicEngine) {
  78256. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  78257. }
  78258. }
  78259. PhysicsViewer.prototype._updateDebugMeshes = function () {
  78260. var plugin = this._physicsEnginePlugin;
  78261. for (var i = 0; i < this._numMeshes; i++) {
  78262. var impostor = this._impostors[i];
  78263. if (!impostor) {
  78264. continue;
  78265. }
  78266. if (impostor.isDisposed) {
  78267. this.hideImpostor(this._impostors[i--]);
  78268. }
  78269. else {
  78270. var mesh = this._meshes[i];
  78271. if (mesh && plugin) {
  78272. plugin.syncMeshWithImpostor(mesh, impostor);
  78273. }
  78274. }
  78275. }
  78276. };
  78277. PhysicsViewer.prototype.showImpostor = function (impostor) {
  78278. if (!this._scene) {
  78279. return;
  78280. }
  78281. for (var i = 0; i < this._numMeshes; i++) {
  78282. if (this._impostors[i] == impostor) {
  78283. return;
  78284. }
  78285. }
  78286. var debugMesh = this._getDebugMesh(impostor, this._scene);
  78287. if (debugMesh) {
  78288. this._impostors[this._numMeshes] = impostor;
  78289. this._meshes[this._numMeshes] = debugMesh;
  78290. if (this._numMeshes === 0) {
  78291. this._renderFunction = this._updateDebugMeshes.bind(this);
  78292. this._scene.registerBeforeRender(this._renderFunction);
  78293. }
  78294. this._numMeshes++;
  78295. }
  78296. };
  78297. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  78298. if (!impostor || !this._scene) {
  78299. return;
  78300. }
  78301. var removed = false;
  78302. for (var i = 0; i < this._numMeshes; i++) {
  78303. if (this._impostors[i] == impostor) {
  78304. var mesh = this._meshes[i];
  78305. if (!mesh) {
  78306. continue;
  78307. }
  78308. this._scene.removeMesh(mesh);
  78309. mesh.dispose();
  78310. this._numMeshes--;
  78311. if (this._numMeshes > 0) {
  78312. this._meshes[i] = this._meshes[this._numMeshes];
  78313. this._impostors[i] = this._impostors[this._numMeshes];
  78314. this._meshes[this._numMeshes] = null;
  78315. this._impostors[this._numMeshes] = null;
  78316. }
  78317. else {
  78318. this._meshes[0] = null;
  78319. this._impostors[0] = null;
  78320. }
  78321. removed = true;
  78322. break;
  78323. }
  78324. }
  78325. if (removed && this._numMeshes === 0) {
  78326. this._scene.unregisterBeforeRender(this._renderFunction);
  78327. }
  78328. };
  78329. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  78330. if (!this._debugMaterial) {
  78331. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  78332. this._debugMaterial.wireframe = true;
  78333. }
  78334. return this._debugMaterial;
  78335. };
  78336. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  78337. if (!this._debugBoxMesh) {
  78338. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  78339. this._debugBoxMesh.renderingGroupId = 1;
  78340. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  78341. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  78342. scene.removeMesh(this._debugBoxMesh);
  78343. }
  78344. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  78345. };
  78346. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  78347. if (!this._debugSphereMesh) {
  78348. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  78349. this._debugSphereMesh.renderingGroupId = 1;
  78350. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  78351. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  78352. scene.removeMesh(this._debugSphereMesh);
  78353. }
  78354. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  78355. };
  78356. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  78357. var mesh = null;
  78358. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  78359. mesh = this._getDebugBoxMesh(scene);
  78360. impostor.getBoxSizeToRef(mesh.scaling);
  78361. }
  78362. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  78363. mesh = this._getDebugSphereMesh(scene);
  78364. var radius = impostor.getRadius();
  78365. mesh.scaling.x = radius * 2;
  78366. mesh.scaling.y = radius * 2;
  78367. mesh.scaling.z = radius * 2;
  78368. }
  78369. return mesh;
  78370. };
  78371. PhysicsViewer.prototype.dispose = function () {
  78372. for (var i = 0; i < this._numMeshes; i++) {
  78373. this.hideImpostor(this._impostors[i]);
  78374. }
  78375. if (this._debugBoxMesh) {
  78376. this._debugBoxMesh.dispose();
  78377. }
  78378. if (this._debugSphereMesh) {
  78379. this._debugSphereMesh.dispose();
  78380. }
  78381. if (this._debugMaterial) {
  78382. this._debugMaterial.dispose();
  78383. }
  78384. this._impostors.length = 0;
  78385. this._scene = null;
  78386. this._physicsEnginePlugin = null;
  78387. };
  78388. return PhysicsViewer;
  78389. }());
  78390. Debug.SkeletonViewer = /** @class */ (function () {
  78391. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  78392. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  78393. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  78394. this.skeleton = skeleton;
  78395. this.mesh = mesh;
  78396. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  78397. this.renderingGroupId = renderingGroupId;
  78398. this.color = BABYLON.Color3.White();
  78399. this._debugLines = new Array();
  78400. this._isEnabled = false;
  78401. this._scene = scene;
  78402. this.update();
  78403. this._renderFunction = this.update.bind(this);
  78404. }
  78405. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  78406. get: function () {
  78407. return this._isEnabled;
  78408. },
  78409. set: function (value) {
  78410. if (this._isEnabled === value) {
  78411. return;
  78412. }
  78413. this._isEnabled = value;
  78414. if (value) {
  78415. this._scene.registerBeforeRender(this._renderFunction);
  78416. }
  78417. else {
  78418. this._scene.unregisterBeforeRender(this._renderFunction);
  78419. }
  78420. },
  78421. enumerable: true,
  78422. configurable: true
  78423. });
  78424. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  78425. if (x === void 0) { x = 0; }
  78426. if (y === void 0) { y = 0; }
  78427. if (z === void 0) { z = 0; }
  78428. var tmat = BABYLON.Tmp.Matrix[0];
  78429. var parentBone = bone.getParent();
  78430. tmat.copyFrom(bone.getLocalMatrix());
  78431. if (x !== 0 || y !== 0 || z !== 0) {
  78432. var tmat2 = BABYLON.Tmp.Matrix[1];
  78433. BABYLON.Matrix.IdentityToRef(tmat2);
  78434. tmat2.m[12] = x;
  78435. tmat2.m[13] = y;
  78436. tmat2.m[14] = z;
  78437. tmat2.multiplyToRef(tmat, tmat);
  78438. }
  78439. if (parentBone) {
  78440. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  78441. }
  78442. tmat.multiplyToRef(meshMat, tmat);
  78443. position.x = tmat.m[12];
  78444. position.y = tmat.m[13];
  78445. position.z = tmat.m[14];
  78446. };
  78447. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  78448. var len = bones.length;
  78449. var meshPos = this.mesh.position;
  78450. for (var i = 0; i < len; i++) {
  78451. var bone = bones[i];
  78452. var points = this._debugLines[i];
  78453. if (!points) {
  78454. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  78455. this._debugLines[i] = points;
  78456. }
  78457. this._getBonePosition(points[0], bone, meshMat);
  78458. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  78459. points[0].subtractInPlace(meshPos);
  78460. points[1].subtractInPlace(meshPos);
  78461. }
  78462. };
  78463. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  78464. var len = bones.length;
  78465. var boneNum = 0;
  78466. var meshPos = this.mesh.position;
  78467. for (var i = len - 1; i >= 0; i--) {
  78468. var childBone = bones[i];
  78469. var parentBone = childBone.getParent();
  78470. if (!parentBone) {
  78471. continue;
  78472. }
  78473. var points = this._debugLines[boneNum];
  78474. if (!points) {
  78475. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  78476. this._debugLines[boneNum] = points;
  78477. }
  78478. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  78479. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  78480. points[0].subtractInPlace(meshPos);
  78481. points[1].subtractInPlace(meshPos);
  78482. boneNum++;
  78483. }
  78484. };
  78485. SkeletonViewer.prototype.update = function () {
  78486. if (this.autoUpdateBonesMatrices) {
  78487. this.skeleton.computeAbsoluteTransforms();
  78488. }
  78489. if (this.skeleton.bones[0].length === undefined) {
  78490. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  78491. }
  78492. else {
  78493. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  78494. }
  78495. if (!this._debugMesh) {
  78496. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  78497. this._debugMesh.renderingGroupId = this.renderingGroupId;
  78498. }
  78499. else {
  78500. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  78501. }
  78502. this._debugMesh.position.copyFrom(this.mesh.position);
  78503. this._debugMesh.color = this.color;
  78504. };
  78505. SkeletonViewer.prototype.dispose = function () {
  78506. if (this._debugMesh) {
  78507. this.isEnabled = false;
  78508. this._debugMesh.dispose();
  78509. this._debugMesh = null;
  78510. }
  78511. };
  78512. return SkeletonViewer;
  78513. }());
  78514. return Debug;
  78515. }());
  78516. BABYLON.Debug = Debug;
  78517. })(BABYLON || (BABYLON = {}));
  78518. //# sourceMappingURL=babylon.debugModules.js.map
  78519. var BABYLON;
  78520. (function (BABYLON) {
  78521. var RayHelper = /** @class */ (function () {
  78522. function RayHelper(ray) {
  78523. this.ray = ray;
  78524. }
  78525. RayHelper.CreateAndShow = function (ray, scene, color) {
  78526. var helper = new RayHelper(ray);
  78527. helper.show(scene, color);
  78528. return helper;
  78529. };
  78530. RayHelper.prototype.show = function (scene, color) {
  78531. if (!this._renderFunction && this.ray) {
  78532. var ray = this.ray;
  78533. this._renderFunction = this._render.bind(this);
  78534. this._scene = scene;
  78535. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  78536. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  78537. if (this._renderFunction) {
  78538. this._scene.registerBeforeRender(this._renderFunction);
  78539. }
  78540. }
  78541. if (color && this._renderLine) {
  78542. this._renderLine.color.copyFrom(color);
  78543. }
  78544. };
  78545. RayHelper.prototype.hide = function () {
  78546. if (this._renderFunction && this._scene) {
  78547. this._scene.unregisterBeforeRender(this._renderFunction);
  78548. this._scene = null;
  78549. this._renderFunction = null;
  78550. if (this._renderLine) {
  78551. this._renderLine.dispose();
  78552. this._renderLine = null;
  78553. }
  78554. this._renderPoints = [];
  78555. }
  78556. };
  78557. RayHelper.prototype._render = function () {
  78558. var ray = this.ray;
  78559. if (!ray) {
  78560. return;
  78561. }
  78562. var point = this._renderPoints[1];
  78563. var len = Math.min(ray.length, 1000000);
  78564. point.copyFrom(ray.direction);
  78565. point.scaleInPlace(len);
  78566. point.addInPlace(ray.origin);
  78567. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  78568. };
  78569. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  78570. this._attachedToMesh = mesh;
  78571. var ray = this.ray;
  78572. if (!ray) {
  78573. return;
  78574. }
  78575. if (!ray.direction) {
  78576. ray.direction = BABYLON.Vector3.Zero();
  78577. }
  78578. if (!ray.origin) {
  78579. ray.origin = BABYLON.Vector3.Zero();
  78580. }
  78581. if (length) {
  78582. ray.length = length;
  78583. }
  78584. if (!meshSpaceOrigin) {
  78585. meshSpaceOrigin = BABYLON.Vector3.Zero();
  78586. }
  78587. if (!meshSpaceDirection) {
  78588. // -1 so that this will work with Mesh.lookAt
  78589. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  78590. }
  78591. if (!this._meshSpaceDirection) {
  78592. this._meshSpaceDirection = meshSpaceDirection.clone();
  78593. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  78594. }
  78595. else {
  78596. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  78597. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  78598. }
  78599. if (!this._updateToMeshFunction) {
  78600. this._updateToMeshFunction = this._updateToMesh.bind(this);
  78601. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  78602. }
  78603. this._updateToMesh();
  78604. };
  78605. RayHelper.prototype.detachFromMesh = function () {
  78606. if (this._attachedToMesh) {
  78607. if (this._updateToMeshFunction) {
  78608. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  78609. }
  78610. this._attachedToMesh = null;
  78611. this._updateToMeshFunction = null;
  78612. }
  78613. };
  78614. RayHelper.prototype._updateToMesh = function () {
  78615. var ray = this.ray;
  78616. if (!this._attachedToMesh || !ray) {
  78617. return;
  78618. }
  78619. if (this._attachedToMesh._isDisposed) {
  78620. this.detachFromMesh();
  78621. return;
  78622. }
  78623. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  78624. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  78625. };
  78626. RayHelper.prototype.dispose = function () {
  78627. this.hide();
  78628. this.detachFromMesh();
  78629. this.ray = null;
  78630. };
  78631. return RayHelper;
  78632. }());
  78633. BABYLON.RayHelper = RayHelper;
  78634. })(BABYLON || (BABYLON = {}));
  78635. //# sourceMappingURL=babylon.rayHelper.js.map
  78636. var BABYLON;
  78637. (function (BABYLON) {
  78638. // load the inspector using require, if not present in the global namespace.
  78639. var DebugLayer = /** @class */ (function () {
  78640. function DebugLayer(scene) {
  78641. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  78642. this._scene = scene;
  78643. // load inspector using require, if it doesn't exist on the global namespace.
  78644. }
  78645. /** Creates the inspector window. */
  78646. DebugLayer.prototype._createInspector = function (config) {
  78647. if (config === void 0) { config = {}; }
  78648. var popup = config.popup || false;
  78649. var initialTab = config.initialTab || 0;
  78650. var parentElement = config.parentElement || null;
  78651. if (!this._inspector) {
  78652. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  78653. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  78654. } // else nothing to do,; instance is already existing
  78655. };
  78656. DebugLayer.prototype.isVisible = function () {
  78657. if (!this._inspector) {
  78658. return false;
  78659. }
  78660. return true;
  78661. };
  78662. DebugLayer.prototype.hide = function () {
  78663. if (this._inspector) {
  78664. try {
  78665. this._inspector.dispose();
  78666. }
  78667. catch (e) {
  78668. // If the inspector has been removed directly from the inspector tool
  78669. }
  78670. this._inspector = null;
  78671. }
  78672. };
  78673. DebugLayer.prototype.show = function (config) {
  78674. if (config === void 0) { config = {}; }
  78675. if (typeof this.BJSINSPECTOR == 'undefined') {
  78676. // Load inspector and add it to the DOM
  78677. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  78678. }
  78679. else {
  78680. // Otherwise creates the inspector
  78681. this._createInspector(config);
  78682. }
  78683. };
  78684. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  78685. return DebugLayer;
  78686. }());
  78687. BABYLON.DebugLayer = DebugLayer;
  78688. })(BABYLON || (BABYLON = {}));
  78689. //# sourceMappingURL=babylon.debugLayer.js.map
  78690. var BABYLON;
  78691. (function (BABYLON) {
  78692. var BoundingBoxRenderer = /** @class */ (function () {
  78693. function BoundingBoxRenderer(scene) {
  78694. this.frontColor = new BABYLON.Color3(1, 1, 1);
  78695. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  78696. this.showBackLines = true;
  78697. this.renderList = new BABYLON.SmartArray(32);
  78698. this._vertexBuffers = {};
  78699. this._scene = scene;
  78700. }
  78701. BoundingBoxRenderer.prototype._prepareRessources = function () {
  78702. if (this._colorShader) {
  78703. return;
  78704. }
  78705. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  78706. attributes: [BABYLON.VertexBuffer.PositionKind],
  78707. uniforms: ["world", "viewProjection", "color"]
  78708. });
  78709. var engine = this._scene.getEngine();
  78710. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  78711. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  78712. this._createIndexBuffer();
  78713. };
  78714. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  78715. var engine = this._scene.getEngine();
  78716. 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]);
  78717. };
  78718. BoundingBoxRenderer.prototype._rebuild = function () {
  78719. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  78720. if (vb) {
  78721. vb._rebuild();
  78722. }
  78723. this._createIndexBuffer();
  78724. };
  78725. BoundingBoxRenderer.prototype.reset = function () {
  78726. this.renderList.reset();
  78727. };
  78728. BoundingBoxRenderer.prototype.render = function () {
  78729. if (this.renderList.length === 0) {
  78730. return;
  78731. }
  78732. this._prepareRessources();
  78733. if (!this._colorShader.isReady()) {
  78734. return;
  78735. }
  78736. var engine = this._scene.getEngine();
  78737. engine.setDepthWrite(false);
  78738. this._colorShader._preBind();
  78739. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  78740. var boundingBox = this.renderList.data[boundingBoxIndex];
  78741. var min = boundingBox.minimum;
  78742. var max = boundingBox.maximum;
  78743. var diff = max.subtract(min);
  78744. var median = min.add(diff.scale(0.5));
  78745. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  78746. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  78747. .multiply(boundingBox.getWorldMatrix());
  78748. // VBOs
  78749. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  78750. if (this.showBackLines) {
  78751. // Back
  78752. engine.setDepthFunctionToGreaterOrEqual();
  78753. this._scene.resetCachedMaterial();
  78754. this._colorShader.setColor4("color", this.backColor.toColor4());
  78755. this._colorShader.bind(worldMatrix);
  78756. // Draw order
  78757. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  78758. }
  78759. // Front
  78760. engine.setDepthFunctionToLess();
  78761. this._scene.resetCachedMaterial();
  78762. this._colorShader.setColor4("color", this.frontColor.toColor4());
  78763. this._colorShader.bind(worldMatrix);
  78764. // Draw order
  78765. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  78766. }
  78767. this._colorShader.unbind();
  78768. engine.setDepthFunctionToLessOrEqual();
  78769. engine.setDepthWrite(true);
  78770. };
  78771. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  78772. this._prepareRessources();
  78773. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  78774. return;
  78775. }
  78776. var engine = this._scene.getEngine();
  78777. engine.setDepthWrite(false);
  78778. engine.setColorWrite(false);
  78779. this._colorShader._preBind();
  78780. var boundingBox = mesh._boundingInfo.boundingBox;
  78781. var min = boundingBox.minimum;
  78782. var max = boundingBox.maximum;
  78783. var diff = max.subtract(min);
  78784. var median = min.add(diff.scale(0.5));
  78785. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  78786. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  78787. .multiply(boundingBox.getWorldMatrix());
  78788. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  78789. engine.setDepthFunctionToLess();
  78790. this._scene.resetCachedMaterial();
  78791. this._colorShader.bind(worldMatrix);
  78792. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  78793. this._colorShader.unbind();
  78794. engine.setDepthFunctionToLessOrEqual();
  78795. engine.setDepthWrite(true);
  78796. engine.setColorWrite(true);
  78797. };
  78798. BoundingBoxRenderer.prototype.dispose = function () {
  78799. if (!this._colorShader) {
  78800. return;
  78801. }
  78802. this.renderList.dispose();
  78803. this._colorShader.dispose();
  78804. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  78805. if (buffer) {
  78806. buffer.dispose();
  78807. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  78808. }
  78809. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  78810. };
  78811. return BoundingBoxRenderer;
  78812. }());
  78813. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  78814. })(BABYLON || (BABYLON = {}));
  78815. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  78816. var BABYLON;
  78817. (function (BABYLON) {
  78818. var MorphTarget = /** @class */ (function () {
  78819. function MorphTarget(name, influence) {
  78820. if (influence === void 0) { influence = 0; }
  78821. this.name = name;
  78822. this.animations = new Array();
  78823. this._positions = null;
  78824. this._normals = null;
  78825. this._tangents = null;
  78826. this.onInfluenceChanged = new BABYLON.Observable();
  78827. this.influence = influence;
  78828. }
  78829. Object.defineProperty(MorphTarget.prototype, "influence", {
  78830. get: function () {
  78831. return this._influence;
  78832. },
  78833. set: function (influence) {
  78834. if (this._influence === influence) {
  78835. return;
  78836. }
  78837. var previous = this._influence;
  78838. this._influence = influence;
  78839. if (this.onInfluenceChanged.hasObservers) {
  78840. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  78841. }
  78842. },
  78843. enumerable: true,
  78844. configurable: true
  78845. });
  78846. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  78847. get: function () {
  78848. return !!this._positions;
  78849. },
  78850. enumerable: true,
  78851. configurable: true
  78852. });
  78853. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  78854. get: function () {
  78855. return !!this._normals;
  78856. },
  78857. enumerable: true,
  78858. configurable: true
  78859. });
  78860. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  78861. get: function () {
  78862. return !!this._tangents;
  78863. },
  78864. enumerable: true,
  78865. configurable: true
  78866. });
  78867. MorphTarget.prototype.setPositions = function (data) {
  78868. this._positions = data;
  78869. };
  78870. MorphTarget.prototype.getPositions = function () {
  78871. return this._positions;
  78872. };
  78873. MorphTarget.prototype.setNormals = function (data) {
  78874. this._normals = data;
  78875. };
  78876. MorphTarget.prototype.getNormals = function () {
  78877. return this._normals;
  78878. };
  78879. MorphTarget.prototype.setTangents = function (data) {
  78880. this._tangents = data;
  78881. };
  78882. MorphTarget.prototype.getTangents = function () {
  78883. return this._tangents;
  78884. };
  78885. /**
  78886. * Serializes the current target into a Serialization object.
  78887. * Returns the serialized object.
  78888. */
  78889. MorphTarget.prototype.serialize = function () {
  78890. var serializationObject = {};
  78891. serializationObject.name = this.name;
  78892. serializationObject.influence = this.influence;
  78893. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  78894. if (this.hasNormals) {
  78895. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  78896. }
  78897. if (this.hasTangents) {
  78898. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  78899. }
  78900. // Animations
  78901. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  78902. return serializationObject;
  78903. };
  78904. // Statics
  78905. MorphTarget.Parse = function (serializationObject) {
  78906. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  78907. result.setPositions(serializationObject.positions);
  78908. if (serializationObject.normals) {
  78909. result.setNormals(serializationObject.normals);
  78910. }
  78911. if (serializationObject.tangents) {
  78912. result.setTangents(serializationObject.tangents);
  78913. }
  78914. // Animations
  78915. if (serializationObject.animations) {
  78916. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  78917. var parsedAnimation = serializationObject.animations[animationIndex];
  78918. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  78919. }
  78920. }
  78921. return result;
  78922. };
  78923. MorphTarget.FromMesh = function (mesh, name, influence) {
  78924. if (!name) {
  78925. name = mesh.name;
  78926. }
  78927. var result = new MorphTarget(name, influence);
  78928. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  78929. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  78930. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  78931. }
  78932. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  78933. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  78934. }
  78935. return result;
  78936. };
  78937. return MorphTarget;
  78938. }());
  78939. BABYLON.MorphTarget = MorphTarget;
  78940. })(BABYLON || (BABYLON = {}));
  78941. //# sourceMappingURL=babylon.morphTarget.js.map
  78942. var BABYLON;
  78943. (function (BABYLON) {
  78944. var MorphTargetManager = /** @class */ (function () {
  78945. function MorphTargetManager(scene) {
  78946. if (scene === void 0) { scene = null; }
  78947. this._targets = new Array();
  78948. this._targetObservable = new Array();
  78949. this._activeTargets = new BABYLON.SmartArray(16);
  78950. this._supportsNormals = false;
  78951. this._supportsTangents = false;
  78952. this._vertexCount = 0;
  78953. this._uniqueId = 0;
  78954. this._tempInfluences = new Array();
  78955. if (!scene) {
  78956. scene = BABYLON.Engine.LastCreatedScene;
  78957. }
  78958. this._scene = scene;
  78959. if (this._scene) {
  78960. this._scene.morphTargetManagers.push(this);
  78961. this._uniqueId = this._scene.getUniqueId();
  78962. }
  78963. }
  78964. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  78965. get: function () {
  78966. return this._uniqueId;
  78967. },
  78968. enumerable: true,
  78969. configurable: true
  78970. });
  78971. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  78972. get: function () {
  78973. return this._vertexCount;
  78974. },
  78975. enumerable: true,
  78976. configurable: true
  78977. });
  78978. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  78979. get: function () {
  78980. return this._supportsNormals;
  78981. },
  78982. enumerable: true,
  78983. configurable: true
  78984. });
  78985. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  78986. get: function () {
  78987. return this._supportsTangents;
  78988. },
  78989. enumerable: true,
  78990. configurable: true
  78991. });
  78992. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  78993. get: function () {
  78994. return this._targets.length;
  78995. },
  78996. enumerable: true,
  78997. configurable: true
  78998. });
  78999. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  79000. get: function () {
  79001. return this._activeTargets.length;
  79002. },
  79003. enumerable: true,
  79004. configurable: true
  79005. });
  79006. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  79007. get: function () {
  79008. return this._influences;
  79009. },
  79010. enumerable: true,
  79011. configurable: true
  79012. });
  79013. MorphTargetManager.prototype.getActiveTarget = function (index) {
  79014. return this._activeTargets.data[index];
  79015. };
  79016. MorphTargetManager.prototype.getTarget = function (index) {
  79017. return this._targets[index];
  79018. };
  79019. MorphTargetManager.prototype.addTarget = function (target) {
  79020. var _this = this;
  79021. this._targets.push(target);
  79022. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  79023. _this._syncActiveTargets(needUpdate);
  79024. }));
  79025. this._syncActiveTargets(true);
  79026. };
  79027. MorphTargetManager.prototype.removeTarget = function (target) {
  79028. var index = this._targets.indexOf(target);
  79029. if (index >= 0) {
  79030. this._targets.splice(index, 1);
  79031. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  79032. this._syncActiveTargets(true);
  79033. }
  79034. };
  79035. /**
  79036. * Serializes the current manager into a Serialization object.
  79037. * Returns the serialized object.
  79038. */
  79039. MorphTargetManager.prototype.serialize = function () {
  79040. var serializationObject = {};
  79041. serializationObject.id = this.uniqueId;
  79042. serializationObject.targets = [];
  79043. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  79044. var target = _a[_i];
  79045. serializationObject.targets.push(target.serialize());
  79046. }
  79047. return serializationObject;
  79048. };
  79049. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  79050. var influenceCount = 0;
  79051. this._activeTargets.reset();
  79052. this._supportsNormals = true;
  79053. this._supportsTangents = true;
  79054. this._vertexCount = 0;
  79055. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  79056. var target = _a[_i];
  79057. this._activeTargets.push(target);
  79058. this._tempInfluences[influenceCount++] = target.influence;
  79059. var positions = target.getPositions();
  79060. if (positions) {
  79061. this._supportsNormals = this._supportsNormals && target.hasNormals;
  79062. this._supportsTangents = this._supportsTangents && target.hasTangents;
  79063. var vertexCount = positions.length / 3;
  79064. if (this._vertexCount === 0) {
  79065. this._vertexCount = vertexCount;
  79066. }
  79067. else if (this._vertexCount !== vertexCount) {
  79068. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  79069. return;
  79070. }
  79071. }
  79072. }
  79073. if (!this._influences || this._influences.length !== influenceCount) {
  79074. this._influences = new Float32Array(influenceCount);
  79075. }
  79076. for (var index = 0; index < influenceCount; index++) {
  79077. this._influences[index] = this._tempInfluences[index];
  79078. }
  79079. if (needUpdate && this._scene) {
  79080. // Flag meshes as dirty to resync with the active targets
  79081. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  79082. var mesh = _c[_b];
  79083. if (mesh.morphTargetManager === this) {
  79084. mesh._syncGeometryWithMorphTargetManager();
  79085. }
  79086. }
  79087. }
  79088. };
  79089. // Statics
  79090. MorphTargetManager.Parse = function (serializationObject, scene) {
  79091. var result = new MorphTargetManager(scene);
  79092. result._uniqueId = serializationObject.id;
  79093. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  79094. var targetData = _a[_i];
  79095. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  79096. }
  79097. return result;
  79098. };
  79099. return MorphTargetManager;
  79100. }());
  79101. BABYLON.MorphTargetManager = MorphTargetManager;
  79102. })(BABYLON || (BABYLON = {}));
  79103. //# sourceMappingURL=babylon.morphTargetManager.js.map
  79104. var BABYLON;
  79105. (function (BABYLON) {
  79106. var Octree = /** @class */ (function () {
  79107. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  79108. if (maxDepth === void 0) { maxDepth = 2; }
  79109. this.maxDepth = maxDepth;
  79110. this.dynamicContent = new Array();
  79111. this._maxBlockCapacity = maxBlockCapacity || 64;
  79112. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  79113. this._creationFunc = creationFunc;
  79114. }
  79115. // Methods
  79116. Octree.prototype.update = function (worldMin, worldMax, entries) {
  79117. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  79118. };
  79119. Octree.prototype.addMesh = function (entry) {
  79120. for (var index = 0; index < this.blocks.length; index++) {
  79121. var block = this.blocks[index];
  79122. block.addEntry(entry);
  79123. }
  79124. };
  79125. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  79126. this._selectionContent.reset();
  79127. for (var index = 0; index < this.blocks.length; index++) {
  79128. var block = this.blocks[index];
  79129. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  79130. }
  79131. if (allowDuplicate) {
  79132. this._selectionContent.concat(this.dynamicContent);
  79133. }
  79134. else {
  79135. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  79136. }
  79137. return this._selectionContent;
  79138. };
  79139. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  79140. this._selectionContent.reset();
  79141. for (var index = 0; index < this.blocks.length; index++) {
  79142. var block = this.blocks[index];
  79143. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  79144. }
  79145. if (allowDuplicate) {
  79146. this._selectionContent.concat(this.dynamicContent);
  79147. }
  79148. else {
  79149. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  79150. }
  79151. return this._selectionContent;
  79152. };
  79153. Octree.prototype.intersectsRay = function (ray) {
  79154. this._selectionContent.reset();
  79155. for (var index = 0; index < this.blocks.length; index++) {
  79156. var block = this.blocks[index];
  79157. block.intersectsRay(ray, this._selectionContent);
  79158. }
  79159. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  79160. return this._selectionContent;
  79161. };
  79162. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  79163. target.blocks = new Array();
  79164. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  79165. // Segmenting space
  79166. for (var x = 0; x < 2; x++) {
  79167. for (var y = 0; y < 2; y++) {
  79168. for (var z = 0; z < 2; z++) {
  79169. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  79170. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  79171. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  79172. block.addEntries(entries);
  79173. target.blocks.push(block);
  79174. }
  79175. }
  79176. }
  79177. };
  79178. Octree.CreationFuncForMeshes = function (entry, block) {
  79179. var boundingInfo = entry.getBoundingInfo();
  79180. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  79181. block.entries.push(entry);
  79182. }
  79183. };
  79184. Octree.CreationFuncForSubMeshes = function (entry, block) {
  79185. var boundingInfo = entry.getBoundingInfo();
  79186. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  79187. block.entries.push(entry);
  79188. }
  79189. };
  79190. return Octree;
  79191. }());
  79192. BABYLON.Octree = Octree;
  79193. })(BABYLON || (BABYLON = {}));
  79194. //# sourceMappingURL=babylon.octree.js.map
  79195. var BABYLON;
  79196. (function (BABYLON) {
  79197. var OctreeBlock = /** @class */ (function () {
  79198. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  79199. this.entries = new Array();
  79200. this._boundingVectors = new Array();
  79201. this._capacity = capacity;
  79202. this._depth = depth;
  79203. this._maxDepth = maxDepth;
  79204. this._creationFunc = creationFunc;
  79205. this._minPoint = minPoint;
  79206. this._maxPoint = maxPoint;
  79207. this._boundingVectors.push(minPoint.clone());
  79208. this._boundingVectors.push(maxPoint.clone());
  79209. this._boundingVectors.push(minPoint.clone());
  79210. this._boundingVectors[2].x = maxPoint.x;
  79211. this._boundingVectors.push(minPoint.clone());
  79212. this._boundingVectors[3].y = maxPoint.y;
  79213. this._boundingVectors.push(minPoint.clone());
  79214. this._boundingVectors[4].z = maxPoint.z;
  79215. this._boundingVectors.push(maxPoint.clone());
  79216. this._boundingVectors[5].z = minPoint.z;
  79217. this._boundingVectors.push(maxPoint.clone());
  79218. this._boundingVectors[6].x = minPoint.x;
  79219. this._boundingVectors.push(maxPoint.clone());
  79220. this._boundingVectors[7].y = minPoint.y;
  79221. }
  79222. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  79223. // Property
  79224. get: function () {
  79225. return this._capacity;
  79226. },
  79227. enumerable: true,
  79228. configurable: true
  79229. });
  79230. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  79231. get: function () {
  79232. return this._minPoint;
  79233. },
  79234. enumerable: true,
  79235. configurable: true
  79236. });
  79237. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  79238. get: function () {
  79239. return this._maxPoint;
  79240. },
  79241. enumerable: true,
  79242. configurable: true
  79243. });
  79244. // Methods
  79245. OctreeBlock.prototype.addEntry = function (entry) {
  79246. if (this.blocks) {
  79247. for (var index = 0; index < this.blocks.length; index++) {
  79248. var block = this.blocks[index];
  79249. block.addEntry(entry);
  79250. }
  79251. return;
  79252. }
  79253. this._creationFunc(entry, this);
  79254. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  79255. this.createInnerBlocks();
  79256. }
  79257. };
  79258. OctreeBlock.prototype.addEntries = function (entries) {
  79259. for (var index = 0; index < entries.length; index++) {
  79260. var mesh = entries[index];
  79261. this.addEntry(mesh);
  79262. }
  79263. };
  79264. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  79265. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  79266. if (this.blocks) {
  79267. for (var index = 0; index < this.blocks.length; index++) {
  79268. var block = this.blocks[index];
  79269. block.select(frustumPlanes, selection, allowDuplicate);
  79270. }
  79271. return;
  79272. }
  79273. if (allowDuplicate) {
  79274. selection.concat(this.entries);
  79275. }
  79276. else {
  79277. selection.concatWithNoDuplicate(this.entries);
  79278. }
  79279. }
  79280. };
  79281. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  79282. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  79283. if (this.blocks) {
  79284. for (var index = 0; index < this.blocks.length; index++) {
  79285. var block = this.blocks[index];
  79286. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  79287. }
  79288. return;
  79289. }
  79290. if (allowDuplicate) {
  79291. selection.concat(this.entries);
  79292. }
  79293. else {
  79294. selection.concatWithNoDuplicate(this.entries);
  79295. }
  79296. }
  79297. };
  79298. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  79299. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  79300. if (this.blocks) {
  79301. for (var index = 0; index < this.blocks.length; index++) {
  79302. var block = this.blocks[index];
  79303. block.intersectsRay(ray, selection);
  79304. }
  79305. return;
  79306. }
  79307. selection.concatWithNoDuplicate(this.entries);
  79308. }
  79309. };
  79310. OctreeBlock.prototype.createInnerBlocks = function () {
  79311. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  79312. };
  79313. return OctreeBlock;
  79314. }());
  79315. BABYLON.OctreeBlock = OctreeBlock;
  79316. })(BABYLON || (BABYLON = {}));
  79317. //# sourceMappingURL=babylon.octreeBlock.js.map
  79318. var BABYLON;
  79319. (function (BABYLON) {
  79320. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  79321. __extends(VRDistortionCorrectionPostProcess, _super);
  79322. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  79323. var _this = _super.call(this, name, "vrDistortionCorrection", [
  79324. 'LensCenter',
  79325. 'Scale',
  79326. 'ScaleIn',
  79327. 'HmdWarpParam'
  79328. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  79329. _this._isRightEye = isRightEye;
  79330. _this._distortionFactors = vrMetrics.distortionK;
  79331. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  79332. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  79333. _this.adaptScaleToCurrentViewport = true;
  79334. _this.onSizeChangedObservable.add(function () {
  79335. _this.aspectRatio = _this.width * .5 / _this.height;
  79336. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  79337. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  79338. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  79339. });
  79340. _this.onApplyObservable.add(function (effect) {
  79341. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  79342. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  79343. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  79344. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  79345. });
  79346. return _this;
  79347. }
  79348. return VRDistortionCorrectionPostProcess;
  79349. }(BABYLON.PostProcess));
  79350. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  79351. })(BABYLON || (BABYLON = {}));
  79352. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  79353. var BABYLON;
  79354. (function (BABYLON) {
  79355. var AnaglyphPostProcess = /** @class */ (function (_super) {
  79356. __extends(AnaglyphPostProcess, _super);
  79357. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  79358. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  79359. _this._passedProcess = rigCameras[0]._rigPostProcess;
  79360. _this.onApplyObservable.add(function (effect) {
  79361. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  79362. });
  79363. return _this;
  79364. }
  79365. return AnaglyphPostProcess;
  79366. }(BABYLON.PostProcess));
  79367. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  79368. })(BABYLON || (BABYLON = {}));
  79369. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  79370. var BABYLON;
  79371. (function (BABYLON) {
  79372. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  79373. __extends(StereoscopicInterlacePostProcess, _super);
  79374. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  79375. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  79376. _this._passedProcess = rigCameras[0]._rigPostProcess;
  79377. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  79378. _this.onSizeChangedObservable.add(function () {
  79379. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  79380. });
  79381. _this.onApplyObservable.add(function (effect) {
  79382. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  79383. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  79384. });
  79385. return _this;
  79386. }
  79387. return StereoscopicInterlacePostProcess;
  79388. }(BABYLON.PostProcess));
  79389. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  79390. })(BABYLON || (BABYLON = {}));
  79391. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  79392. var BABYLON;
  79393. (function (BABYLON) {
  79394. /**
  79395. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  79396. * Screen rotation is taken into account.
  79397. */
  79398. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  79399. function FreeCameraDeviceOrientationInput() {
  79400. var _this = this;
  79401. this._screenOrientationAngle = 0;
  79402. this._screenQuaternion = new BABYLON.Quaternion();
  79403. this._alpha = 0;
  79404. this._beta = 0;
  79405. this._gamma = 0;
  79406. this._orientationChanged = function () {
  79407. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  79408. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  79409. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  79410. };
  79411. this._deviceOrientation = function (evt) {
  79412. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  79413. _this._beta = evt.beta !== null ? evt.beta : 0;
  79414. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  79415. };
  79416. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  79417. this._orientationChanged();
  79418. }
  79419. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  79420. get: function () {
  79421. return this._camera;
  79422. },
  79423. set: function (camera) {
  79424. this._camera = camera;
  79425. if (this._camera != null && !this._camera.rotationQuaternion) {
  79426. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  79427. }
  79428. },
  79429. enumerable: true,
  79430. configurable: true
  79431. });
  79432. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  79433. window.addEventListener("orientationchange", this._orientationChanged);
  79434. window.addEventListener("deviceorientation", this._deviceOrientation);
  79435. //In certain cases, the attach control is called AFTER orientation was changed,
  79436. //So this is needed.
  79437. this._orientationChanged();
  79438. };
  79439. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  79440. window.removeEventListener("orientationchange", this._orientationChanged);
  79441. window.removeEventListener("deviceorientation", this._deviceOrientation);
  79442. };
  79443. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  79444. //if no device orientation provided, don't update the rotation.
  79445. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  79446. if (!this._alpha)
  79447. return;
  79448. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  79449. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  79450. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  79451. //Mirror on XY Plane
  79452. this._camera.rotationQuaternion.z *= -1;
  79453. this._camera.rotationQuaternion.w *= -1;
  79454. };
  79455. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  79456. return "FreeCameraDeviceOrientationInput";
  79457. };
  79458. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  79459. return "deviceOrientation";
  79460. };
  79461. return FreeCameraDeviceOrientationInput;
  79462. }());
  79463. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  79464. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  79465. })(BABYLON || (BABYLON = {}));
  79466. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  79467. var BABYLON;
  79468. (function (BABYLON) {
  79469. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  79470. function ArcRotateCameraVRDeviceOrientationInput() {
  79471. this.alphaCorrection = 1;
  79472. this.betaCorrection = 1;
  79473. this.gammaCorrection = 1;
  79474. this._alpha = 0;
  79475. this._gamma = 0;
  79476. this._dirty = false;
  79477. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  79478. }
  79479. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  79480. this.camera.attachControl(element, noPreventDefault);
  79481. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  79482. };
  79483. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  79484. if (evt.alpha !== null) {
  79485. this._alpha = +evt.alpha | 0;
  79486. }
  79487. if (evt.gamma !== null) {
  79488. this._gamma = +evt.gamma | 0;
  79489. }
  79490. this._dirty = true;
  79491. };
  79492. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  79493. if (this._dirty) {
  79494. this._dirty = false;
  79495. if (this._gamma < 0) {
  79496. this._gamma = 180 + this._gamma;
  79497. }
  79498. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  79499. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  79500. }
  79501. };
  79502. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  79503. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  79504. };
  79505. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  79506. return "ArcRotateCameraVRDeviceOrientationInput";
  79507. };
  79508. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  79509. return "VRDeviceOrientation";
  79510. };
  79511. return ArcRotateCameraVRDeviceOrientationInput;
  79512. }());
  79513. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  79514. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  79515. })(BABYLON || (BABYLON = {}));
  79516. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  79517. var BABYLON;
  79518. (function (BABYLON) {
  79519. var VRCameraMetrics = /** @class */ (function () {
  79520. function VRCameraMetrics() {
  79521. this.compensateDistortion = true;
  79522. }
  79523. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  79524. get: function () {
  79525. return this.hResolution / (2 * this.vResolution);
  79526. },
  79527. enumerable: true,
  79528. configurable: true
  79529. });
  79530. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  79531. get: function () {
  79532. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  79533. },
  79534. enumerable: true,
  79535. configurable: true
  79536. });
  79537. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  79538. get: function () {
  79539. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  79540. var h = (4 * meters) / this.hScreenSize;
  79541. return BABYLON.Matrix.Translation(h, 0, 0);
  79542. },
  79543. enumerable: true,
  79544. configurable: true
  79545. });
  79546. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  79547. get: function () {
  79548. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  79549. var h = (4 * meters) / this.hScreenSize;
  79550. return BABYLON.Matrix.Translation(-h, 0, 0);
  79551. },
  79552. enumerable: true,
  79553. configurable: true
  79554. });
  79555. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  79556. get: function () {
  79557. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  79558. },
  79559. enumerable: true,
  79560. configurable: true
  79561. });
  79562. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  79563. get: function () {
  79564. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  79565. },
  79566. enumerable: true,
  79567. configurable: true
  79568. });
  79569. VRCameraMetrics.GetDefault = function () {
  79570. var result = new VRCameraMetrics();
  79571. result.hResolution = 1280;
  79572. result.vResolution = 800;
  79573. result.hScreenSize = 0.149759993;
  79574. result.vScreenSize = 0.0935999975;
  79575. result.vScreenCenter = 0.0467999987;
  79576. result.eyeToScreenDistance = 0.0410000011;
  79577. result.lensSeparationDistance = 0.0635000020;
  79578. result.interpupillaryDistance = 0.0640000030;
  79579. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  79580. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  79581. result.postProcessScaleFactor = 1.714605507808412;
  79582. result.lensCenterOffset = 0.151976421;
  79583. return result;
  79584. };
  79585. return VRCameraMetrics;
  79586. }());
  79587. BABYLON.VRCameraMetrics = VRCameraMetrics;
  79588. })(BABYLON || (BABYLON = {}));
  79589. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  79590. var BABYLON;
  79591. (function (BABYLON) {
  79592. /**
  79593. * This represents a WebVR camera.
  79594. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  79595. * @example http://doc.babylonjs.com/how_to/webvr_camera
  79596. */
  79597. var WebVRFreeCamera = /** @class */ (function (_super) {
  79598. __extends(WebVRFreeCamera, _super);
  79599. /**
  79600. * Instantiates a WebVRFreeCamera.
  79601. * @param name The name of the WebVRFreeCamera
  79602. * @param position The starting anchor position for the camera
  79603. * @param scene The scene the camera belongs to
  79604. * @param webVROptions a set of customizable options for the webVRCamera
  79605. */
  79606. function WebVRFreeCamera(name, position, scene, webVROptions) {
  79607. if (webVROptions === void 0) { webVROptions = {}; }
  79608. var _this = _super.call(this, name, position, scene) || this;
  79609. _this.webVROptions = webVROptions;
  79610. /**
  79611. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  79612. */
  79613. _this._vrDevice = null;
  79614. /**
  79615. * The rawPose of the vrDevice.
  79616. */
  79617. _this.rawPose = null;
  79618. _this._specsVersion = "1.1";
  79619. _this._attached = false;
  79620. _this._descendants = [];
  79621. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  79622. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  79623. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  79624. _this._standingMatrix = null;
  79625. /**
  79626. * Represents device position in babylon space.
  79627. */
  79628. _this.devicePosition = BABYLON.Vector3.Zero();
  79629. /**
  79630. * Represents device rotation in babylon space.
  79631. */
  79632. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  79633. /**
  79634. * The scale of the device to be used when translating from device space to babylon space.
  79635. */
  79636. _this.deviceScaleFactor = 1;
  79637. _this._deviceToWorld = BABYLON.Matrix.Identity();
  79638. _this._worldToDevice = BABYLON.Matrix.Identity();
  79639. /**
  79640. * References to the webVR controllers for the vrDevice.
  79641. */
  79642. _this.controllers = [];
  79643. /**
  79644. * Emits an event when a controller is attached.
  79645. */
  79646. _this.onControllersAttachedObservable = new BABYLON.Observable();
  79647. /**
  79648. * Emits an event when a controller's mesh has been loaded;
  79649. */
  79650. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  79651. /**
  79652. * If the rig cameras be used as parent instead of this camera.
  79653. */
  79654. _this.rigParenting = true;
  79655. _this._defaultHeight = undefined;
  79656. _this._workingVector = BABYLON.Vector3.Zero();
  79657. _this._oneVector = BABYLON.Vector3.One();
  79658. _this._workingMatrix = BABYLON.Matrix.Identity();
  79659. _this._cache.position = BABYLON.Vector3.Zero();
  79660. if (webVROptions.defaultHeight) {
  79661. _this._defaultHeight = webVROptions.defaultHeight;
  79662. _this.position.y = _this._defaultHeight;
  79663. }
  79664. _this.minZ = 0.1;
  79665. //legacy support - the compensation boolean was removed.
  79666. if (arguments.length === 5) {
  79667. _this.webVROptions = arguments[4];
  79668. }
  79669. // default webVR options
  79670. if (_this.webVROptions.trackPosition == undefined) {
  79671. _this.webVROptions.trackPosition = true;
  79672. }
  79673. if (_this.webVROptions.controllerMeshes == undefined) {
  79674. _this.webVROptions.controllerMeshes = true;
  79675. }
  79676. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  79677. _this.webVROptions.defaultLightingOnControllers = true;
  79678. }
  79679. _this.rotationQuaternion = new BABYLON.Quaternion();
  79680. if (_this.webVROptions && _this.webVROptions.positionScale) {
  79681. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  79682. }
  79683. //enable VR
  79684. var engine = _this.getEngine();
  79685. _this._onVREnabled = function (success) { if (success) {
  79686. _this.initControllers();
  79687. } };
  79688. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  79689. engine.initWebVR().add(function (event) {
  79690. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  79691. return;
  79692. }
  79693. _this._vrDevice = event.vrDisplay;
  79694. //reset the rig parameters.
  79695. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  79696. if (_this._attached) {
  79697. _this.getEngine().enableVR();
  79698. }
  79699. });
  79700. if (typeof (VRFrameData) !== "undefined")
  79701. _this._frameData = new VRFrameData();
  79702. /**
  79703. * The idea behind the following lines:
  79704. * objects that have the camera as parent should actually have the rig cameras as a parent.
  79705. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  79706. * the second will not show it correctly.
  79707. *
  79708. * To solve this - each object that has the camera as parent will be added to a protected array.
  79709. * When the rig camera renders, it will take this array and set all of those to be its children.
  79710. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  79711. * Amazing!
  79712. */
  79713. scene.onBeforeCameraRenderObservable.add(function (camera) {
  79714. if (camera.parent === _this && _this.rigParenting) {
  79715. _this._descendants = _this.getDescendants(true, function (n) {
  79716. // don't take the cameras or the controllers!
  79717. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  79718. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  79719. return !isController && !isRigCamera;
  79720. });
  79721. _this._descendants.forEach(function (node) {
  79722. node.parent = camera;
  79723. });
  79724. }
  79725. });
  79726. scene.onAfterCameraRenderObservable.add(function (camera) {
  79727. if (camera.parent === _this && _this.rigParenting) {
  79728. _this._descendants.forEach(function (node) {
  79729. node.parent = _this;
  79730. });
  79731. }
  79732. });
  79733. return _this;
  79734. }
  79735. /**
  79736. * Gets the device distance from the ground in meters.
  79737. * @returns the distance in meters from the vrDevice to ground in device space. If standing matrix is not supported for the vrDevice 0 is returned.
  79738. */
  79739. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  79740. if (this._standingMatrix) {
  79741. // Add standing matrix offset to get real offset from ground in room
  79742. this._standingMatrix.getTranslationToRef(this._workingVector);
  79743. return this._deviceRoomPosition.y + this._workingVector.y;
  79744. }
  79745. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  79746. return this._defaultHeight || 0;
  79747. };
  79748. /**
  79749. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  79750. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  79751. */
  79752. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  79753. var _this = this;
  79754. if (callback === void 0) { callback = function (bool) { }; }
  79755. // Use standing matrix if available
  79756. this.getEngine().initWebVRAsync().then(function (result) {
  79757. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  79758. callback(false);
  79759. }
  79760. else {
  79761. _this._standingMatrix = new BABYLON.Matrix();
  79762. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  79763. if (!_this.getScene().useRightHandedSystem) {
  79764. [2, 6, 8, 9, 14].forEach(function (num) {
  79765. if (_this._standingMatrix) {
  79766. _this._standingMatrix.m[num] *= -1;
  79767. }
  79768. });
  79769. }
  79770. callback(true);
  79771. }
  79772. });
  79773. };
  79774. /**
  79775. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  79776. * @returns A promise with a boolean set to if the standing matrix is supported.
  79777. */
  79778. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  79779. var _this = this;
  79780. return new Promise(function (res, rej) {
  79781. _this.useStandingMatrix(function (supported) {
  79782. res(supported);
  79783. });
  79784. });
  79785. };
  79786. /**
  79787. * Disposes the camera
  79788. */
  79789. WebVRFreeCamera.prototype.dispose = function () {
  79790. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  79791. _super.prototype.dispose.call(this);
  79792. };
  79793. /**
  79794. * Gets a vrController by name.
  79795. * @param name The name of the controller to retreive
  79796. * @returns the controller matching the name specified or null if not found
  79797. */
  79798. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  79799. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  79800. var gp = _a[_i];
  79801. if (gp.hand === name) {
  79802. return gp;
  79803. }
  79804. }
  79805. return null;
  79806. };
  79807. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  79808. /**
  79809. * The controller corrisponding to the users left hand.
  79810. */
  79811. get: function () {
  79812. if (!this._leftController) {
  79813. this._leftController = this.getControllerByName("left");
  79814. }
  79815. return this._leftController;
  79816. },
  79817. enumerable: true,
  79818. configurable: true
  79819. });
  79820. ;
  79821. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  79822. /**
  79823. * The controller corrisponding to the users right hand.
  79824. */
  79825. get: function () {
  79826. if (!this._rightController) {
  79827. this._rightController = this.getControllerByName("right");
  79828. }
  79829. return this._rightController;
  79830. },
  79831. enumerable: true,
  79832. configurable: true
  79833. });
  79834. ;
  79835. /**
  79836. * Casts a ray forward from the vrCamera's gaze.
  79837. * @param length Length of the ray (default: 100)
  79838. * @returns the ray corrisponding to the gaze
  79839. */
  79840. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  79841. if (length === void 0) { length = 100; }
  79842. if (this.leftCamera) {
  79843. // Use left eye to avoid computation to compute center on every call
  79844. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  79845. }
  79846. else {
  79847. return _super.prototype.getForwardRay.call(this, length);
  79848. }
  79849. };
  79850. /**
  79851. * Updates the camera based on device's frame data
  79852. */
  79853. WebVRFreeCamera.prototype._checkInputs = function () {
  79854. if (this._vrDevice && this._vrDevice.isPresenting) {
  79855. this._vrDevice.getFrameData(this._frameData);
  79856. this.updateFromDevice(this._frameData.pose);
  79857. }
  79858. _super.prototype._checkInputs.call(this);
  79859. };
  79860. /**
  79861. * Updates the poseControlled values based on the input device pose.
  79862. * @param poseData Pose coming from the device
  79863. */
  79864. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  79865. if (poseData && poseData.orientation) {
  79866. this.rawPose = poseData;
  79867. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  79868. if (this.getScene().useRightHandedSystem) {
  79869. this._deviceRoomRotationQuaternion.z *= -1;
  79870. this._deviceRoomRotationQuaternion.w *= -1;
  79871. }
  79872. if (this.webVROptions.trackPosition && this.rawPose.position) {
  79873. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  79874. if (this.getScene().useRightHandedSystem) {
  79875. this._deviceRoomPosition.z *= -1;
  79876. }
  79877. }
  79878. }
  79879. };
  79880. /**
  79881. * WebVR's attach control will start broadcasting frames to the device.
  79882. * Note that in certain browsers (chrome for example) this function must be called
  79883. * within a user-interaction callback. Example:
  79884. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  79885. *
  79886. * @param element html element to attach the vrDevice to
  79887. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  79888. */
  79889. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  79890. _super.prototype.attachControl.call(this, element, noPreventDefault);
  79891. this._attached = true;
  79892. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  79893. if (this._vrDevice) {
  79894. this.getEngine().enableVR();
  79895. }
  79896. };
  79897. /**
  79898. * Detaches the camera from the html element and disables VR
  79899. *
  79900. * @param element html element to detach from
  79901. */
  79902. WebVRFreeCamera.prototype.detachControl = function (element) {
  79903. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  79904. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  79905. _super.prototype.detachControl.call(this, element);
  79906. this._attached = false;
  79907. this.getEngine().disableVR();
  79908. };
  79909. /**
  79910. * @returns the name of this class
  79911. */
  79912. WebVRFreeCamera.prototype.getClassName = function () {
  79913. return "WebVRFreeCamera";
  79914. };
  79915. /**
  79916. * Calls resetPose on the vrDisplay
  79917. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  79918. */
  79919. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  79920. //uses the vrDisplay's "resetPose()".
  79921. //pitch and roll won't be affected.
  79922. this._vrDevice.resetPose();
  79923. };
  79924. /**
  79925. * Updates the rig cameras (left and right eye)
  79926. */
  79927. WebVRFreeCamera.prototype._updateRigCameras = function () {
  79928. var camLeft = this._rigCameras[0];
  79929. var camRight = this._rigCameras[1];
  79930. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  79931. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  79932. camLeft.position.copyFrom(this._deviceRoomPosition);
  79933. camRight.position.copyFrom(this._deviceRoomPosition);
  79934. };
  79935. /**
  79936. * Updates the cached values of the camera
  79937. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  79938. */
  79939. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  79940. var _this = this;
  79941. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  79942. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  79943. if (!this.updateCacheCalled) {
  79944. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  79945. this.updateCacheCalled = true;
  79946. this.update();
  79947. }
  79948. // Set working vector to the device position in room space rotated by the new rotation
  79949. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  79950. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  79951. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  79952. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  79953. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  79954. // Add translation from anchor position
  79955. this._deviceToWorld.getTranslationToRef(this._workingVector);
  79956. this._workingVector.addInPlace(this.position);
  79957. this._workingVector.subtractInPlace(this._cache.position);
  79958. this._deviceToWorld.setTranslation(this._workingVector);
  79959. // Set an inverted matrix to be used when updating the camera
  79960. this._deviceToWorld.invertToRef(this._worldToDevice);
  79961. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  79962. this.controllers.forEach(function (controller) {
  79963. controller._deviceToWorld = _this._deviceToWorld;
  79964. controller.update();
  79965. });
  79966. }
  79967. if (!ignoreParentClass) {
  79968. _super.prototype._updateCache.call(this);
  79969. }
  79970. this.updateCacheCalled = false;
  79971. };
  79972. /**
  79973. * Updates the current device position and rotation in the babylon world
  79974. */
  79975. WebVRFreeCamera.prototype.update = function () {
  79976. // Get current device position in babylon world
  79977. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  79978. // Get current device rotation in babylon world
  79979. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  79980. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  79981. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  79982. _super.prototype.update.call(this);
  79983. };
  79984. /**
  79985. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  79986. * @returns an identity matrix
  79987. */
  79988. WebVRFreeCamera.prototype._getViewMatrix = function () {
  79989. return BABYLON.Matrix.Identity();
  79990. };
  79991. /**
  79992. * This function is called by the two RIG cameras.
  79993. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  79994. */
  79995. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  79996. var _this = this;
  79997. //WebVR 1.1
  79998. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  79999. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  80000. if (!this.getScene().useRightHandedSystem) {
  80001. [2, 6, 8, 9, 14].forEach(function (num) {
  80002. _this._webvrViewMatrix.m[num] *= -1;
  80003. });
  80004. }
  80005. // update the camera rotation matrix
  80006. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  80007. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  80008. // Computing target and final matrix
  80009. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  80010. var parentCamera = this._cameraRigParams["parentCamera"];
  80011. // should the view matrix be updated with scale and position offset?
  80012. if (parentCamera.deviceScaleFactor !== 1) {
  80013. this._webvrViewMatrix.invert();
  80014. // scale the position, if set
  80015. if (parentCamera.deviceScaleFactor) {
  80016. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  80017. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  80018. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  80019. }
  80020. this._webvrViewMatrix.invert();
  80021. }
  80022. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  80023. return this._webvrViewMatrix;
  80024. };
  80025. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  80026. var _this = this;
  80027. var parentCamera = this.parent;
  80028. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  80029. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  80030. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  80031. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  80032. //babylon compatible matrix
  80033. if (!this.getScene().useRightHandedSystem) {
  80034. [8, 9, 10, 11].forEach(function (num) {
  80035. _this._projectionMatrix.m[num] *= -1;
  80036. });
  80037. }
  80038. return this._projectionMatrix;
  80039. };
  80040. /**
  80041. * Initializes the controllers and their meshes
  80042. */
  80043. WebVRFreeCamera.prototype.initControllers = function () {
  80044. var _this = this;
  80045. this.controllers = [];
  80046. var manager = this.getScene().gamepadManager;
  80047. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  80048. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  80049. var webVrController = gamepad;
  80050. if (webVrController.defaultModel) {
  80051. webVrController.defaultModel.setEnabled(false);
  80052. }
  80053. if (webVrController.hand === "right") {
  80054. _this._rightController = null;
  80055. }
  80056. if (webVrController.hand === "left") {
  80057. _this._rightController = null;
  80058. }
  80059. var controllerIndex = _this.controllers.indexOf(webVrController);
  80060. if (controllerIndex !== -1) {
  80061. _this.controllers.splice(controllerIndex, 1);
  80062. }
  80063. }
  80064. });
  80065. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  80066. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  80067. var webVrController_1 = gamepad;
  80068. webVrController_1._deviceToWorld = _this._deviceToWorld;
  80069. if (_this.webVROptions.controllerMeshes) {
  80070. if (webVrController_1.defaultModel) {
  80071. webVrController_1.defaultModel.setEnabled(true);
  80072. }
  80073. else {
  80074. // Load the meshes
  80075. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  80076. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  80077. if (_this.webVROptions.defaultLightingOnControllers) {
  80078. if (!_this._lightOnControllers) {
  80079. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  80080. }
  80081. var activateLightOnSubMeshes_1 = function (mesh, light) {
  80082. var children = mesh.getChildren();
  80083. if (children.length !== 0) {
  80084. children.forEach(function (mesh) {
  80085. light.includedOnlyMeshes.push(mesh);
  80086. activateLightOnSubMeshes_1(mesh, light);
  80087. });
  80088. }
  80089. };
  80090. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  80091. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  80092. }
  80093. });
  80094. }
  80095. }
  80096. webVrController_1.attachToPoseControlledCamera(_this);
  80097. // since this is async - sanity check. Is the controller already stored?
  80098. if (_this.controllers.indexOf(webVrController_1) === -1) {
  80099. //add to the controllers array
  80100. _this.controllers.push(webVrController_1);
  80101. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  80102. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  80103. // So we're overriding setting left & right manually to be sure
  80104. var firstViveWandDetected = false;
  80105. for (var i = 0; i < _this.controllers.length; i++) {
  80106. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  80107. if (!firstViveWandDetected) {
  80108. firstViveWandDetected = true;
  80109. _this.controllers[i].hand = "left";
  80110. }
  80111. else {
  80112. _this.controllers[i].hand = "right";
  80113. }
  80114. }
  80115. }
  80116. //did we find enough controllers? Great! let the developer know.
  80117. if (_this.controllers.length >= 2) {
  80118. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  80119. }
  80120. }
  80121. }
  80122. });
  80123. };
  80124. return WebVRFreeCamera;
  80125. }(BABYLON.FreeCamera));
  80126. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  80127. })(BABYLON || (BABYLON = {}));
  80128. //# sourceMappingURL=babylon.webVRCamera.js.map
  80129. var BABYLON;
  80130. (function (BABYLON) {
  80131. // We're mainly based on the logic defined into the FreeCamera code
  80132. /**
  80133. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  80134. * being tilted forward or back and left or right.
  80135. */
  80136. var DeviceOrientationCamera = /** @class */ (function (_super) {
  80137. __extends(DeviceOrientationCamera, _super);
  80138. /**
  80139. * Creates a new device orientation camera. @see DeviceOrientationCamera
  80140. * @param name The name of the camera
  80141. * @param position The start position camera
  80142. * @param scene The scene the camera belongs to
  80143. */
  80144. function DeviceOrientationCamera(name, position, scene) {
  80145. var _this = _super.call(this, name, position, scene) || this;
  80146. _this._quaternionCache = new BABYLON.Quaternion();
  80147. _this.inputs.addDeviceOrientation();
  80148. return _this;
  80149. }
  80150. /**
  80151. * Gets the current instance class name ("DeviceOrientationCamera").
  80152. * This helps avoiding instanceof at run time.
  80153. * @returns the class name
  80154. */
  80155. DeviceOrientationCamera.prototype.getClassName = function () {
  80156. return "DeviceOrientationCamera";
  80157. };
  80158. /**
  80159. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  80160. */
  80161. DeviceOrientationCamera.prototype._checkInputs = function () {
  80162. _super.prototype._checkInputs.call(this);
  80163. this._quaternionCache.copyFrom(this.rotationQuaternion);
  80164. if (this._initialQuaternion) {
  80165. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  80166. }
  80167. };
  80168. /**
  80169. * Reset the camera to its default orientation on the specified axis only.
  80170. * @param axis The axis to reset
  80171. */
  80172. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  80173. var _this = this;
  80174. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  80175. //can only work if this camera has a rotation quaternion already.
  80176. if (!this.rotationQuaternion)
  80177. return;
  80178. if (!this._initialQuaternion) {
  80179. this._initialQuaternion = new BABYLON.Quaternion();
  80180. }
  80181. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  80182. ['x', 'y', 'z'].forEach(function (axisName) {
  80183. if (!axis[axisName]) {
  80184. _this._initialQuaternion[axisName] = 0;
  80185. }
  80186. else {
  80187. _this._initialQuaternion[axisName] *= -1;
  80188. }
  80189. });
  80190. this._initialQuaternion.normalize();
  80191. //force rotation update
  80192. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  80193. };
  80194. return DeviceOrientationCamera;
  80195. }(BABYLON.FreeCamera));
  80196. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  80197. })(BABYLON || (BABYLON = {}));
  80198. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  80199. var BABYLON;
  80200. (function (BABYLON) {
  80201. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  80202. __extends(VRDeviceOrientationFreeCamera, _super);
  80203. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  80204. if (compensateDistortion === void 0) { compensateDistortion = true; }
  80205. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  80206. var _this = _super.call(this, name, position, scene) || this;
  80207. vrCameraMetrics.compensateDistortion = compensateDistortion;
  80208. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  80209. return _this;
  80210. }
  80211. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  80212. return "VRDeviceOrientationFreeCamera";
  80213. };
  80214. return VRDeviceOrientationFreeCamera;
  80215. }(BABYLON.DeviceOrientationCamera));
  80216. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  80217. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  80218. __extends(VRDeviceOrientationGamepadCamera, _super);
  80219. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  80220. if (compensateDistortion === void 0) { compensateDistortion = true; }
  80221. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  80222. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  80223. _this.inputs.addGamepad();
  80224. return _this;
  80225. }
  80226. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  80227. return "VRDeviceOrientationGamepadCamera";
  80228. };
  80229. return VRDeviceOrientationGamepadCamera;
  80230. }(VRDeviceOrientationFreeCamera));
  80231. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  80232. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  80233. __extends(VRDeviceOrientationArcRotateCamera, _super);
  80234. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  80235. if (compensateDistortion === void 0) { compensateDistortion = true; }
  80236. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  80237. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  80238. vrCameraMetrics.compensateDistortion = compensateDistortion;
  80239. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  80240. _this.inputs.addVRDeviceOrientation();
  80241. return _this;
  80242. }
  80243. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  80244. return "VRDeviceOrientationArcRotateCamera";
  80245. };
  80246. return VRDeviceOrientationArcRotateCamera;
  80247. }(BABYLON.ArcRotateCamera));
  80248. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  80249. })(BABYLON || (BABYLON = {}));
  80250. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  80251. var BABYLON;
  80252. (function (BABYLON) {
  80253. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  80254. __extends(AnaglyphFreeCamera, _super);
  80255. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  80256. var _this = _super.call(this, name, position, scene) || this;
  80257. _this.interaxialDistance = interaxialDistance;
  80258. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  80259. return _this;
  80260. }
  80261. AnaglyphFreeCamera.prototype.getClassName = function () {
  80262. return "AnaglyphFreeCamera";
  80263. };
  80264. return AnaglyphFreeCamera;
  80265. }(BABYLON.FreeCamera));
  80266. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  80267. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  80268. __extends(AnaglyphArcRotateCamera, _super);
  80269. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  80270. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  80271. _this.interaxialDistance = interaxialDistance;
  80272. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  80273. return _this;
  80274. }
  80275. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  80276. return "AnaglyphArcRotateCamera";
  80277. };
  80278. return AnaglyphArcRotateCamera;
  80279. }(BABYLON.ArcRotateCamera));
  80280. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  80281. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  80282. __extends(AnaglyphGamepadCamera, _super);
  80283. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  80284. var _this = _super.call(this, name, position, scene) || this;
  80285. _this.interaxialDistance = interaxialDistance;
  80286. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  80287. return _this;
  80288. }
  80289. AnaglyphGamepadCamera.prototype.getClassName = function () {
  80290. return "AnaglyphGamepadCamera";
  80291. };
  80292. return AnaglyphGamepadCamera;
  80293. }(BABYLON.GamepadCamera));
  80294. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  80295. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  80296. __extends(AnaglyphUniversalCamera, _super);
  80297. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  80298. var _this = _super.call(this, name, position, scene) || this;
  80299. _this.interaxialDistance = interaxialDistance;
  80300. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  80301. return _this;
  80302. }
  80303. AnaglyphUniversalCamera.prototype.getClassName = function () {
  80304. return "AnaglyphUniversalCamera";
  80305. };
  80306. return AnaglyphUniversalCamera;
  80307. }(BABYLON.UniversalCamera));
  80308. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  80309. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  80310. __extends(StereoscopicFreeCamera, _super);
  80311. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  80312. var _this = _super.call(this, name, position, scene) || this;
  80313. _this.interaxialDistance = interaxialDistance;
  80314. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  80315. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  80316. return _this;
  80317. }
  80318. StereoscopicFreeCamera.prototype.getClassName = function () {
  80319. return "StereoscopicFreeCamera";
  80320. };
  80321. return StereoscopicFreeCamera;
  80322. }(BABYLON.FreeCamera));
  80323. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  80324. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  80325. __extends(StereoscopicArcRotateCamera, _super);
  80326. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  80327. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  80328. _this.interaxialDistance = interaxialDistance;
  80329. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  80330. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  80331. return _this;
  80332. }
  80333. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  80334. return "StereoscopicArcRotateCamera";
  80335. };
  80336. return StereoscopicArcRotateCamera;
  80337. }(BABYLON.ArcRotateCamera));
  80338. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  80339. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  80340. __extends(StereoscopicGamepadCamera, _super);
  80341. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  80342. var _this = _super.call(this, name, position, scene) || this;
  80343. _this.interaxialDistance = interaxialDistance;
  80344. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  80345. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  80346. return _this;
  80347. }
  80348. StereoscopicGamepadCamera.prototype.getClassName = function () {
  80349. return "StereoscopicGamepadCamera";
  80350. };
  80351. return StereoscopicGamepadCamera;
  80352. }(BABYLON.GamepadCamera));
  80353. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  80354. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  80355. __extends(StereoscopicUniversalCamera, _super);
  80356. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  80357. var _this = _super.call(this, name, position, scene) || this;
  80358. _this.interaxialDistance = interaxialDistance;
  80359. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  80360. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  80361. return _this;
  80362. }
  80363. StereoscopicUniversalCamera.prototype.getClassName = function () {
  80364. return "StereoscopicUniversalCamera";
  80365. };
  80366. return StereoscopicUniversalCamera;
  80367. }(BABYLON.UniversalCamera));
  80368. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  80369. })(BABYLON || (BABYLON = {}));
  80370. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  80371. var BABYLON;
  80372. (function (BABYLON) {
  80373. var VRExperienceHelperGazer = /** @class */ (function () {
  80374. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  80375. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  80376. this.scene = scene;
  80377. this._pointerDownOnMeshAsked = false;
  80378. this._isActionableMesh = false;
  80379. this._teleportationRequestInitiated = false;
  80380. this._teleportationBackRequestInitiated = false;
  80381. this._dpadPressed = true;
  80382. this._activePointer = false;
  80383. this._id = VRExperienceHelperGazer._idCounter++;
  80384. // Gaze tracker
  80385. if (!gazeTrackerToClone) {
  80386. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  80387. this._gazeTracker.bakeCurrentTransformIntoVertices();
  80388. this._gazeTracker.isPickable = false;
  80389. this._gazeTracker.isVisible = false;
  80390. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  80391. targetMat.specularColor = BABYLON.Color3.Black();
  80392. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  80393. targetMat.backFaceCulling = false;
  80394. this._gazeTracker.material = targetMat;
  80395. }
  80396. else {
  80397. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  80398. }
  80399. }
  80400. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  80401. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  80402. };
  80403. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  80404. this._pointerDownOnMeshAsked = true;
  80405. if (this._currentMeshSelected && this._currentHit) {
  80406. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  80407. }
  80408. };
  80409. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  80410. if (this._currentMeshSelected && this._currentHit) {
  80411. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  80412. }
  80413. this._pointerDownOnMeshAsked = false;
  80414. };
  80415. VRExperienceHelperGazer.prototype._activatePointer = function () {
  80416. this._activePointer = true;
  80417. };
  80418. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  80419. this._activePointer = false;
  80420. };
  80421. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  80422. };
  80423. VRExperienceHelperGazer.prototype.dispose = function () {
  80424. this._interactionsEnabled = false;
  80425. this._teleportationEnabled = false;
  80426. };
  80427. VRExperienceHelperGazer._idCounter = 0;
  80428. return VRExperienceHelperGazer;
  80429. }());
  80430. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  80431. __extends(VRExperienceHelperControllerGazer, _super);
  80432. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  80433. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  80434. _this.webVRController = webVRController;
  80435. // Laser pointer
  80436. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  80437. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  80438. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  80439. laserPointerMaterial.alpha = 0.6;
  80440. _this._laserPointer.material = laserPointerMaterial;
  80441. _this._laserPointer.rotation.x = Math.PI / 2;
  80442. _this._laserPointer.position.z = -0.5;
  80443. _this._laserPointer.isVisible = false;
  80444. _this._laserPointer.parent = webVRController.mesh;
  80445. return _this;
  80446. }
  80447. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  80448. return this.webVRController.getForwardRay(length);
  80449. };
  80450. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  80451. _super.prototype._activatePointer.call(this);
  80452. this._laserPointer.isVisible = true;
  80453. };
  80454. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  80455. _super.prototype._deactivatePointer.call(this);
  80456. this._laserPointer.isVisible = false;
  80457. };
  80458. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  80459. this._laserPointer.material.emissiveColor = color;
  80460. };
  80461. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  80462. this._laserPointer.parent = mesh;
  80463. };
  80464. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  80465. this._laserPointer.scaling.y = distance;
  80466. this._laserPointer.position.z = -distance / 2;
  80467. };
  80468. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  80469. _super.prototype.dispose.call(this);
  80470. this._laserPointer.dispose();
  80471. };
  80472. return VRExperienceHelperControllerGazer;
  80473. }(VRExperienceHelperGazer));
  80474. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  80475. __extends(VRExperienceHelperCameraGazer, _super);
  80476. function VRExperienceHelperCameraGazer(getCamera, scene) {
  80477. var _this = _super.call(this, scene) || this;
  80478. _this.getCamera = getCamera;
  80479. return _this;
  80480. }
  80481. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  80482. var camera = this.getCamera();
  80483. if (camera) {
  80484. return camera.getForwardRay(length);
  80485. }
  80486. else {
  80487. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  80488. }
  80489. };
  80490. return VRExperienceHelperCameraGazer;
  80491. }(VRExperienceHelperGazer));
  80492. /**
  80493. * Helps to quickly add VR support to an existing scene.
  80494. * See http://doc.babylonjs.com/how_to/webvr_helper
  80495. */
  80496. var VRExperienceHelper = /** @class */ (function () {
  80497. /**
  80498. * Instantiates a VRExperienceHelper.
  80499. * Helps to quickly add VR support to an existing scene.
  80500. * @param scene The scene the VRExperienceHelper belongs to.
  80501. * @param webVROptions Options to modify the vr experience helper's behavior.
  80502. */
  80503. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  80504. if (webVROptions === void 0) { webVROptions = {}; }
  80505. var _this = this;
  80506. this.webVROptions = webVROptions;
  80507. // Can the system support WebVR, even if a headset isn't plugged in?
  80508. this._webVRsupported = false;
  80509. // If WebVR is supported, is a headset plugged in and are we ready to present?
  80510. this._webVRready = false;
  80511. // Are we waiting for the requestPresent callback to complete?
  80512. this._webVRrequesting = false;
  80513. // Are we presenting to the headset right now?
  80514. this._webVRpresenting = false;
  80515. // Are we presenting in the fullscreen fallback?
  80516. this._fullscreenVRpresenting = false;
  80517. /**
  80518. * Observable raised when entering VR.
  80519. */
  80520. this.onEnteringVRObservable = new BABYLON.Observable();
  80521. /**
  80522. * Observable raised when exiting VR.
  80523. */
  80524. this.onExitingVRObservable = new BABYLON.Observable();
  80525. /**
  80526. * Observable raised when controller mesh is loaded.
  80527. */
  80528. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  80529. this._useCustomVRButton = false;
  80530. this._teleportationRequested = false;
  80531. this._teleportActive = false;
  80532. this._floorMeshesCollection = [];
  80533. this._rotationAllowed = true;
  80534. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  80535. this._rotationRightAsked = false;
  80536. this._rotationLeftAsked = false;
  80537. this._isDefaultTeleportationTarget = true;
  80538. this._teleportationFillColor = "#444444";
  80539. this._teleportationBorderColor = "#FFFFFF";
  80540. this._rotationAngle = 0;
  80541. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  80542. this._padSensibilityUp = 0.65;
  80543. this._padSensibilityDown = 0.35;
  80544. this.leftController = null;
  80545. this.rightController = null;
  80546. /**
  80547. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  80548. */
  80549. this.onNewMeshSelected = new BABYLON.Observable();
  80550. /**
  80551. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  80552. */
  80553. this.onNewMeshPicked = new BABYLON.Observable();
  80554. /**
  80555. * Observable raised before camera teleportation
  80556. */
  80557. this.onBeforeCameraTeleport = new BABYLON.Observable();
  80558. /**
  80559. * Observable raised after camera teleportation
  80560. */
  80561. this.onAfterCameraTeleport = new BABYLON.Observable();
  80562. /**
  80563. * Observable raised when current selected mesh gets unselected
  80564. */
  80565. this.onSelectedMeshUnselected = new BABYLON.Observable();
  80566. /**
  80567. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  80568. */
  80569. this.teleportationEnabled = true;
  80570. this._teleportationInitialized = false;
  80571. this._interactionsEnabled = false;
  80572. this._interactionsRequested = false;
  80573. this._displayGaze = true;
  80574. this._displayLaserPointer = true;
  80575. this._onResize = function () {
  80576. _this.moveButtonToBottomRight();
  80577. if (_this._fullscreenVRpresenting && _this._webVRready) {
  80578. _this.exitVR();
  80579. }
  80580. };
  80581. this._onFullscreenChange = function () {
  80582. if (document.fullscreen !== undefined) {
  80583. _this._fullscreenVRpresenting = document.fullscreen;
  80584. }
  80585. else if (document.mozFullScreen !== undefined) {
  80586. _this._fullscreenVRpresenting = document.mozFullScreen;
  80587. }
  80588. else if (document.webkitIsFullScreen !== undefined) {
  80589. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  80590. }
  80591. else if (document.msIsFullScreen !== undefined) {
  80592. _this._fullscreenVRpresenting = document.msIsFullScreen;
  80593. }
  80594. if (!_this._fullscreenVRpresenting && _this._canvas) {
  80595. _this.exitVR();
  80596. if (!_this._useCustomVRButton) {
  80597. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  80598. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  80599. }
  80600. }
  80601. };
  80602. this.beforeRender = function () {
  80603. if (_this.leftController && _this.leftController._activePointer) {
  80604. _this._castRayAndSelectObject(_this.leftController);
  80605. }
  80606. if (_this.rightController && _this.rightController._activePointer) {
  80607. _this._castRayAndSelectObject(_this.rightController);
  80608. }
  80609. if (!(_this.leftController && _this.leftController._activePointer) && !(_this.rightController && _this.rightController._activePointer)) {
  80610. _this._castRayAndSelectObject(_this._cameraGazer);
  80611. }
  80612. else {
  80613. _this._cameraGazer._gazeTracker.isVisible = false;
  80614. }
  80615. };
  80616. this._onNewGamepadConnected = function (gamepad) {
  80617. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  80618. if (gamepad.leftStick) {
  80619. gamepad.onleftstickchanged(function (stickValues) {
  80620. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  80621. // Listening to classic/xbox gamepad only if no VR controller is active
  80622. if ((!_this.leftController && !_this.rightController) ||
  80623. ((_this.leftController && !_this.leftController._activePointer) &&
  80624. (_this.rightController && !_this.rightController._activePointer))) {
  80625. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  80626. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  80627. }
  80628. }
  80629. });
  80630. }
  80631. if (gamepad.rightStick) {
  80632. gamepad.onrightstickchanged(function (stickValues) {
  80633. if (_this._teleportationInitialized) {
  80634. _this._checkRotate(stickValues, _this._cameraGazer);
  80635. }
  80636. });
  80637. }
  80638. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  80639. gamepad.onbuttondown(function (buttonPressed) {
  80640. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  80641. _this._cameraGazer._selectionPointerDown();
  80642. }
  80643. });
  80644. gamepad.onbuttonup(function (buttonPressed) {
  80645. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  80646. _this._cameraGazer._selectionPointerUp();
  80647. }
  80648. });
  80649. }
  80650. }
  80651. else {
  80652. var webVRController = gamepad;
  80653. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  80654. if (webVRController.hand === "right" || (_this.leftController && _this.leftController.webVRController != webVRController)) {
  80655. _this.rightController = controller;
  80656. }
  80657. else {
  80658. _this.leftController = controller;
  80659. }
  80660. _this._tryEnableInteractionOnController(controller);
  80661. }
  80662. };
  80663. // This only succeeds if the controller's mesh exists for the controller so this must be called whenever new controller is connected or when mesh is loaded
  80664. this._tryEnableInteractionOnController = function (controller) {
  80665. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  80666. _this._enableInteractionOnController(controller);
  80667. }
  80668. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  80669. _this._enableTeleportationOnController(controller);
  80670. }
  80671. };
  80672. this._onNewGamepadDisconnected = function (gamepad) {
  80673. if (gamepad instanceof BABYLON.WebVRController) {
  80674. if (gamepad.hand === "left" && _this.leftController != null) {
  80675. _this.leftController.dispose();
  80676. _this.leftController = null;
  80677. }
  80678. if (gamepad.hand === "right" && _this.rightController != null) {
  80679. _this.rightController.dispose();
  80680. _this.rightController = null;
  80681. }
  80682. }
  80683. };
  80684. this._workingVector = BABYLON.Vector3.Zero();
  80685. this._workingQuaternion = BABYLON.Quaternion.Identity();
  80686. this._workingMatrix = BABYLON.Matrix.Identity();
  80687. this._scene = scene;
  80688. this._canvas = scene.getEngine().getRenderingCanvas();
  80689. // Parse options
  80690. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  80691. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  80692. }
  80693. if (webVROptions.createDeviceOrientationCamera === undefined) {
  80694. webVROptions.createDeviceOrientationCamera = true;
  80695. }
  80696. if (webVROptions.defaultHeight === undefined) {
  80697. webVROptions.defaultHeight = 1.7;
  80698. }
  80699. if (webVROptions.useCustomVRButton) {
  80700. this._useCustomVRButton = true;
  80701. if (webVROptions.customVRButton) {
  80702. this._btnVR = webVROptions.customVRButton;
  80703. }
  80704. }
  80705. if (webVROptions.rayLength) {
  80706. this._rayLength = webVROptions.rayLength;
  80707. }
  80708. this._defaultHeight = webVROptions.defaultHeight;
  80709. // Set position
  80710. if (this._scene.activeCamera) {
  80711. this._position = this._scene.activeCamera.position.clone();
  80712. }
  80713. else {
  80714. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  80715. }
  80716. // Set non-vr camera
  80717. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  80718. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  80719. // Copy data from existing camera
  80720. if (this._scene.activeCamera) {
  80721. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  80722. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  80723. // Set rotation from previous camera
  80724. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  80725. var targetCamera = this._scene.activeCamera;
  80726. if (targetCamera.rotationQuaternion) {
  80727. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  80728. }
  80729. else {
  80730. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  80731. }
  80732. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  80733. }
  80734. }
  80735. this._scene.activeCamera = this._deviceOrientationCamera;
  80736. if (this._canvas) {
  80737. this._scene.activeCamera.attachControl(this._canvas);
  80738. }
  80739. }
  80740. else {
  80741. this._existingCamera = this._scene.activeCamera;
  80742. }
  80743. // Create VR cameras
  80744. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  80745. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  80746. }
  80747. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  80748. this._webVRCamera.useStandingMatrix();
  80749. // Create default button
  80750. if (!this._useCustomVRButton) {
  80751. this._btnVR = document.createElement("BUTTON");
  80752. this._btnVR.className = "babylonVRicon";
  80753. this._btnVR.id = "babylonVRiconbtn";
  80754. this._btnVR.title = "Click to switch to VR";
  80755. 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) }";
  80756. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  80757. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  80758. // css += ".babylonVRicon.vrdisplaysupported { }";
  80759. // css += ".babylonVRicon.vrdisplayready { }";
  80760. // css += ".babylonVRicon.vrdisplayrequesting { }";
  80761. var style = document.createElement('style');
  80762. style.appendChild(document.createTextNode(css));
  80763. document.getElementsByTagName('head')[0].appendChild(style);
  80764. this.moveButtonToBottomRight();
  80765. }
  80766. // VR button click event
  80767. if (this._btnVR) {
  80768. this._btnVR.addEventListener("click", function () {
  80769. if (!_this.isInVRMode) {
  80770. _this.enterVR();
  80771. }
  80772. else {
  80773. _this.exitVR();
  80774. }
  80775. });
  80776. }
  80777. // Window events
  80778. window.addEventListener("resize", this._onResize);
  80779. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  80780. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  80781. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  80782. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  80783. // Display vr button when headset is connected
  80784. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  80785. this.displayVRButton();
  80786. }
  80787. else {
  80788. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  80789. if (e.vrDisplay) {
  80790. _this.displayVRButton();
  80791. }
  80792. });
  80793. }
  80794. // Exiting VR mode using 'ESC' key on desktop
  80795. this._onKeyDown = function (event) {
  80796. if (event.keyCode === 27 && _this.isInVRMode) {
  80797. _this.exitVR();
  80798. }
  80799. };
  80800. document.addEventListener("keydown", this._onKeyDown);
  80801. // Exiting VR mode double tapping the touch screen
  80802. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  80803. if (_this.isInVRMode) {
  80804. _this.exitVR();
  80805. if (_this._fullscreenVRpresenting) {
  80806. _this._scene.getEngine().switchFullscreen(true);
  80807. }
  80808. }
  80809. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  80810. // Listen for WebVR display changes
  80811. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  80812. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  80813. this._onVRRequestPresentStart = function () {
  80814. _this._webVRrequesting = true;
  80815. _this.updateButtonVisibility();
  80816. };
  80817. this._onVRRequestPresentComplete = function (success) {
  80818. _this._webVRrequesting = false;
  80819. _this.updateButtonVisibility();
  80820. };
  80821. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  80822. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  80823. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  80824. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  80825. scene.onDisposeObservable.add(function () {
  80826. _this.dispose();
  80827. });
  80828. // Gamepad connection events
  80829. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  80830. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  80831. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  80832. this.updateButtonVisibility();
  80833. //create easing functions
  80834. this._circleEase = new BABYLON.CircleEase();
  80835. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  80836. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  80837. }
  80838. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  80839. /** Return this.onEnteringVRObservable
  80840. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  80841. */
  80842. get: function () {
  80843. return this.onEnteringVRObservable;
  80844. },
  80845. enumerable: true,
  80846. configurable: true
  80847. });
  80848. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  80849. /** Return this.onExitingVRObservable
  80850. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  80851. */
  80852. get: function () {
  80853. return this.onExitingVRObservable;
  80854. },
  80855. enumerable: true,
  80856. configurable: true
  80857. });
  80858. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  80859. /** Return this.onControllerMeshLoadedObservable
  80860. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  80861. */
  80862. get: function () {
  80863. return this.onControllerMeshLoadedObservable;
  80864. },
  80865. enumerable: true,
  80866. configurable: true
  80867. });
  80868. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  80869. /**
  80870. * The mesh used to display where the user is going to teleport.
  80871. */
  80872. get: function () {
  80873. return this._teleportationTarget;
  80874. },
  80875. /**
  80876. * Sets the mesh to be used to display where the user is going to teleport.
  80877. */
  80878. set: function (value) {
  80879. if (value) {
  80880. value.name = "teleportationTarget";
  80881. this._isDefaultTeleportationTarget = false;
  80882. this._teleportationTarget = value;
  80883. }
  80884. },
  80885. enumerable: true,
  80886. configurable: true
  80887. });
  80888. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  80889. /**
  80890. * The mesh used to display where the user is selecting,
  80891. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  80892. * See http://doc.babylonjs.com/resources/baking_transformations
  80893. */
  80894. get: function () {
  80895. return this._cameraGazer._gazeTracker;
  80896. },
  80897. set: function (value) {
  80898. if (value) {
  80899. this._cameraGazer._gazeTracker = value;
  80900. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  80901. this._cameraGazer._gazeTracker.isPickable = false;
  80902. this._cameraGazer._gazeTracker.isVisible = false;
  80903. this._cameraGazer._gazeTracker.name = "gazeTracker";
  80904. if (this.leftController) {
  80905. this.leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  80906. }
  80907. if (this.rightController) {
  80908. this.rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  80909. }
  80910. }
  80911. },
  80912. enumerable: true,
  80913. configurable: true
  80914. });
  80915. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  80916. /**
  80917. * If the ray of the gaze should be displayed.
  80918. */
  80919. get: function () {
  80920. return this._displayGaze;
  80921. },
  80922. /**
  80923. * Sets if the ray of the gaze should be displayed.
  80924. */
  80925. set: function (value) {
  80926. this._displayGaze = value;
  80927. if (!value) {
  80928. this._cameraGazer._gazeTracker.isVisible = false;
  80929. if (this.leftController) {
  80930. this.leftController._gazeTracker.isVisible = false;
  80931. }
  80932. if (this.rightController) {
  80933. this.rightController._gazeTracker.isVisible = false;
  80934. }
  80935. }
  80936. },
  80937. enumerable: true,
  80938. configurable: true
  80939. });
  80940. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  80941. /**
  80942. * If the ray of the LaserPointer should be displayed.
  80943. */
  80944. get: function () {
  80945. return this._displayLaserPointer;
  80946. },
  80947. /**
  80948. * Sets if the ray of the LaserPointer should be displayed.
  80949. */
  80950. set: function (value) {
  80951. this._displayLaserPointer = value;
  80952. if (!value) {
  80953. if (this.rightController) {
  80954. this.rightController._deactivatePointer();
  80955. this.rightController._gazeTracker.isVisible = false;
  80956. }
  80957. if (this.leftController) {
  80958. this.leftController._deactivatePointer();
  80959. this.leftController._gazeTracker.isVisible = false;
  80960. }
  80961. }
  80962. else {
  80963. if (this.rightController) {
  80964. this.rightController._activatePointer();
  80965. }
  80966. else if (this.leftController) {
  80967. this.leftController._activatePointer();
  80968. }
  80969. }
  80970. },
  80971. enumerable: true,
  80972. configurable: true
  80973. });
  80974. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  80975. /**
  80976. * The deviceOrientationCamera used as the camera when not in VR.
  80977. */
  80978. get: function () {
  80979. return this._deviceOrientationCamera;
  80980. },
  80981. enumerable: true,
  80982. configurable: true
  80983. });
  80984. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  80985. /**
  80986. * Based on the current WebVR support, returns the current VR camera used.
  80987. */
  80988. get: function () {
  80989. if (this._webVRready) {
  80990. return this._webVRCamera;
  80991. }
  80992. else {
  80993. return this._scene.activeCamera;
  80994. }
  80995. },
  80996. enumerable: true,
  80997. configurable: true
  80998. });
  80999. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  81000. /**
  81001. * The webVRCamera which is used when in VR.
  81002. */
  81003. get: function () {
  81004. return this._webVRCamera;
  81005. },
  81006. enumerable: true,
  81007. configurable: true
  81008. });
  81009. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  81010. /**
  81011. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  81012. */
  81013. get: function () {
  81014. return this._vrDeviceOrientationCamera;
  81015. },
  81016. enumerable: true,
  81017. configurable: true
  81018. });
  81019. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  81020. get: function () {
  81021. var result = this._cameraGazer._teleportationRequestInitiated
  81022. || (this.leftController !== null && this.leftController._teleportationRequestInitiated)
  81023. || (this.rightController !== null && this.rightController._teleportationRequestInitiated);
  81024. return result;
  81025. },
  81026. enumerable: true,
  81027. configurable: true
  81028. });
  81029. // Raised when one of the controller has loaded successfully its associated default mesh
  81030. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  81031. if (this.leftController && this.leftController.webVRController == webVRController) {
  81032. this._tryEnableInteractionOnController(this.leftController);
  81033. }
  81034. if (this.rightController && this.rightController.webVRController == webVRController) {
  81035. this._tryEnableInteractionOnController(this.rightController);
  81036. }
  81037. try {
  81038. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  81039. }
  81040. catch (err) {
  81041. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  81042. }
  81043. };
  81044. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  81045. /**
  81046. * Gets a value indicating if we are currently in VR mode.
  81047. */
  81048. get: function () {
  81049. return this._webVRpresenting || this._fullscreenVRpresenting;
  81050. },
  81051. enumerable: true,
  81052. configurable: true
  81053. });
  81054. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  81055. var vrDisplay = this._scene.getEngine().getVRDevice();
  81056. if (vrDisplay) {
  81057. var wasPresenting = this._webVRpresenting;
  81058. // A VR display is connected
  81059. this._webVRpresenting = vrDisplay.isPresenting;
  81060. if (wasPresenting && !this._webVRpresenting)
  81061. this.exitVR();
  81062. }
  81063. else {
  81064. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  81065. }
  81066. this.updateButtonVisibility();
  81067. };
  81068. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  81069. this._webVRsupported = eventArgs.vrSupported;
  81070. this._webVRready = !!eventArgs.vrDisplay;
  81071. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  81072. this.updateButtonVisibility();
  81073. };
  81074. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  81075. if (this._canvas && !this._useCustomVRButton) {
  81076. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  81077. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  81078. }
  81079. };
  81080. VRExperienceHelper.prototype.displayVRButton = function () {
  81081. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  81082. document.body.appendChild(this._btnVR);
  81083. this._btnVRDisplayed = true;
  81084. }
  81085. };
  81086. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  81087. if (!this._btnVR || this._useCustomVRButton) {
  81088. return;
  81089. }
  81090. this._btnVR.className = "babylonVRicon";
  81091. if (this.isInVRMode) {
  81092. this._btnVR.className += " vrdisplaypresenting";
  81093. }
  81094. else {
  81095. if (this._webVRready)
  81096. this._btnVR.className += " vrdisplayready";
  81097. if (this._webVRsupported)
  81098. this._btnVR.className += " vrdisplaysupported";
  81099. if (this._webVRrequesting)
  81100. this._btnVR.className += " vrdisplayrequesting";
  81101. }
  81102. };
  81103. /**
  81104. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  81105. * Otherwise, will use the fullscreen API.
  81106. */
  81107. VRExperienceHelper.prototype.enterVR = function () {
  81108. if (this.onEnteringVRObservable) {
  81109. try {
  81110. this.onEnteringVRObservable.notifyObservers(this);
  81111. }
  81112. catch (err) {
  81113. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  81114. }
  81115. }
  81116. if (this._scene.activeCamera) {
  81117. this._position = this._scene.activeCamera.position.clone();
  81118. // make sure that we return to the last active camera
  81119. this._existingCamera = this._scene.activeCamera;
  81120. }
  81121. if (this._webVRrequesting)
  81122. return;
  81123. // If WebVR is supported and a headset is connected
  81124. if (this._webVRready) {
  81125. if (!this._webVRpresenting) {
  81126. this._webVRCamera.position = this._position;
  81127. this._scene.activeCamera = this._webVRCamera;
  81128. }
  81129. }
  81130. else if (this._vrDeviceOrientationCamera) {
  81131. this._vrDeviceOrientationCamera.position = this._position;
  81132. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  81133. this._scene.getEngine().switchFullscreen(true);
  81134. this.updateButtonVisibility();
  81135. }
  81136. if (this._scene.activeCamera && this._canvas) {
  81137. this._scene.activeCamera.attachControl(this._canvas);
  81138. }
  81139. if (this._interactionsEnabled) {
  81140. this._scene.registerBeforeRender(this.beforeRender);
  81141. }
  81142. };
  81143. /**
  81144. * Attempt to exit VR, or fullscreen.
  81145. */
  81146. VRExperienceHelper.prototype.exitVR = function () {
  81147. if (this.onExitingVRObservable) {
  81148. try {
  81149. this.onExitingVRObservable.notifyObservers(this);
  81150. }
  81151. catch (err) {
  81152. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  81153. }
  81154. }
  81155. if (this._webVRpresenting) {
  81156. this._scene.getEngine().disableVR();
  81157. }
  81158. if (this._scene.activeCamera) {
  81159. this._position = this._scene.activeCamera.position.clone();
  81160. }
  81161. if (this._deviceOrientationCamera) {
  81162. this._deviceOrientationCamera.position = this._position;
  81163. this._scene.activeCamera = this._deviceOrientationCamera;
  81164. if (this._canvas) {
  81165. this._scene.activeCamera.attachControl(this._canvas);
  81166. }
  81167. }
  81168. else if (this._existingCamera) {
  81169. this._existingCamera.position = this._position;
  81170. this._scene.activeCamera = this._existingCamera;
  81171. }
  81172. this.updateButtonVisibility();
  81173. if (this._interactionsEnabled) {
  81174. this._scene.unregisterBeforeRender(this.beforeRender);
  81175. }
  81176. };
  81177. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  81178. /**
  81179. * The position of the vr experience helper.
  81180. */
  81181. get: function () {
  81182. return this._position;
  81183. },
  81184. /**
  81185. * Sets the position of the vr experience helper.
  81186. */
  81187. set: function (value) {
  81188. this._position = value;
  81189. if (this._scene.activeCamera) {
  81190. this._scene.activeCamera.position = value;
  81191. }
  81192. },
  81193. enumerable: true,
  81194. configurable: true
  81195. });
  81196. /**
  81197. * Enables controllers and user interactions suck as selecting and object or clicking on an object.
  81198. */
  81199. VRExperienceHelper.prototype.enableInteractions = function () {
  81200. var _this = this;
  81201. if (!this._interactionsEnabled) {
  81202. this._interactionsRequested = true;
  81203. if (this.leftController) {
  81204. this._enableInteractionOnController(this.leftController);
  81205. }
  81206. if (this.rightController) {
  81207. this._enableInteractionOnController(this.rightController);
  81208. }
  81209. this.raySelectionPredicate = function (mesh) {
  81210. return mesh.isVisible;
  81211. };
  81212. this.meshSelectionPredicate = function (mesh) {
  81213. return true;
  81214. };
  81215. this._raySelectionPredicate = function (mesh) {
  81216. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  81217. && mesh.name.indexOf("teleportationTarget") === -1
  81218. && mesh.name.indexOf("torusTeleportation") === -1
  81219. && mesh.name.indexOf("laserPointer") === -1)) {
  81220. return _this.raySelectionPredicate(mesh);
  81221. }
  81222. return false;
  81223. };
  81224. this._interactionsEnabled = true;
  81225. }
  81226. };
  81227. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  81228. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  81229. if (this._floorMeshesCollection[i].id === mesh.id) {
  81230. return true;
  81231. }
  81232. }
  81233. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  81234. return true;
  81235. }
  81236. return false;
  81237. };
  81238. /**
  81239. * Adds a floor mesh to be used for teleportation.
  81240. * @param floorMesh the mesh to be used for teleportation.
  81241. */
  81242. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  81243. if (!this._floorMeshesCollection) {
  81244. return;
  81245. }
  81246. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  81247. return;
  81248. }
  81249. this._floorMeshesCollection.push(floorMesh);
  81250. };
  81251. /**
  81252. * Removes a floor mesh from being used for teleportation.
  81253. * @param floorMesh the mesh to be removed.
  81254. */
  81255. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  81256. if (!this._floorMeshesCollection) {
  81257. return;
  81258. }
  81259. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  81260. if (meshIndex !== -1) {
  81261. this._floorMeshesCollection.splice(meshIndex, 1);
  81262. }
  81263. };
  81264. /**
  81265. * Enables interactions and teleportation using the VR controllers and gaze.
  81266. * @param vrTeleportationOptions options to modify teleportation behavior.
  81267. */
  81268. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  81269. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  81270. if (!this._teleportationInitialized) {
  81271. this._teleportationRequested = true;
  81272. this.enableInteractions();
  81273. if (vrTeleportationOptions.floorMeshName) {
  81274. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  81275. }
  81276. if (vrTeleportationOptions.floorMeshes) {
  81277. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  81278. }
  81279. if (this.leftController != null) {
  81280. this._enableTeleportationOnController(this.leftController);
  81281. }
  81282. if (this.rightController != null) {
  81283. this._enableTeleportationOnController(this.rightController);
  81284. }
  81285. // Creates an image processing post process for the vignette not relying
  81286. // on the main scene configuration for image processing to reduce setup and spaces
  81287. // (gamma/linear) conflicts.
  81288. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  81289. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  81290. imageProcessingConfiguration.vignetteEnabled = true;
  81291. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  81292. this._webVRCamera.detachPostProcess(this._postProcessMove);
  81293. this._teleportationInitialized = true;
  81294. if (this._isDefaultTeleportationTarget) {
  81295. this._createTeleportationCircles();
  81296. }
  81297. }
  81298. };
  81299. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  81300. var _this = this;
  81301. var controllerMesh = controller.webVRController.mesh;
  81302. if (controllerMesh) {
  81303. var makeNotPick = function (root) {
  81304. root.name += " laserPointer";
  81305. root.getChildMeshes().forEach(function (c) {
  81306. makeNotPick(c);
  81307. });
  81308. };
  81309. makeNotPick(controllerMesh);
  81310. var childMeshes = controllerMesh.getChildMeshes();
  81311. for (var i = 0; i < childMeshes.length; i++) {
  81312. if (childMeshes[i].name && childMeshes[i].name.indexOf("POINTING_POSE") >= 0) {
  81313. controllerMesh = childMeshes[i];
  81314. break;
  81315. }
  81316. }
  81317. controller._setLaserPointerParent(controllerMesh);
  81318. controller._interactionsEnabled = true;
  81319. controller._activatePointer();
  81320. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  81321. // Enabling / disabling laserPointer
  81322. if (_this._displayLaserPointer && stateObject.value === 1) {
  81323. if (controller._activePointer) {
  81324. controller._deactivatePointer();
  81325. }
  81326. else {
  81327. controller._activatePointer();
  81328. }
  81329. if (_this.displayGaze) {
  81330. controller._gazeTracker.isVisible = controller._activePointer;
  81331. }
  81332. }
  81333. });
  81334. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  81335. if (!controller._pointerDownOnMeshAsked) {
  81336. if (stateObject.value > _this._padSensibilityUp) {
  81337. controller._selectionPointerDown();
  81338. }
  81339. }
  81340. else if (stateObject.value < _this._padSensibilityDown) {
  81341. controller._selectionPointerUp();
  81342. }
  81343. });
  81344. }
  81345. };
  81346. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  81347. // Dont teleport if another gaze already requested teleportation
  81348. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  81349. return;
  81350. }
  81351. if (!gazer._teleportationRequestInitiated) {
  81352. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  81353. gazer._activatePointer();
  81354. gazer._teleportationRequestInitiated = true;
  81355. }
  81356. }
  81357. else {
  81358. // Listening to the proper controller values changes to confirm teleportation
  81359. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  81360. if (this._teleportActive) {
  81361. this._teleportCamera(this._haloCenter);
  81362. }
  81363. gazer._teleportationRequestInitiated = false;
  81364. }
  81365. }
  81366. };
  81367. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  81368. // Only rotate when user is not currently selecting a teleportation location
  81369. if (gazer._teleportationRequestInitiated) {
  81370. return;
  81371. }
  81372. if (!this._rotationLeftAsked) {
  81373. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  81374. this._rotationLeftAsked = true;
  81375. if (this._rotationAllowed) {
  81376. this._rotateCamera(false);
  81377. }
  81378. }
  81379. }
  81380. else {
  81381. if (stateObject.x > -this._padSensibilityDown) {
  81382. this._rotationLeftAsked = false;
  81383. }
  81384. }
  81385. if (!this._rotationRightAsked) {
  81386. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  81387. this._rotationRightAsked = true;
  81388. if (this._rotationAllowed) {
  81389. this._rotateCamera(true);
  81390. }
  81391. }
  81392. }
  81393. else {
  81394. if (stateObject.x < this._padSensibilityDown) {
  81395. this._rotationRightAsked = false;
  81396. }
  81397. }
  81398. };
  81399. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  81400. // Only teleport backwards when user is not currently selecting a teleportation location
  81401. if (gazer._teleportationRequestInitiated) {
  81402. return;
  81403. }
  81404. // Teleport backwards
  81405. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  81406. if (!gazer._teleportationBackRequestInitiated) {
  81407. if (!this.currentVRCamera) {
  81408. return;
  81409. }
  81410. // Get rotation and position of the current camera
  81411. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  81412. var position = this.currentVRCamera.position;
  81413. // If the camera has device position, use that instead
  81414. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  81415. rotation = this.currentVRCamera.deviceRotationQuaternion;
  81416. position = this.currentVRCamera.devicePosition;
  81417. }
  81418. // Get matrix with only the y rotation of the device rotation
  81419. rotation.toEulerAnglesToRef(this._workingVector);
  81420. this._workingVector.z = 0;
  81421. this._workingVector.x = 0;
  81422. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  81423. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  81424. // Rotate backwards ray by device rotation to cast at the ground behind the user
  81425. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  81426. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  81427. var ray = new BABYLON.Ray(position, this._workingVector);
  81428. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  81429. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  81430. this._teleportCamera(hit.pickedPoint);
  81431. }
  81432. gazer._teleportationBackRequestInitiated = true;
  81433. }
  81434. }
  81435. else {
  81436. gazer._teleportationBackRequestInitiated = false;
  81437. }
  81438. };
  81439. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  81440. var _this = this;
  81441. var controllerMesh = controller.webVRController.mesh;
  81442. if (controllerMesh) {
  81443. if (!controller._interactionsEnabled) {
  81444. this._enableInteractionOnController(controller);
  81445. }
  81446. controller._interactionsEnabled = true;
  81447. controller._teleportationEnabled = true;
  81448. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  81449. controller._dpadPressed = false;
  81450. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  81451. controller._dpadPressed = stateObject.pressed;
  81452. if (!controller._dpadPressed) {
  81453. _this._rotationLeftAsked = false;
  81454. _this._rotationRightAsked = false;
  81455. controller._teleportationBackRequestInitiated = false;
  81456. }
  81457. });
  81458. }
  81459. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  81460. if (_this.teleportationEnabled) {
  81461. _this._checkTeleportBackwards(stateObject, controller);
  81462. _this._checkTeleportWithRay(stateObject, controller);
  81463. }
  81464. _this._checkRotate(stateObject, controller);
  81465. });
  81466. }
  81467. };
  81468. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  81469. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  81470. this._teleportationTarget.isPickable = false;
  81471. var length = 512;
  81472. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  81473. dynamicTexture.hasAlpha = true;
  81474. var context = dynamicTexture.getContext();
  81475. var centerX = length / 2;
  81476. var centerY = length / 2;
  81477. var radius = 200;
  81478. context.beginPath();
  81479. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  81480. context.fillStyle = this._teleportationFillColor;
  81481. context.fill();
  81482. context.lineWidth = 10;
  81483. context.strokeStyle = this._teleportationBorderColor;
  81484. context.stroke();
  81485. context.closePath();
  81486. dynamicTexture.update();
  81487. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  81488. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  81489. this._teleportationTarget.material = teleportationCircleMaterial;
  81490. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  81491. torus.isPickable = false;
  81492. torus.parent = this._teleportationTarget;
  81493. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  81494. var keys = [];
  81495. keys.push({
  81496. frame: 0,
  81497. value: 0
  81498. });
  81499. keys.push({
  81500. frame: 30,
  81501. value: 0.4
  81502. });
  81503. keys.push({
  81504. frame: 60,
  81505. value: 0
  81506. });
  81507. animationInnerCircle.setKeys(keys);
  81508. var easingFunction = new BABYLON.SineEase();
  81509. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  81510. animationInnerCircle.setEasingFunction(easingFunction);
  81511. torus.animations = [];
  81512. torus.animations.push(animationInnerCircle);
  81513. this._scene.beginAnimation(torus, 0, 60, true);
  81514. this._hideTeleportationTarget();
  81515. };
  81516. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  81517. this._teleportActive = true;
  81518. if (this._teleportationInitialized) {
  81519. this._teleportationTarget.isVisible = true;
  81520. if (this._isDefaultTeleportationTarget) {
  81521. this._teleportationTarget.getChildren()[0].isVisible = true;
  81522. }
  81523. }
  81524. };
  81525. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  81526. this._teleportActive = false;
  81527. if (this._teleportationInitialized) {
  81528. this._teleportationTarget.isVisible = false;
  81529. if (this._isDefaultTeleportationTarget) {
  81530. this._teleportationTarget.getChildren()[0].isVisible = false;
  81531. }
  81532. }
  81533. };
  81534. VRExperienceHelper.prototype._rotateCamera = function (right) {
  81535. var _this = this;
  81536. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  81537. return;
  81538. }
  81539. if (right) {
  81540. this._rotationAngle++;
  81541. }
  81542. else {
  81543. this._rotationAngle--;
  81544. }
  81545. this.currentVRCamera.animations = [];
  81546. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  81547. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  81548. var animationRotationKeys = [];
  81549. animationRotationKeys.push({
  81550. frame: 0,
  81551. value: this.currentVRCamera.rotationQuaternion
  81552. });
  81553. animationRotationKeys.push({
  81554. frame: 6,
  81555. value: target
  81556. });
  81557. animationRotation.setKeys(animationRotationKeys);
  81558. animationRotation.setEasingFunction(this._circleEase);
  81559. this.currentVRCamera.animations.push(animationRotation);
  81560. this._postProcessMove.animations = [];
  81561. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  81562. var vignetteWeightKeys = [];
  81563. vignetteWeightKeys.push({
  81564. frame: 0,
  81565. value: 0
  81566. });
  81567. vignetteWeightKeys.push({
  81568. frame: 3,
  81569. value: 4
  81570. });
  81571. vignetteWeightKeys.push({
  81572. frame: 6,
  81573. value: 0
  81574. });
  81575. animationPP.setKeys(vignetteWeightKeys);
  81576. animationPP.setEasingFunction(this._circleEase);
  81577. this._postProcessMove.animations.push(animationPP);
  81578. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  81579. var vignetteStretchKeys = [];
  81580. vignetteStretchKeys.push({
  81581. frame: 0,
  81582. value: 0
  81583. });
  81584. vignetteStretchKeys.push({
  81585. frame: 3,
  81586. value: 10
  81587. });
  81588. vignetteStretchKeys.push({
  81589. frame: 6,
  81590. value: 0
  81591. });
  81592. animationPP2.setKeys(vignetteStretchKeys);
  81593. animationPP2.setEasingFunction(this._circleEase);
  81594. this._postProcessMove.animations.push(animationPP2);
  81595. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  81596. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  81597. this._postProcessMove.samples = 4;
  81598. this._webVRCamera.attachPostProcess(this._postProcessMove);
  81599. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  81600. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  81601. });
  81602. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  81603. };
  81604. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer) {
  81605. if (hit.pickedPoint) {
  81606. if (gazer._teleportationRequestInitiated) {
  81607. this._displayTeleportationTarget();
  81608. this._haloCenter.copyFrom(hit.pickedPoint);
  81609. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  81610. }
  81611. var pickNormal = hit.getNormal(true, false);
  81612. if (pickNormal) {
  81613. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  81614. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  81615. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  81616. }
  81617. this._teleportationTarget.position.y += 0.1;
  81618. }
  81619. };
  81620. VRExperienceHelper.prototype._teleportCamera = function (location) {
  81621. var _this = this;
  81622. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  81623. return;
  81624. }
  81625. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  81626. // offset of the headset from the anchor.
  81627. if (this.webVRCamera.leftCamera) {
  81628. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  81629. this._workingVector.subtractInPlace(this.webVRCamera.position);
  81630. location.subtractToRef(this._workingVector, this._workingVector);
  81631. }
  81632. else {
  81633. this._workingVector.copyFrom(location);
  81634. }
  81635. // Add height to account for user's height offset
  81636. if (this.isInVRMode) {
  81637. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround();
  81638. }
  81639. else {
  81640. this._workingVector.y += this._defaultHeight;
  81641. }
  81642. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  81643. // Create animation from the camera's position to the new location
  81644. this.currentVRCamera.animations = [];
  81645. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  81646. var animationCameraTeleportationKeys = [{
  81647. frame: 0,
  81648. value: this.currentVRCamera.position
  81649. },
  81650. {
  81651. frame: 11,
  81652. value: this._workingVector
  81653. }
  81654. ];
  81655. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  81656. animationCameraTeleportation.setEasingFunction(this._circleEase);
  81657. this.currentVRCamera.animations.push(animationCameraTeleportation);
  81658. this._postProcessMove.animations = [];
  81659. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  81660. var vignetteWeightKeys = [];
  81661. vignetteWeightKeys.push({
  81662. frame: 0,
  81663. value: 0
  81664. });
  81665. vignetteWeightKeys.push({
  81666. frame: 5,
  81667. value: 8
  81668. });
  81669. vignetteWeightKeys.push({
  81670. frame: 11,
  81671. value: 0
  81672. });
  81673. animationPP.setKeys(vignetteWeightKeys);
  81674. this._postProcessMove.animations.push(animationPP);
  81675. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  81676. var vignetteStretchKeys = [];
  81677. vignetteStretchKeys.push({
  81678. frame: 0,
  81679. value: 0
  81680. });
  81681. vignetteStretchKeys.push({
  81682. frame: 5,
  81683. value: 10
  81684. });
  81685. vignetteStretchKeys.push({
  81686. frame: 11,
  81687. value: 0
  81688. });
  81689. animationPP2.setKeys(vignetteStretchKeys);
  81690. this._postProcessMove.animations.push(animationPP2);
  81691. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  81692. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  81693. this._webVRCamera.attachPostProcess(this._postProcessMove);
  81694. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  81695. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  81696. });
  81697. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  81698. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  81699. });
  81700. this._hideTeleportationTarget();
  81701. };
  81702. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  81703. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  81704. return;
  81705. }
  81706. var hit = this._scene.pickWithRay(gazer._getForwardRay(this._rayLength), this._raySelectionPredicate);
  81707. // Moving the gazeTracker on the mesh face targetted
  81708. if (hit && hit.pickedPoint) {
  81709. if (this._displayGaze) {
  81710. var multiplier = 1;
  81711. gazer._gazeTracker.isVisible = true;
  81712. if (gazer._isActionableMesh) {
  81713. multiplier = 3;
  81714. }
  81715. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  81716. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  81717. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  81718. var pickNormal = hit.getNormal();
  81719. // To avoid z-fighting
  81720. var deltaFighting = 0.002;
  81721. if (pickNormal) {
  81722. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  81723. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  81724. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  81725. }
  81726. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  81727. if (gazer._gazeTracker.position.x < 0) {
  81728. gazer._gazeTracker.position.x += deltaFighting;
  81729. }
  81730. else {
  81731. gazer._gazeTracker.position.x -= deltaFighting;
  81732. }
  81733. if (gazer._gazeTracker.position.y < 0) {
  81734. gazer._gazeTracker.position.y += deltaFighting;
  81735. }
  81736. else {
  81737. gazer._gazeTracker.position.y -= deltaFighting;
  81738. }
  81739. if (gazer._gazeTracker.position.z < 0) {
  81740. gazer._gazeTracker.position.z += deltaFighting;
  81741. }
  81742. else {
  81743. gazer._gazeTracker.position.z -= deltaFighting;
  81744. }
  81745. }
  81746. // Changing the size of the laser pointer based on the distance from the targetted point
  81747. gazer._updatePointerDistance(hit.distance);
  81748. }
  81749. else {
  81750. gazer._gazeTracker.isVisible = false;
  81751. }
  81752. if (hit && hit.pickedMesh) {
  81753. gazer._currentHit = hit;
  81754. if (gazer._pointerDownOnMeshAsked) {
  81755. this._scene.simulatePointerMove(gazer._currentHit, { pointerId: gazer._id });
  81756. }
  81757. // The object selected is the floor, we're in a teleportation scenario
  81758. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  81759. // Moving the teleportation area to this targetted point
  81760. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  81761. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  81762. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  81763. }
  81764. gazer._currentMeshSelected = null;
  81765. if (gazer._teleportationRequestInitiated) {
  81766. this._moveTeleportationSelectorTo(hit, gazer);
  81767. }
  81768. return;
  81769. }
  81770. // If not, we're in a selection scenario
  81771. //this._teleportationAllowed = false;
  81772. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  81773. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  81774. this.onNewMeshPicked.notifyObservers(hit);
  81775. gazer._currentMeshSelected = hit.pickedMesh;
  81776. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  81777. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  81778. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  81779. gazer._isActionableMesh = true;
  81780. }
  81781. else {
  81782. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  81783. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  81784. gazer._isActionableMesh = false;
  81785. }
  81786. try {
  81787. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  81788. }
  81789. catch (err) {
  81790. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  81791. }
  81792. }
  81793. else {
  81794. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  81795. gazer._currentMeshSelected = null;
  81796. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  81797. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  81798. }
  81799. }
  81800. }
  81801. else {
  81802. gazer._currentHit = null;
  81803. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  81804. gazer._currentMeshSelected = null;
  81805. //this._teleportationAllowed = false;
  81806. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  81807. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  81808. }
  81809. };
  81810. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  81811. if (mesh) {
  81812. this.onSelectedMeshUnselected.notifyObservers(mesh);
  81813. }
  81814. };
  81815. /**
  81816. * Sets the color of the laser ray from the vr controllers.
  81817. * @param color new color for the ray.
  81818. */
  81819. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  81820. if (this.leftController) {
  81821. this.leftController._setLaserPointerColor(color);
  81822. }
  81823. if (this.rightController) {
  81824. this.rightController._setLaserPointerColor(color);
  81825. }
  81826. };
  81827. /**
  81828. * Sets the color of the ray from the vr headsets gaze.
  81829. * @param color new color for the ray.
  81830. */
  81831. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  81832. if (!this._cameraGazer._gazeTracker.material) {
  81833. return;
  81834. }
  81835. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  81836. if (this.leftController) {
  81837. this.leftController._gazeTracker.material.emissiveColor = color;
  81838. }
  81839. if (this.rightController) {
  81840. this.rightController._gazeTracker.material.emissiveColor = color;
  81841. }
  81842. };
  81843. /**
  81844. * Exits VR and disposes of the vr experience helper
  81845. */
  81846. VRExperienceHelper.prototype.dispose = function () {
  81847. if (this.isInVRMode) {
  81848. this.exitVR();
  81849. }
  81850. if (this._postProcessMove) {
  81851. this._postProcessMove.dispose();
  81852. }
  81853. if (this._webVRCamera) {
  81854. this._webVRCamera.dispose();
  81855. }
  81856. if (this._vrDeviceOrientationCamera) {
  81857. this._vrDeviceOrientationCamera.dispose();
  81858. }
  81859. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  81860. document.body.removeChild(this._btnVR);
  81861. }
  81862. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  81863. this._deviceOrientationCamera.dispose();
  81864. }
  81865. if (this._cameraGazer) {
  81866. this._cameraGazer.dispose();
  81867. }
  81868. if (this.leftController) {
  81869. this.leftController.dispose();
  81870. }
  81871. if (this.rightController) {
  81872. this.rightController.dispose();
  81873. }
  81874. if (this._teleportationTarget) {
  81875. this._teleportationTarget.dispose();
  81876. }
  81877. this._floorMeshesCollection = [];
  81878. document.removeEventListener("keydown", this._onKeyDown);
  81879. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  81880. window.removeEventListener("resize", this._onResize);
  81881. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  81882. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  81883. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  81884. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  81885. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  81886. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  81887. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  81888. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  81889. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  81890. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  81891. this._scene.unregisterBeforeRender(this.beforeRender);
  81892. };
  81893. /**
  81894. * Gets the name of the VRExperienceHelper class
  81895. * @returns "VRExperienceHelper"
  81896. */
  81897. VRExperienceHelper.prototype.getClassName = function () {
  81898. return "VRExperienceHelper";
  81899. };
  81900. return VRExperienceHelper;
  81901. }());
  81902. BABYLON.VRExperienceHelper = VRExperienceHelper;
  81903. })(BABYLON || (BABYLON = {}));
  81904. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  81905. // Mainly based on these 2 articles :
  81906. // 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
  81907. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  81908. var BABYLON;
  81909. (function (BABYLON) {
  81910. var JoystickAxis;
  81911. (function (JoystickAxis) {
  81912. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  81913. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  81914. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  81915. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  81916. var VirtualJoystick = /** @class */ (function () {
  81917. function VirtualJoystick(leftJoystick) {
  81918. var _this = this;
  81919. if (leftJoystick) {
  81920. this._leftJoystick = true;
  81921. }
  81922. else {
  81923. this._leftJoystick = false;
  81924. }
  81925. VirtualJoystick._globalJoystickIndex++;
  81926. // By default left & right arrow keys are moving the X
  81927. // and up & down keys are moving the Y
  81928. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  81929. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  81930. this.reverseLeftRight = false;
  81931. this.reverseUpDown = false;
  81932. // collections of pointers
  81933. this._touches = new BABYLON.StringDictionary();
  81934. this.deltaPosition = BABYLON.Vector3.Zero();
  81935. this._joystickSensibility = 25;
  81936. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  81937. this._onResize = function (evt) {
  81938. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  81939. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  81940. if (VirtualJoystick.vjCanvas) {
  81941. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  81942. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  81943. }
  81944. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  81945. };
  81946. // injecting a canvas element on top of the canvas 3D game
  81947. if (!VirtualJoystick.vjCanvas) {
  81948. window.addEventListener("resize", this._onResize, false);
  81949. VirtualJoystick.vjCanvas = document.createElement("canvas");
  81950. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  81951. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  81952. VirtualJoystick.vjCanvas.width = window.innerWidth;
  81953. VirtualJoystick.vjCanvas.height = window.innerHeight;
  81954. VirtualJoystick.vjCanvas.style.width = "100%";
  81955. VirtualJoystick.vjCanvas.style.height = "100%";
  81956. VirtualJoystick.vjCanvas.style.position = "absolute";
  81957. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  81958. VirtualJoystick.vjCanvas.style.top = "0px";
  81959. VirtualJoystick.vjCanvas.style.left = "0px";
  81960. VirtualJoystick.vjCanvas.style.zIndex = "5";
  81961. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  81962. // Support for jQuery PEP polyfill
  81963. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  81964. var context = VirtualJoystick.vjCanvas.getContext('2d');
  81965. if (!context) {
  81966. throw new Error("Unable to create canvas for virtual joystick");
  81967. }
  81968. VirtualJoystick.vjCanvasContext = context;
  81969. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  81970. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  81971. document.body.appendChild(VirtualJoystick.vjCanvas);
  81972. }
  81973. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  81974. this.pressed = false;
  81975. // default joystick color
  81976. this._joystickColor = "cyan";
  81977. this._joystickPointerID = -1;
  81978. // current joystick position
  81979. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  81980. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  81981. // origin joystick position
  81982. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  81983. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  81984. this._onPointerDownHandlerRef = function (evt) {
  81985. _this._onPointerDown(evt);
  81986. };
  81987. this._onPointerMoveHandlerRef = function (evt) {
  81988. _this._onPointerMove(evt);
  81989. };
  81990. this._onPointerUpHandlerRef = function (evt) {
  81991. _this._onPointerUp(evt);
  81992. };
  81993. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  81994. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  81995. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  81996. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  81997. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  81998. evt.preventDefault(); // Disables system menu
  81999. }, false);
  82000. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  82001. }
  82002. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  82003. this._joystickSensibility = newJoystickSensibility;
  82004. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  82005. };
  82006. VirtualJoystick.prototype._onPointerDown = function (e) {
  82007. var positionOnScreenCondition;
  82008. e.preventDefault();
  82009. if (this._leftJoystick === true) {
  82010. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  82011. }
  82012. else {
  82013. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  82014. }
  82015. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  82016. // First contact will be dedicated to the virtual joystick
  82017. this._joystickPointerID = e.pointerId;
  82018. this._joystickPointerStartPos.x = e.clientX;
  82019. this._joystickPointerStartPos.y = e.clientY;
  82020. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  82021. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  82022. this._deltaJoystickVector.x = 0;
  82023. this._deltaJoystickVector.y = 0;
  82024. this.pressed = true;
  82025. this._touches.add(e.pointerId.toString(), e);
  82026. }
  82027. else {
  82028. // You can only trigger the action buttons with a joystick declared
  82029. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  82030. this._action();
  82031. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  82032. }
  82033. }
  82034. };
  82035. VirtualJoystick.prototype._onPointerMove = function (e) {
  82036. // If the current pointer is the one associated to the joystick (first touch contact)
  82037. if (this._joystickPointerID == e.pointerId) {
  82038. this._joystickPointerPos.x = e.clientX;
  82039. this._joystickPointerPos.y = e.clientY;
  82040. this._deltaJoystickVector = this._joystickPointerPos.clone();
  82041. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  82042. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  82043. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  82044. switch (this._axisTargetedByLeftAndRight) {
  82045. case JoystickAxis.X:
  82046. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  82047. break;
  82048. case JoystickAxis.Y:
  82049. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  82050. break;
  82051. case JoystickAxis.Z:
  82052. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  82053. break;
  82054. }
  82055. var directionUpDown = this.reverseUpDown ? 1 : -1;
  82056. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  82057. switch (this._axisTargetedByUpAndDown) {
  82058. case JoystickAxis.X:
  82059. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  82060. break;
  82061. case JoystickAxis.Y:
  82062. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  82063. break;
  82064. case JoystickAxis.Z:
  82065. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  82066. break;
  82067. }
  82068. }
  82069. else {
  82070. var data = this._touches.get(e.pointerId.toString());
  82071. if (data) {
  82072. data.x = e.clientX;
  82073. data.y = e.clientY;
  82074. }
  82075. }
  82076. };
  82077. VirtualJoystick.prototype._onPointerUp = function (e) {
  82078. if (this._joystickPointerID == e.pointerId) {
  82079. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  82080. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  82081. this._joystickPointerID = -1;
  82082. this.pressed = false;
  82083. }
  82084. else {
  82085. var touch = this._touches.get(e.pointerId.toString());
  82086. if (touch) {
  82087. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  82088. }
  82089. }
  82090. this._deltaJoystickVector.x = 0;
  82091. this._deltaJoystickVector.y = 0;
  82092. this._touches.remove(e.pointerId.toString());
  82093. };
  82094. /**
  82095. * Change the color of the virtual joystick
  82096. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  82097. */
  82098. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  82099. this._joystickColor = newColor;
  82100. };
  82101. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  82102. this._action = action;
  82103. };
  82104. // Define which axis you'd like to control for left & right
  82105. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  82106. switch (axis) {
  82107. case JoystickAxis.X:
  82108. case JoystickAxis.Y:
  82109. case JoystickAxis.Z:
  82110. this._axisTargetedByLeftAndRight = axis;
  82111. break;
  82112. default:
  82113. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  82114. break;
  82115. }
  82116. };
  82117. // Define which axis you'd like to control for up & down
  82118. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  82119. switch (axis) {
  82120. case JoystickAxis.X:
  82121. case JoystickAxis.Y:
  82122. case JoystickAxis.Z:
  82123. this._axisTargetedByUpAndDown = axis;
  82124. break;
  82125. default:
  82126. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  82127. break;
  82128. }
  82129. };
  82130. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  82131. var _this = this;
  82132. if (this.pressed) {
  82133. this._touches.forEach(function (key, touch) {
  82134. if (touch.pointerId === _this._joystickPointerID) {
  82135. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  82136. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  82137. VirtualJoystick.vjCanvasContext.beginPath();
  82138. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  82139. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  82140. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  82141. VirtualJoystick.vjCanvasContext.stroke();
  82142. VirtualJoystick.vjCanvasContext.closePath();
  82143. VirtualJoystick.vjCanvasContext.beginPath();
  82144. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  82145. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  82146. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  82147. VirtualJoystick.vjCanvasContext.stroke();
  82148. VirtualJoystick.vjCanvasContext.closePath();
  82149. VirtualJoystick.vjCanvasContext.beginPath();
  82150. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  82151. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  82152. VirtualJoystick.vjCanvasContext.stroke();
  82153. VirtualJoystick.vjCanvasContext.closePath();
  82154. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  82155. }
  82156. else {
  82157. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  82158. VirtualJoystick.vjCanvasContext.beginPath();
  82159. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  82160. VirtualJoystick.vjCanvasContext.beginPath();
  82161. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  82162. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  82163. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  82164. VirtualJoystick.vjCanvasContext.stroke();
  82165. VirtualJoystick.vjCanvasContext.closePath();
  82166. touch.prevX = touch.x;
  82167. touch.prevY = touch.y;
  82168. }
  82169. ;
  82170. });
  82171. }
  82172. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  82173. };
  82174. VirtualJoystick.prototype.releaseCanvas = function () {
  82175. if (VirtualJoystick.vjCanvas) {
  82176. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  82177. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  82178. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  82179. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  82180. window.removeEventListener("resize", this._onResize);
  82181. document.body.removeChild(VirtualJoystick.vjCanvas);
  82182. VirtualJoystick.vjCanvas = null;
  82183. }
  82184. };
  82185. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  82186. VirtualJoystick._globalJoystickIndex = 0;
  82187. return VirtualJoystick;
  82188. }());
  82189. BABYLON.VirtualJoystick = VirtualJoystick;
  82190. })(BABYLON || (BABYLON = {}));
  82191. //# sourceMappingURL=babylon.virtualJoystick.js.map
  82192. var BABYLON;
  82193. (function (BABYLON) {
  82194. // We're mainly based on the logic defined into the FreeCamera code
  82195. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  82196. __extends(VirtualJoysticksCamera, _super);
  82197. function VirtualJoysticksCamera(name, position, scene) {
  82198. var _this = _super.call(this, name, position, scene) || this;
  82199. _this.inputs.addVirtualJoystick();
  82200. return _this;
  82201. }
  82202. VirtualJoysticksCamera.prototype.getClassName = function () {
  82203. return "VirtualJoysticksCamera";
  82204. };
  82205. return VirtualJoysticksCamera;
  82206. }(BABYLON.FreeCamera));
  82207. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  82208. })(BABYLON || (BABYLON = {}));
  82209. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  82210. var BABYLON;
  82211. (function (BABYLON) {
  82212. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  82213. function FreeCameraVirtualJoystickInput() {
  82214. }
  82215. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  82216. return this._leftjoystick;
  82217. };
  82218. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  82219. return this._rightjoystick;
  82220. };
  82221. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  82222. if (this._leftjoystick) {
  82223. var camera = this.camera;
  82224. var speed = camera._computeLocalCameraSpeed() * 50;
  82225. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  82226. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  82227. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  82228. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  82229. if (!this._leftjoystick.pressed) {
  82230. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  82231. }
  82232. if (!this._rightjoystick.pressed) {
  82233. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  82234. }
  82235. }
  82236. };
  82237. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  82238. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  82239. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  82240. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  82241. this._leftjoystick.setJoystickSensibility(0.15);
  82242. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  82243. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  82244. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  82245. this._rightjoystick.reverseUpDown = true;
  82246. this._rightjoystick.setJoystickSensibility(0.05);
  82247. this._rightjoystick.setJoystickColor("yellow");
  82248. };
  82249. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  82250. this._leftjoystick.releaseCanvas();
  82251. this._rightjoystick.releaseCanvas();
  82252. };
  82253. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  82254. return "FreeCameraVirtualJoystickInput";
  82255. };
  82256. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  82257. return "virtualJoystick";
  82258. };
  82259. return FreeCameraVirtualJoystickInput;
  82260. }());
  82261. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  82262. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  82263. })(BABYLON || (BABYLON = {}));
  82264. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  82265. var BABYLON;
  82266. (function (BABYLON) {
  82267. var SimplificationSettings = /** @class */ (function () {
  82268. function SimplificationSettings(quality, distance, optimizeMesh) {
  82269. this.quality = quality;
  82270. this.distance = distance;
  82271. this.optimizeMesh = optimizeMesh;
  82272. }
  82273. return SimplificationSettings;
  82274. }());
  82275. BABYLON.SimplificationSettings = SimplificationSettings;
  82276. var SimplificationQueue = /** @class */ (function () {
  82277. function SimplificationQueue() {
  82278. this.running = false;
  82279. this._simplificationArray = [];
  82280. }
  82281. SimplificationQueue.prototype.addTask = function (task) {
  82282. this._simplificationArray.push(task);
  82283. };
  82284. SimplificationQueue.prototype.executeNext = function () {
  82285. var task = this._simplificationArray.pop();
  82286. if (task) {
  82287. this.running = true;
  82288. this.runSimplification(task);
  82289. }
  82290. else {
  82291. this.running = false;
  82292. }
  82293. };
  82294. SimplificationQueue.prototype.runSimplification = function (task) {
  82295. var _this = this;
  82296. if (task.parallelProcessing) {
  82297. //parallel simplifier
  82298. task.settings.forEach(function (setting) {
  82299. var simplifier = _this.getSimplifier(task);
  82300. simplifier.simplify(setting, function (newMesh) {
  82301. task.mesh.addLODLevel(setting.distance, newMesh);
  82302. newMesh.isVisible = true;
  82303. //check if it is the last
  82304. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  82305. //all done, run the success callback.
  82306. task.successCallback();
  82307. }
  82308. _this.executeNext();
  82309. });
  82310. });
  82311. }
  82312. else {
  82313. //single simplifier.
  82314. var simplifier = this.getSimplifier(task);
  82315. var runDecimation = function (setting, callback) {
  82316. simplifier.simplify(setting, function (newMesh) {
  82317. task.mesh.addLODLevel(setting.distance, newMesh);
  82318. newMesh.isVisible = true;
  82319. //run the next quality level
  82320. callback();
  82321. });
  82322. };
  82323. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  82324. runDecimation(task.settings[loop.index], function () {
  82325. loop.executeNext();
  82326. });
  82327. }, function () {
  82328. //execution ended, run the success callback.
  82329. if (task.successCallback) {
  82330. task.successCallback();
  82331. }
  82332. _this.executeNext();
  82333. });
  82334. }
  82335. };
  82336. SimplificationQueue.prototype.getSimplifier = function (task) {
  82337. switch (task.simplificationType) {
  82338. case SimplificationType.QUADRATIC:
  82339. default:
  82340. return new QuadraticErrorSimplification(task.mesh);
  82341. }
  82342. };
  82343. return SimplificationQueue;
  82344. }());
  82345. BABYLON.SimplificationQueue = SimplificationQueue;
  82346. /**
  82347. * The implemented types of simplification.
  82348. * At the moment only Quadratic Error Decimation is implemented.
  82349. */
  82350. var SimplificationType;
  82351. (function (SimplificationType) {
  82352. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  82353. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  82354. var DecimationTriangle = /** @class */ (function () {
  82355. function DecimationTriangle(vertices) {
  82356. this.vertices = vertices;
  82357. this.error = new Array(4);
  82358. this.deleted = false;
  82359. this.isDirty = false;
  82360. this.deletePending = false;
  82361. this.borderFactor = 0;
  82362. }
  82363. return DecimationTriangle;
  82364. }());
  82365. BABYLON.DecimationTriangle = DecimationTriangle;
  82366. var DecimationVertex = /** @class */ (function () {
  82367. function DecimationVertex(position, id) {
  82368. this.position = position;
  82369. this.id = id;
  82370. this.isBorder = true;
  82371. this.q = new QuadraticMatrix();
  82372. this.triangleCount = 0;
  82373. this.triangleStart = 0;
  82374. this.originalOffsets = [];
  82375. }
  82376. DecimationVertex.prototype.updatePosition = function (newPosition) {
  82377. this.position.copyFrom(newPosition);
  82378. };
  82379. return DecimationVertex;
  82380. }());
  82381. BABYLON.DecimationVertex = DecimationVertex;
  82382. var QuadraticMatrix = /** @class */ (function () {
  82383. function QuadraticMatrix(data) {
  82384. this.data = new Array(10);
  82385. for (var i = 0; i < 10; ++i) {
  82386. if (data && data[i]) {
  82387. this.data[i] = data[i];
  82388. }
  82389. else {
  82390. this.data[i] = 0;
  82391. }
  82392. }
  82393. }
  82394. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  82395. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  82396. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  82397. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  82398. return det;
  82399. };
  82400. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  82401. for (var i = 0; i < 10; ++i) {
  82402. this.data[i] += matrix.data[i];
  82403. }
  82404. };
  82405. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  82406. for (var i = 0; i < 10; ++i) {
  82407. this.data[i] += data[i];
  82408. }
  82409. };
  82410. QuadraticMatrix.prototype.add = function (matrix) {
  82411. var m = new QuadraticMatrix();
  82412. for (var i = 0; i < 10; ++i) {
  82413. m.data[i] = this.data[i] + matrix.data[i];
  82414. }
  82415. return m;
  82416. };
  82417. QuadraticMatrix.FromData = function (a, b, c, d) {
  82418. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  82419. };
  82420. //returning an array to avoid garbage collection
  82421. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  82422. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  82423. };
  82424. return QuadraticMatrix;
  82425. }());
  82426. BABYLON.QuadraticMatrix = QuadraticMatrix;
  82427. var Reference = /** @class */ (function () {
  82428. function Reference(vertexId, triangleId) {
  82429. this.vertexId = vertexId;
  82430. this.triangleId = triangleId;
  82431. }
  82432. return Reference;
  82433. }());
  82434. BABYLON.Reference = Reference;
  82435. /**
  82436. * An implementation of the Quadratic Error simplification algorithm.
  82437. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  82438. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  82439. * @author RaananW
  82440. */
  82441. var QuadraticErrorSimplification = /** @class */ (function () {
  82442. function QuadraticErrorSimplification(_mesh) {
  82443. this._mesh = _mesh;
  82444. this.syncIterations = 5000;
  82445. this.aggressiveness = 7;
  82446. this.decimationIterations = 100;
  82447. this.boundingBoxEpsilon = BABYLON.Epsilon;
  82448. }
  82449. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  82450. var _this = this;
  82451. this.initDecimatedMesh();
  82452. //iterating through the submeshes array, one after the other.
  82453. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  82454. _this.initWithMesh(loop.index, function () {
  82455. _this.runDecimation(settings, loop.index, function () {
  82456. loop.executeNext();
  82457. });
  82458. }, settings.optimizeMesh);
  82459. }, function () {
  82460. setTimeout(function () {
  82461. successCallback(_this._reconstructedMesh);
  82462. }, 0);
  82463. });
  82464. };
  82465. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  82466. var _this = this;
  82467. var targetCount = ~~(this.triangles.length * settings.quality);
  82468. var deletedTriangles = 0;
  82469. var triangleCount = this.triangles.length;
  82470. var iterationFunction = function (iteration, callback) {
  82471. setTimeout(function () {
  82472. if (iteration % 5 === 0) {
  82473. _this.updateMesh(iteration === 0);
  82474. }
  82475. for (var i = 0; i < _this.triangles.length; ++i) {
  82476. _this.triangles[i].isDirty = false;
  82477. }
  82478. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  82479. var trianglesIterator = function (i) {
  82480. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  82481. var t = _this.triangles[tIdx];
  82482. if (!t)
  82483. return;
  82484. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  82485. return;
  82486. }
  82487. for (var j = 0; j < 3; ++j) {
  82488. if (t.error[j] < threshold) {
  82489. var deleted0 = [];
  82490. var deleted1 = [];
  82491. var v0 = t.vertices[j];
  82492. var v1 = t.vertices[(j + 1) % 3];
  82493. if (v0.isBorder || v1.isBorder)
  82494. continue;
  82495. var p = BABYLON.Vector3.Zero();
  82496. var n = BABYLON.Vector3.Zero();
  82497. var uv = BABYLON.Vector2.Zero();
  82498. var color = new BABYLON.Color4(0, 0, 0, 1);
  82499. _this.calculateError(v0, v1, p, n, uv, color);
  82500. var delTr = new Array();
  82501. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  82502. continue;
  82503. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  82504. continue;
  82505. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  82506. continue;
  82507. var uniqueArray = new Array();
  82508. delTr.forEach(function (deletedT) {
  82509. if (uniqueArray.indexOf(deletedT) === -1) {
  82510. deletedT.deletePending = true;
  82511. uniqueArray.push(deletedT);
  82512. }
  82513. });
  82514. if (uniqueArray.length % 2 !== 0) {
  82515. continue;
  82516. }
  82517. v0.q = v1.q.add(v0.q);
  82518. v0.updatePosition(p);
  82519. var tStart = _this.references.length;
  82520. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  82521. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  82522. var tCount = _this.references.length - tStart;
  82523. if (tCount <= v0.triangleCount) {
  82524. if (tCount) {
  82525. for (var c = 0; c < tCount; c++) {
  82526. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  82527. }
  82528. }
  82529. }
  82530. else {
  82531. v0.triangleStart = tStart;
  82532. }
  82533. v0.triangleCount = tCount;
  82534. break;
  82535. }
  82536. }
  82537. };
  82538. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  82539. }, 0);
  82540. };
  82541. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  82542. if (triangleCount - deletedTriangles <= targetCount)
  82543. loop.breakLoop();
  82544. else {
  82545. iterationFunction(loop.index, function () {
  82546. loop.executeNext();
  82547. });
  82548. }
  82549. }, function () {
  82550. setTimeout(function () {
  82551. //reconstruct this part of the mesh
  82552. _this.reconstructMesh(submeshIndex);
  82553. successCallback();
  82554. }, 0);
  82555. });
  82556. };
  82557. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  82558. var _this = this;
  82559. this.vertices = [];
  82560. this.triangles = [];
  82561. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  82562. var indices = this._mesh.getIndices();
  82563. var submesh = this._mesh.subMeshes[submeshIndex];
  82564. var findInVertices = function (positionToSearch) {
  82565. if (optimizeMesh) {
  82566. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  82567. if (_this.vertices[ii].position.equals(positionToSearch)) {
  82568. return _this.vertices[ii];
  82569. }
  82570. }
  82571. }
  82572. return null;
  82573. };
  82574. var vertexReferences = [];
  82575. var vertexInit = function (i) {
  82576. if (!positionData) {
  82577. return;
  82578. }
  82579. var offset = i + submesh.verticesStart;
  82580. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  82581. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  82582. vertex.originalOffsets.push(offset);
  82583. if (vertex.id === _this.vertices.length) {
  82584. _this.vertices.push(vertex);
  82585. }
  82586. vertexReferences.push(vertex.id);
  82587. };
  82588. //var totalVertices = mesh.getTotalVertices();
  82589. var totalVertices = submesh.verticesCount;
  82590. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  82591. var indicesInit = function (i) {
  82592. if (!indices) {
  82593. return;
  82594. }
  82595. var offset = (submesh.indexStart / 3) + i;
  82596. var pos = (offset * 3);
  82597. var i0 = indices[pos + 0];
  82598. var i1 = indices[pos + 1];
  82599. var i2 = indices[pos + 2];
  82600. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  82601. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  82602. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  82603. var triangle = new DecimationTriangle([v0, v1, v2]);
  82604. triangle.originalOffset = pos;
  82605. _this.triangles.push(triangle);
  82606. };
  82607. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  82608. _this.init(callback);
  82609. });
  82610. });
  82611. };
  82612. QuadraticErrorSimplification.prototype.init = function (callback) {
  82613. var _this = this;
  82614. var triangleInit1 = function (i) {
  82615. var t = _this.triangles[i];
  82616. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  82617. for (var j = 0; j < 3; j++) {
  82618. 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))));
  82619. }
  82620. };
  82621. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  82622. var triangleInit2 = function (i) {
  82623. var t = _this.triangles[i];
  82624. for (var j = 0; j < 3; ++j) {
  82625. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  82626. }
  82627. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  82628. };
  82629. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  82630. callback();
  82631. });
  82632. });
  82633. };
  82634. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  82635. var newTriangles = [];
  82636. var i;
  82637. for (i = 0; i < this.vertices.length; ++i) {
  82638. this.vertices[i].triangleCount = 0;
  82639. }
  82640. var t;
  82641. var j;
  82642. for (i = 0; i < this.triangles.length; ++i) {
  82643. if (!this.triangles[i].deleted) {
  82644. t = this.triangles[i];
  82645. for (j = 0; j < 3; ++j) {
  82646. t.vertices[j].triangleCount = 1;
  82647. }
  82648. newTriangles.push(t);
  82649. }
  82650. }
  82651. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  82652. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  82653. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  82654. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  82655. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  82656. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  82657. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  82658. var vertexCount = 0;
  82659. for (i = 0; i < this.vertices.length; ++i) {
  82660. var vertex = this.vertices[i];
  82661. vertex.id = vertexCount;
  82662. if (vertex.triangleCount) {
  82663. vertex.originalOffsets.forEach(function (originalOffset) {
  82664. if (!normalData) {
  82665. return;
  82666. }
  82667. newPositionData.push(vertex.position.x);
  82668. newPositionData.push(vertex.position.y);
  82669. newPositionData.push(vertex.position.z);
  82670. newNormalData.push(normalData[originalOffset * 3]);
  82671. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  82672. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  82673. if (uvs && uvs.length) {
  82674. newUVsData.push(uvs[(originalOffset * 2)]);
  82675. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  82676. }
  82677. else if (colorsData && colorsData.length) {
  82678. newColorsData.push(colorsData[(originalOffset * 4)]);
  82679. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  82680. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  82681. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  82682. }
  82683. ++vertexCount;
  82684. });
  82685. }
  82686. }
  82687. var startingIndex = this._reconstructedMesh.getTotalIndices();
  82688. var startingVertex = this._reconstructedMesh.getTotalVertices();
  82689. var submeshesArray = this._reconstructedMesh.subMeshes;
  82690. this._reconstructedMesh.subMeshes = [];
  82691. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  82692. var originalIndices = this._mesh.getIndices();
  82693. for (i = 0; i < newTriangles.length; ++i) {
  82694. t = newTriangles[i]; //now get the new referencing point for each vertex
  82695. [0, 1, 2].forEach(function (idx) {
  82696. var id = originalIndices[t.originalOffset + idx];
  82697. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  82698. if (offset < 0)
  82699. offset = 0;
  82700. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  82701. });
  82702. }
  82703. //overwriting the old vertex buffers and indices.
  82704. this._reconstructedMesh.setIndices(newIndicesArray);
  82705. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  82706. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  82707. if (newUVsData.length > 0)
  82708. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  82709. if (newColorsData.length > 0)
  82710. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  82711. //create submesh
  82712. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  82713. if (submeshIndex > 0) {
  82714. this._reconstructedMesh.subMeshes = [];
  82715. submeshesArray.forEach(function (submesh) {
  82716. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  82717. });
  82718. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  82719. }
  82720. };
  82721. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  82722. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  82723. this._reconstructedMesh.material = this._mesh.material;
  82724. this._reconstructedMesh.parent = this._mesh.parent;
  82725. this._reconstructedMesh.isVisible = false;
  82726. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  82727. };
  82728. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  82729. for (var i = 0; i < vertex1.triangleCount; ++i) {
  82730. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  82731. if (t.deleted)
  82732. continue;
  82733. var s = this.references[vertex1.triangleStart + i].vertexId;
  82734. var v1 = t.vertices[(s + 1) % 3];
  82735. var v2 = t.vertices[(s + 2) % 3];
  82736. if ((v1 === vertex2 || v2 === vertex2)) {
  82737. deletedArray[i] = true;
  82738. delTr.push(t);
  82739. continue;
  82740. }
  82741. var d1 = v1.position.subtract(point);
  82742. d1 = d1.normalize();
  82743. var d2 = v2.position.subtract(point);
  82744. d2 = d2.normalize();
  82745. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  82746. return true;
  82747. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  82748. deletedArray[i] = false;
  82749. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  82750. return true;
  82751. }
  82752. return false;
  82753. };
  82754. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  82755. var newDeleted = deletedTriangles;
  82756. for (var i = 0; i < vertex.triangleCount; ++i) {
  82757. var ref = this.references[vertex.triangleStart + i];
  82758. var t = this.triangles[ref.triangleId];
  82759. if (t.deleted)
  82760. continue;
  82761. if (deletedArray[i] && t.deletePending) {
  82762. t.deleted = true;
  82763. newDeleted++;
  82764. continue;
  82765. }
  82766. t.vertices[ref.vertexId] = origVertex;
  82767. t.isDirty = true;
  82768. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  82769. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  82770. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  82771. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  82772. this.references.push(ref);
  82773. }
  82774. return newDeleted;
  82775. };
  82776. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  82777. for (var i = 0; i < this.vertices.length; ++i) {
  82778. var vCount = [];
  82779. var vId = [];
  82780. var v = this.vertices[i];
  82781. var j;
  82782. for (j = 0; j < v.triangleCount; ++j) {
  82783. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  82784. for (var ii = 0; ii < 3; ii++) {
  82785. var ofs = 0;
  82786. var vv = triangle.vertices[ii];
  82787. while (ofs < vCount.length) {
  82788. if (vId[ofs] === vv.id)
  82789. break;
  82790. ++ofs;
  82791. }
  82792. if (ofs === vCount.length) {
  82793. vCount.push(1);
  82794. vId.push(vv.id);
  82795. }
  82796. else {
  82797. vCount[ofs]++;
  82798. }
  82799. }
  82800. }
  82801. for (j = 0; j < vCount.length; ++j) {
  82802. if (vCount[j] === 1) {
  82803. this.vertices[vId[j]].isBorder = true;
  82804. }
  82805. else {
  82806. this.vertices[vId[j]].isBorder = false;
  82807. }
  82808. }
  82809. }
  82810. };
  82811. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  82812. if (identifyBorders === void 0) { identifyBorders = false; }
  82813. var i;
  82814. if (!identifyBorders) {
  82815. var newTrianglesVector = [];
  82816. for (i = 0; i < this.triangles.length; ++i) {
  82817. if (!this.triangles[i].deleted) {
  82818. newTrianglesVector.push(this.triangles[i]);
  82819. }
  82820. }
  82821. this.triangles = newTrianglesVector;
  82822. }
  82823. for (i = 0; i < this.vertices.length; ++i) {
  82824. this.vertices[i].triangleCount = 0;
  82825. this.vertices[i].triangleStart = 0;
  82826. }
  82827. var t;
  82828. var j;
  82829. var v;
  82830. for (i = 0; i < this.triangles.length; ++i) {
  82831. t = this.triangles[i];
  82832. for (j = 0; j < 3; ++j) {
  82833. v = t.vertices[j];
  82834. v.triangleCount++;
  82835. }
  82836. }
  82837. var tStart = 0;
  82838. for (i = 0; i < this.vertices.length; ++i) {
  82839. this.vertices[i].triangleStart = tStart;
  82840. tStart += this.vertices[i].triangleCount;
  82841. this.vertices[i].triangleCount = 0;
  82842. }
  82843. var newReferences = new Array(this.triangles.length * 3);
  82844. for (i = 0; i < this.triangles.length; ++i) {
  82845. t = this.triangles[i];
  82846. for (j = 0; j < 3; ++j) {
  82847. v = t.vertices[j];
  82848. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  82849. v.triangleCount++;
  82850. }
  82851. }
  82852. this.references = newReferences;
  82853. if (identifyBorders) {
  82854. this.identifyBorder();
  82855. }
  82856. };
  82857. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  82858. var x = point.x;
  82859. var y = point.y;
  82860. var z = point.z;
  82861. 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
  82862. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  82863. };
  82864. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  82865. var q = vertex1.q.add(vertex2.q);
  82866. var border = vertex1.isBorder && vertex2.isBorder;
  82867. var error = 0;
  82868. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  82869. if (qDet !== 0 && !border) {
  82870. if (!pointResult) {
  82871. pointResult = BABYLON.Vector3.Zero();
  82872. }
  82873. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  82874. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  82875. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  82876. error = this.vertexError(q, pointResult);
  82877. }
  82878. else {
  82879. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  82880. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  82881. var error1 = this.vertexError(q, vertex1.position);
  82882. var error2 = this.vertexError(q, vertex2.position);
  82883. var error3 = this.vertexError(q, p3);
  82884. error = Math.min(error1, error2, error3);
  82885. if (error === error1) {
  82886. if (pointResult) {
  82887. pointResult.copyFrom(vertex1.position);
  82888. }
  82889. }
  82890. else if (error === error2) {
  82891. if (pointResult) {
  82892. pointResult.copyFrom(vertex2.position);
  82893. }
  82894. }
  82895. else {
  82896. if (pointResult) {
  82897. pointResult.copyFrom(p3);
  82898. }
  82899. }
  82900. }
  82901. return error;
  82902. };
  82903. return QuadraticErrorSimplification;
  82904. }());
  82905. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  82906. })(BABYLON || (BABYLON = {}));
  82907. //# sourceMappingURL=babylon.meshSimplification.js.map
  82908. var BABYLON;
  82909. (function (BABYLON) {
  82910. var MeshLODLevel = /** @class */ (function () {
  82911. function MeshLODLevel(distance, mesh) {
  82912. this.distance = distance;
  82913. this.mesh = mesh;
  82914. }
  82915. return MeshLODLevel;
  82916. }());
  82917. BABYLON.MeshLODLevel = MeshLODLevel;
  82918. })(BABYLON || (BABYLON = {}));
  82919. //# sourceMappingURL=babylon.meshLODLevel.js.map
  82920. var BABYLON;
  82921. (function (BABYLON) {
  82922. /**
  82923. * Defines the root class used to create scene optimization to use with SceneOptimizer
  82924. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  82925. */
  82926. var SceneOptimization = /** @class */ (function () {
  82927. /**
  82928. * Creates the SceneOptimization object
  82929. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  82930. * @param desc defines the description associated with the optimization
  82931. */
  82932. function SceneOptimization(
  82933. /**
  82934. * Defines the priority of this optimization (0 by default which means first in the list)
  82935. */
  82936. priority) {
  82937. if (priority === void 0) { priority = 0; }
  82938. this.priority = priority;
  82939. }
  82940. /**
  82941. * Gets a string describing the action executed by the current optimization
  82942. * @returns description string
  82943. */
  82944. SceneOptimization.prototype.getDescription = function () {
  82945. return "";
  82946. };
  82947. /**
  82948. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  82949. * @param scene defines the current scene where to apply this optimization
  82950. * @param optimizer defines the current optimizer
  82951. * @returns true if everything that can be done was applied
  82952. */
  82953. SceneOptimization.prototype.apply = function (scene, optimizer) {
  82954. return true;
  82955. };
  82956. ;
  82957. return SceneOptimization;
  82958. }());
  82959. BABYLON.SceneOptimization = SceneOptimization;
  82960. /**
  82961. * Defines an optimization used to reduce the size of render target textures
  82962. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  82963. */
  82964. var TextureOptimization = /** @class */ (function (_super) {
  82965. __extends(TextureOptimization, _super);
  82966. /**
  82967. * Creates the TextureOptimization object
  82968. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  82969. * @param maximumSize defines the maximum sized allowed for textures (1024 is the default value). If a texture is bigger, it will be scaled down using a factor defined by the step parameter
  82970. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  82971. */
  82972. function TextureOptimization(
  82973. /**
  82974. * Defines the priority of this optimization (0 by default which means first in the list)
  82975. */
  82976. priority,
  82977. /**
  82978. * Defines the maximum sized allowed for textures (1024 is the default value). If a texture is bigger, it will be scaled down using a factor defined by the step parameter
  82979. */
  82980. maximumSize,
  82981. /**
  82982. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  82983. */
  82984. step) {
  82985. if (priority === void 0) { priority = 0; }
  82986. if (maximumSize === void 0) { maximumSize = 1024; }
  82987. if (step === void 0) { step = 0.5; }
  82988. var _this = _super.call(this, priority) || this;
  82989. _this.priority = priority;
  82990. _this.maximumSize = maximumSize;
  82991. _this.step = step;
  82992. return _this;
  82993. }
  82994. /**
  82995. * Gets a string describing the action executed by the current optimization
  82996. * @returns description string
  82997. */
  82998. TextureOptimization.prototype.getDescription = function () {
  82999. return "Reducing render target texture size to " + this.maximumSize;
  83000. };
  83001. /**
  83002. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  83003. * @param scene defines the current scene where to apply this optimization
  83004. * @param optimizer defines the current optimizer
  83005. * @returns true if everything that can be done was applied
  83006. */
  83007. TextureOptimization.prototype.apply = function (scene, optimizer) {
  83008. var allDone = true;
  83009. for (var index = 0; index < scene.textures.length; index++) {
  83010. var texture = scene.textures[index];
  83011. if (!texture.canRescale || texture.getContext) {
  83012. continue;
  83013. }
  83014. var currentSize = texture.getSize();
  83015. var maxDimension = Math.max(currentSize.width, currentSize.height);
  83016. if (maxDimension > this.maximumSize) {
  83017. texture.scale(this.step);
  83018. allDone = false;
  83019. }
  83020. }
  83021. return allDone;
  83022. };
  83023. return TextureOptimization;
  83024. }(SceneOptimization));
  83025. BABYLON.TextureOptimization = TextureOptimization;
  83026. /**
  83027. * Defines an optimization used to increase or decrease the rendering resolution
  83028. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  83029. */
  83030. var HardwareScalingOptimization = /** @class */ (function (_super) {
  83031. __extends(HardwareScalingOptimization, _super);
  83032. /**
  83033. * Creates the HardwareScalingOptimization object
  83034. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  83035. * @param maximumScale defines the maximum scale to use (2 by default)
  83036. * @param step defines the step to use between two passes (0.5 by default)
  83037. */
  83038. function HardwareScalingOptimization(
  83039. /**
  83040. * Defines the priority of this optimization (0 by default which means first in the list)
  83041. */
  83042. priority,
  83043. /**
  83044. * Defines the maximum scale to use (2 by default)
  83045. */
  83046. maximumScale,
  83047. /**
  83048. * Defines the step to use between two passes (0.5 by default)
  83049. */
  83050. step) {
  83051. if (priority === void 0) { priority = 0; }
  83052. if (maximumScale === void 0) { maximumScale = 2; }
  83053. if (step === void 0) { step = 0.25; }
  83054. var _this = _super.call(this, priority) || this;
  83055. _this.priority = priority;
  83056. _this.maximumScale = maximumScale;
  83057. _this.step = step;
  83058. _this._currentScale = -1;
  83059. _this._directionOffset = 1;
  83060. return _this;
  83061. }
  83062. /**
  83063. * Gets a string describing the action executed by the current optimization
  83064. * @return description string
  83065. */
  83066. HardwareScalingOptimization.prototype.getDescription = function () {
  83067. return "Setting hardware scaling level to " + this._currentScale;
  83068. };
  83069. /**
  83070. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  83071. * @param scene defines the current scene where to apply this optimization
  83072. * @param optimizer defines the current optimizer
  83073. * @returns true if everything that can be done was applied
  83074. */
  83075. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  83076. if (this._currentScale === -1) {
  83077. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  83078. if (this._currentScale > this.maximumScale) {
  83079. this._directionOffset = -1;
  83080. }
  83081. }
  83082. this._currentScale += this._directionOffset * this.step;
  83083. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  83084. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  83085. };
  83086. ;
  83087. return HardwareScalingOptimization;
  83088. }(SceneOptimization));
  83089. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  83090. /**
  83091. * Defines an optimization used to remove shadows
  83092. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  83093. */
  83094. var ShadowsOptimization = /** @class */ (function (_super) {
  83095. __extends(ShadowsOptimization, _super);
  83096. function ShadowsOptimization() {
  83097. return _super !== null && _super.apply(this, arguments) || this;
  83098. }
  83099. /**
  83100. * Gets a string describing the action executed by the current optimization
  83101. * @return description string
  83102. */
  83103. ShadowsOptimization.prototype.getDescription = function () {
  83104. return "Turning shadows on/off";
  83105. };
  83106. /**
  83107. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  83108. * @param scene defines the current scene where to apply this optimization
  83109. * @param optimizer defines the current optimizer
  83110. * @returns true if everything that can be done was applied
  83111. */
  83112. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  83113. scene.shadowsEnabled = optimizer.isInImprovementMode;
  83114. return true;
  83115. };
  83116. ;
  83117. return ShadowsOptimization;
  83118. }(SceneOptimization));
  83119. BABYLON.ShadowsOptimization = ShadowsOptimization;
  83120. /**
  83121. * Defines an optimization used to turn post-processes off
  83122. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  83123. */
  83124. var PostProcessesOptimization = /** @class */ (function (_super) {
  83125. __extends(PostProcessesOptimization, _super);
  83126. function PostProcessesOptimization() {
  83127. return _super !== null && _super.apply(this, arguments) || this;
  83128. }
  83129. /**
  83130. * Gets a string describing the action executed by the current optimization
  83131. * @return description string
  83132. */
  83133. PostProcessesOptimization.prototype.getDescription = function () {
  83134. return "Turning post-processes on/off";
  83135. };
  83136. /**
  83137. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  83138. * @param scene defines the current scene where to apply this optimization
  83139. * @param optimizer defines the current optimizer
  83140. * @returns true if everything that can be done was applied
  83141. */
  83142. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  83143. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  83144. return true;
  83145. };
  83146. ;
  83147. return PostProcessesOptimization;
  83148. }(SceneOptimization));
  83149. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  83150. /**
  83151. * Defines an optimization used to turn lens flares off
  83152. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  83153. */
  83154. var LensFlaresOptimization = /** @class */ (function (_super) {
  83155. __extends(LensFlaresOptimization, _super);
  83156. function LensFlaresOptimization() {
  83157. return _super !== null && _super.apply(this, arguments) || this;
  83158. }
  83159. /**
  83160. * Gets a string describing the action executed by the current optimization
  83161. * @return description string
  83162. */
  83163. LensFlaresOptimization.prototype.getDescription = function () {
  83164. return "Turning lens flares on/off";
  83165. };
  83166. /**
  83167. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  83168. * @param scene defines the current scene where to apply this optimization
  83169. * @param optimizer defines the current optimizer
  83170. * @returns true if everything that can be done was applied
  83171. */
  83172. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  83173. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  83174. return true;
  83175. };
  83176. ;
  83177. return LensFlaresOptimization;
  83178. }(SceneOptimization));
  83179. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  83180. /**
  83181. * Defines an optimization based on user defined callback.
  83182. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  83183. */
  83184. var CustomOptimization = /** @class */ (function (_super) {
  83185. __extends(CustomOptimization, _super);
  83186. function CustomOptimization() {
  83187. return _super !== null && _super.apply(this, arguments) || this;
  83188. }
  83189. /**
  83190. * Gets a string describing the action executed by the current optimization
  83191. * @returns description string
  83192. */
  83193. CustomOptimization.prototype.getDescription = function () {
  83194. if (this.onGetDescription) {
  83195. return this.onGetDescription();
  83196. }
  83197. return "Running user defined callback";
  83198. };
  83199. /**
  83200. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  83201. * @param scene defines the current scene where to apply this optimization
  83202. * @param optimizer defines the current optimizer
  83203. * @returns true if everything that can be done was applied
  83204. */
  83205. CustomOptimization.prototype.apply = function (scene, optimizer) {
  83206. if (this.onApply) {
  83207. return this.onApply(scene, optimizer);
  83208. }
  83209. return true;
  83210. };
  83211. ;
  83212. return CustomOptimization;
  83213. }(SceneOptimization));
  83214. BABYLON.CustomOptimization = CustomOptimization;
  83215. /**
  83216. * Defines an optimization used to turn particles off
  83217. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  83218. */
  83219. var ParticlesOptimization = /** @class */ (function (_super) {
  83220. __extends(ParticlesOptimization, _super);
  83221. function ParticlesOptimization() {
  83222. return _super !== null && _super.apply(this, arguments) || this;
  83223. }
  83224. /**
  83225. * Gets a string describing the action executed by the current optimization
  83226. * @return description string
  83227. */
  83228. ParticlesOptimization.prototype.getDescription = function () {
  83229. return "Turning particles on/off";
  83230. };
  83231. /**
  83232. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  83233. * @param scene defines the current scene where to apply this optimization
  83234. * @param optimizer defines the current optimizer
  83235. * @returns true if everything that can be done was applied
  83236. */
  83237. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  83238. scene.particlesEnabled = optimizer.isInImprovementMode;
  83239. return true;
  83240. };
  83241. ;
  83242. return ParticlesOptimization;
  83243. }(SceneOptimization));
  83244. BABYLON.ParticlesOptimization = ParticlesOptimization;
  83245. /**
  83246. * Defines an optimization used to turn render targets off
  83247. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  83248. */
  83249. var RenderTargetsOptimization = /** @class */ (function (_super) {
  83250. __extends(RenderTargetsOptimization, _super);
  83251. function RenderTargetsOptimization() {
  83252. return _super !== null && _super.apply(this, arguments) || this;
  83253. }
  83254. /**
  83255. * Gets a string describing the action executed by the current optimization
  83256. * @return description string
  83257. */
  83258. RenderTargetsOptimization.prototype.getDescription = function () {
  83259. return "Turning render targets off";
  83260. };
  83261. /**
  83262. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  83263. * @param scene defines the current scene where to apply this optimization
  83264. * @param optimizer defines the current optimizer
  83265. * @returns true if everything that can be done was applied
  83266. */
  83267. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  83268. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  83269. return true;
  83270. };
  83271. ;
  83272. return RenderTargetsOptimization;
  83273. }(SceneOptimization));
  83274. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  83275. /**
  83276. * Defines an optimization used to merge meshes with compatible materials
  83277. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  83278. */
  83279. var MergeMeshesOptimization = /** @class */ (function (_super) {
  83280. __extends(MergeMeshesOptimization, _super);
  83281. function MergeMeshesOptimization() {
  83282. var _this = _super !== null && _super.apply(this, arguments) || this;
  83283. _this._canBeMerged = function (abstractMesh) {
  83284. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  83285. return false;
  83286. }
  83287. var mesh = abstractMesh;
  83288. if (!mesh.isVisible || !mesh.isEnabled()) {
  83289. return false;
  83290. }
  83291. if (mesh.instances.length > 0) {
  83292. return false;
  83293. }
  83294. if (mesh.skeleton || mesh.hasLODLevels) {
  83295. return false;
  83296. }
  83297. if (mesh.parent) {
  83298. return false;
  83299. }
  83300. return true;
  83301. };
  83302. return _this;
  83303. }
  83304. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  83305. /**
  83306. * Gets or sets a boolean which defines if optimization octree has to be updated
  83307. */
  83308. get: function () {
  83309. return MergeMeshesOptimization._UpdateSelectionTree;
  83310. },
  83311. /**
  83312. * Gets or sets a boolean which defines if optimization octree has to be updated
  83313. */
  83314. set: function (value) {
  83315. MergeMeshesOptimization._UpdateSelectionTree = value;
  83316. },
  83317. enumerable: true,
  83318. configurable: true
  83319. });
  83320. /**
  83321. * Gets a string describing the action executed by the current optimization
  83322. * @return description string
  83323. */
  83324. MergeMeshesOptimization.prototype.getDescription = function () {
  83325. return "Merging similar meshes together";
  83326. };
  83327. /**
  83328. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  83329. * @param scene defines the current scene where to apply this optimization
  83330. * @param optimizer defines the current optimizer
  83331. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  83332. * @returns true if everything that can be done was applied
  83333. */
  83334. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  83335. var globalPool = scene.meshes.slice(0);
  83336. var globalLength = globalPool.length;
  83337. for (var index = 0; index < globalLength; index++) {
  83338. var currentPool = new Array();
  83339. var current = globalPool[index];
  83340. // Checks
  83341. if (!this._canBeMerged(current)) {
  83342. continue;
  83343. }
  83344. currentPool.push(current);
  83345. // Find compatible meshes
  83346. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  83347. var otherMesh = globalPool[subIndex];
  83348. if (!this._canBeMerged(otherMesh)) {
  83349. continue;
  83350. }
  83351. if (otherMesh.material !== current.material) {
  83352. continue;
  83353. }
  83354. if (otherMesh.checkCollisions !== current.checkCollisions) {
  83355. continue;
  83356. }
  83357. currentPool.push(otherMesh);
  83358. globalLength--;
  83359. globalPool.splice(subIndex, 1);
  83360. subIndex--;
  83361. }
  83362. if (currentPool.length < 2) {
  83363. continue;
  83364. }
  83365. // Merge meshes
  83366. BABYLON.Mesh.MergeMeshes(currentPool);
  83367. }
  83368. if (updateSelectionTree != undefined) {
  83369. if (updateSelectionTree) {
  83370. scene.createOrUpdateSelectionOctree();
  83371. }
  83372. }
  83373. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  83374. scene.createOrUpdateSelectionOctree();
  83375. }
  83376. return true;
  83377. };
  83378. ;
  83379. MergeMeshesOptimization._UpdateSelectionTree = false;
  83380. return MergeMeshesOptimization;
  83381. }(SceneOptimization));
  83382. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  83383. /**
  83384. * Defines a list of options used by SceneOptimizer
  83385. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  83386. */
  83387. var SceneOptimizerOptions = /** @class */ (function () {
  83388. /**
  83389. * Creates a new list of options used by SceneOptimizer
  83390. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  83391. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  83392. */
  83393. function SceneOptimizerOptions(
  83394. /**
  83395. * Defines the target frame rate to reach (60 by default)
  83396. */
  83397. targetFrameRate,
  83398. /**
  83399. * Defines the interval between two checkes (2000ms by default)
  83400. */
  83401. trackerDuration) {
  83402. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  83403. if (trackerDuration === void 0) { trackerDuration = 2000; }
  83404. this.targetFrameRate = targetFrameRate;
  83405. this.trackerDuration = trackerDuration;
  83406. /**
  83407. * Gets the list of optimizations to apply
  83408. */
  83409. this.optimizations = new Array();
  83410. }
  83411. /**
  83412. * Add a new optimization
  83413. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  83414. * @returns the current SceneOptimizerOptions
  83415. */
  83416. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  83417. this.optimizations.push(optimization);
  83418. return this;
  83419. };
  83420. /**
  83421. * Add a new custom optimization
  83422. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  83423. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  83424. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  83425. * @returns the current SceneOptimizerOptions
  83426. */
  83427. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  83428. if (priority === void 0) { priority = 0; }
  83429. var optimization = new CustomOptimization(priority);
  83430. optimization.onApply = onApply;
  83431. optimization.onGetDescription = onGetDescription;
  83432. this.optimizations.push(optimization);
  83433. return this;
  83434. };
  83435. /**
  83436. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  83437. * @param targetFrameRate defines the target frame rate (60 by default)
  83438. * @returns a SceneOptimizerOptions object
  83439. */
  83440. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  83441. var result = new SceneOptimizerOptions(targetFrameRate);
  83442. var priority = 0;
  83443. result.addOptimization(new MergeMeshesOptimization(priority));
  83444. result.addOptimization(new ShadowsOptimization(priority));
  83445. result.addOptimization(new LensFlaresOptimization(priority));
  83446. // Next priority
  83447. priority++;
  83448. result.addOptimization(new PostProcessesOptimization(priority));
  83449. result.addOptimization(new ParticlesOptimization(priority));
  83450. // Next priority
  83451. priority++;
  83452. result.addOptimization(new TextureOptimization(priority, 1024));
  83453. return result;
  83454. };
  83455. /**
  83456. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  83457. * @param targetFrameRate defines the target frame rate (60 by default)
  83458. * @returns a SceneOptimizerOptions object
  83459. */
  83460. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  83461. var result = new SceneOptimizerOptions(targetFrameRate);
  83462. var priority = 0;
  83463. result.addOptimization(new MergeMeshesOptimization(priority));
  83464. result.addOptimization(new ShadowsOptimization(priority));
  83465. result.addOptimization(new LensFlaresOptimization(priority));
  83466. // Next priority
  83467. priority++;
  83468. result.addOptimization(new PostProcessesOptimization(priority));
  83469. result.addOptimization(new ParticlesOptimization(priority));
  83470. // Next priority
  83471. priority++;
  83472. result.addOptimization(new TextureOptimization(priority, 512));
  83473. // Next priority
  83474. priority++;
  83475. result.addOptimization(new RenderTargetsOptimization(priority));
  83476. // Next priority
  83477. priority++;
  83478. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  83479. return result;
  83480. };
  83481. /**
  83482. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  83483. * @param targetFrameRate defines the target frame rate (60 by default)
  83484. * @returns a SceneOptimizerOptions object
  83485. */
  83486. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  83487. var result = new SceneOptimizerOptions(targetFrameRate);
  83488. var priority = 0;
  83489. result.addOptimization(new MergeMeshesOptimization(priority));
  83490. result.addOptimization(new ShadowsOptimization(priority));
  83491. result.addOptimization(new LensFlaresOptimization(priority));
  83492. // Next priority
  83493. priority++;
  83494. result.addOptimization(new PostProcessesOptimization(priority));
  83495. result.addOptimization(new ParticlesOptimization(priority));
  83496. // Next priority
  83497. priority++;
  83498. result.addOptimization(new TextureOptimization(priority, 256));
  83499. // Next priority
  83500. priority++;
  83501. result.addOptimization(new RenderTargetsOptimization(priority));
  83502. // Next priority
  83503. priority++;
  83504. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  83505. return result;
  83506. };
  83507. return SceneOptimizerOptions;
  83508. }());
  83509. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  83510. /**
  83511. * Class used to run optimizations in order to reach a target frame rate
  83512. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  83513. */
  83514. var SceneOptimizer = /** @class */ (function () {
  83515. /**
  83516. * Creates a new SceneOptimizer
  83517. * @param scene defines the scene to work on
  83518. * @param options defines the options to use with the SceneOptimizer
  83519. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  83520. * @param improvementMode defines if the scene optimizer must run the maximum optimization while staying over a target frame instead of trying to reach the target framerate (false by default)
  83521. */
  83522. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  83523. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  83524. if (improvementMode === void 0) { improvementMode = false; }
  83525. var _this = this;
  83526. this._isRunning = false;
  83527. this._currentPriorityLevel = 0;
  83528. this._targetFrameRate = 60;
  83529. this._trackerDuration = 2000;
  83530. this._currentFrameRate = 0;
  83531. this._improvementMode = false;
  83532. /**
  83533. * Defines an observable called when the optimizer reaches the target frame rate
  83534. */
  83535. this.onSuccessObservable = new BABYLON.Observable();
  83536. /**
  83537. * Defines an observable called when the optimizer enables an optimization
  83538. */
  83539. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  83540. /**
  83541. * Defines an observable called when the optimizer is not able to reach the target frame rate
  83542. */
  83543. this.onFailureObservable = new BABYLON.Observable();
  83544. if (!options) {
  83545. this._options = new SceneOptimizerOptions();
  83546. }
  83547. else {
  83548. this._options = options;
  83549. }
  83550. if (this._options.targetFrameRate) {
  83551. this._targetFrameRate = this._options.targetFrameRate;
  83552. }
  83553. if (this._options.trackerDuration) {
  83554. this._trackerDuration = this._options.trackerDuration;
  83555. }
  83556. if (autoGeneratePriorities) {
  83557. var priority = 0;
  83558. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  83559. var optim = _a[_i];
  83560. optim.priority = priority++;
  83561. }
  83562. }
  83563. this._improvementMode = improvementMode;
  83564. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  83565. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  83566. _this._sceneDisposeObserver = null;
  83567. _this.dispose();
  83568. });
  83569. }
  83570. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  83571. /**
  83572. * Gets a boolean indicating if the optimizer is in improvement mode
  83573. */
  83574. get: function () {
  83575. return this._improvementMode;
  83576. },
  83577. enumerable: true,
  83578. configurable: true
  83579. });
  83580. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  83581. /**
  83582. * Gets the current priority level (0 at start)
  83583. */
  83584. get: function () {
  83585. return this._currentPriorityLevel;
  83586. },
  83587. enumerable: true,
  83588. configurable: true
  83589. });
  83590. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  83591. /**
  83592. * Gets the current frame rate checked by the SceneOptimizer
  83593. */
  83594. get: function () {
  83595. return this._currentFrameRate;
  83596. },
  83597. enumerable: true,
  83598. configurable: true
  83599. });
  83600. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  83601. /**
  83602. * Gets or sets the current target frame rate (60 by default)
  83603. */
  83604. get: function () {
  83605. return this._targetFrameRate;
  83606. },
  83607. /**
  83608. * Gets or sets the current target frame rate (60 by default)
  83609. */
  83610. set: function (value) {
  83611. this._targetFrameRate = value;
  83612. },
  83613. enumerable: true,
  83614. configurable: true
  83615. });
  83616. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  83617. /**
  83618. * Gets or sets the current interval between two checks (every 2000ms by default)
  83619. */
  83620. get: function () {
  83621. return this._trackerDuration;
  83622. },
  83623. /**
  83624. * Gets or sets the current interval between two checks (every 2000ms by default)
  83625. */
  83626. set: function (value) {
  83627. this._trackerDuration = value;
  83628. },
  83629. enumerable: true,
  83630. configurable: true
  83631. });
  83632. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  83633. /**
  83634. * Gets the list of active optimizations
  83635. */
  83636. get: function () {
  83637. return this._options.optimizations;
  83638. },
  83639. enumerable: true,
  83640. configurable: true
  83641. });
  83642. /**
  83643. * Stops the current optimizer
  83644. */
  83645. SceneOptimizer.prototype.stop = function () {
  83646. this._isRunning = false;
  83647. };
  83648. /**
  83649. * Reset the optimizer to initial step (current priority level = 0)
  83650. */
  83651. SceneOptimizer.prototype.reset = function () {
  83652. this._currentPriorityLevel = 0;
  83653. };
  83654. /**
  83655. * Start the optimizer. By default it will try to reach a specific framerate
  83656. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  83657. */
  83658. SceneOptimizer.prototype.start = function () {
  83659. var _this = this;
  83660. if (this._isRunning) {
  83661. return;
  83662. }
  83663. this._isRunning = true;
  83664. // Let's wait for the scene to be ready before running our check
  83665. this._scene.executeWhenReady(function () {
  83666. setTimeout(function () {
  83667. _this._checkCurrentState();
  83668. }, _this._trackerDuration);
  83669. });
  83670. };
  83671. SceneOptimizer.prototype._checkCurrentState = function () {
  83672. var _this = this;
  83673. if (!this._isRunning) {
  83674. return;
  83675. }
  83676. var scene = this._scene;
  83677. var options = this._options;
  83678. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  83679. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  83680. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  83681. this._isRunning = false;
  83682. this.onSuccessObservable.notifyObservers(this);
  83683. return;
  83684. }
  83685. // Apply current level of optimizations
  83686. var allDone = true;
  83687. var noOptimizationApplied = true;
  83688. for (var index = 0; index < options.optimizations.length; index++) {
  83689. var optimization = options.optimizations[index];
  83690. if (optimization.priority === this._currentPriorityLevel) {
  83691. noOptimizationApplied = false;
  83692. allDone = allDone && optimization.apply(scene, this);
  83693. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  83694. }
  83695. }
  83696. // If no optimization was applied, this is a failure :(
  83697. if (noOptimizationApplied) {
  83698. this._isRunning = false;
  83699. this.onFailureObservable.notifyObservers(this);
  83700. return;
  83701. }
  83702. // If all optimizations were done, move to next level
  83703. if (allDone) {
  83704. this._currentPriorityLevel++;
  83705. }
  83706. // Let's the system running for a specific amount of time before checking FPS
  83707. scene.executeWhenReady(function () {
  83708. setTimeout(function () {
  83709. _this._checkCurrentState();
  83710. }, _this._trackerDuration);
  83711. });
  83712. };
  83713. /**
  83714. * Release all resources
  83715. */
  83716. SceneOptimizer.prototype.dispose = function () {
  83717. this.stop();
  83718. this.onSuccessObservable.clear();
  83719. this.onFailureObservable.clear();
  83720. this.onNewOptimizationAppliedObservable.clear();
  83721. if (this._sceneDisposeObserver) {
  83722. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  83723. }
  83724. };
  83725. /**
  83726. * Helper function to create a SceneOptimizer with one single line of code
  83727. * @param scene defines the scene to work on
  83728. * @param options defines the options to use with the SceneOptimizer
  83729. * @param onSuccess defines a callback to call on success
  83730. * @param onFailure defines a callback to call on failure
  83731. * @returns the new SceneOptimizer object
  83732. */
  83733. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  83734. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  83735. if (onSuccess) {
  83736. optimizer.onSuccessObservable.add(function () {
  83737. onSuccess();
  83738. });
  83739. }
  83740. if (onFailure) {
  83741. optimizer.onFailureObservable.add(function () {
  83742. onFailure();
  83743. });
  83744. }
  83745. optimizer.start();
  83746. return optimizer;
  83747. };
  83748. return SceneOptimizer;
  83749. }());
  83750. BABYLON.SceneOptimizer = SceneOptimizer;
  83751. })(BABYLON || (BABYLON = {}));
  83752. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  83753. var BABYLON;
  83754. (function (BABYLON) {
  83755. var OutlineRenderer = /** @class */ (function () {
  83756. function OutlineRenderer(scene) {
  83757. this.zOffset = 1;
  83758. this._scene = scene;
  83759. }
  83760. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  83761. var _this = this;
  83762. if (useOverlay === void 0) { useOverlay = false; }
  83763. var scene = this._scene;
  83764. var engine = this._scene.getEngine();
  83765. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  83766. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  83767. return;
  83768. }
  83769. var mesh = subMesh.getRenderingMesh();
  83770. var material = subMesh.getMaterial();
  83771. if (!material || !scene.activeCamera) {
  83772. return;
  83773. }
  83774. engine.enableEffect(this._effect);
  83775. // Logarithmic depth
  83776. if (material.useLogarithmicDepth) {
  83777. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  83778. }
  83779. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  83780. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  83781. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  83782. // Bones
  83783. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  83784. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  83785. }
  83786. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  83787. // Alpha test
  83788. if (material && material.needAlphaTesting()) {
  83789. var alphaTexture = material.getAlphaTestTexture();
  83790. if (alphaTexture) {
  83791. this._effect.setTexture("diffuseSampler", alphaTexture);
  83792. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  83793. }
  83794. }
  83795. engine.setZOffset(-this.zOffset);
  83796. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  83797. engine.setZOffset(0);
  83798. };
  83799. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  83800. var defines = [];
  83801. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  83802. var mesh = subMesh.getMesh();
  83803. var material = subMesh.getMaterial();
  83804. if (material) {
  83805. // Alpha test
  83806. if (material.needAlphaTesting()) {
  83807. defines.push("#define ALPHATEST");
  83808. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  83809. attribs.push(BABYLON.VertexBuffer.UVKind);
  83810. defines.push("#define UV1");
  83811. }
  83812. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  83813. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  83814. defines.push("#define UV2");
  83815. }
  83816. }
  83817. //Logarithmic depth
  83818. if (material.useLogarithmicDepth) {
  83819. defines.push("#define LOGARITHMICDEPTH");
  83820. }
  83821. }
  83822. // Bones
  83823. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  83824. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  83825. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  83826. if (mesh.numBoneInfluencers > 4) {
  83827. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  83828. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  83829. }
  83830. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  83831. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  83832. }
  83833. else {
  83834. defines.push("#define NUM_BONE_INFLUENCERS 0");
  83835. }
  83836. // Instances
  83837. if (useInstances) {
  83838. defines.push("#define INSTANCES");
  83839. attribs.push("world0");
  83840. attribs.push("world1");
  83841. attribs.push("world2");
  83842. attribs.push("world3");
  83843. }
  83844. // Get correct effect
  83845. var join = defines.join("\n");
  83846. if (this._cachedDefines !== join) {
  83847. this._cachedDefines = join;
  83848. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  83849. }
  83850. return this._effect.isReady();
  83851. };
  83852. return OutlineRenderer;
  83853. }());
  83854. BABYLON.OutlineRenderer = OutlineRenderer;
  83855. })(BABYLON || (BABYLON = {}));
  83856. //# sourceMappingURL=babylon.outlineRenderer.js.map
  83857. var BABYLON;
  83858. (function (BABYLON) {
  83859. var FaceAdjacencies = /** @class */ (function () {
  83860. function FaceAdjacencies() {
  83861. this.edges = new Array();
  83862. this.edgesConnectedCount = 0;
  83863. }
  83864. return FaceAdjacencies;
  83865. }());
  83866. var EdgesRenderer = /** @class */ (function () {
  83867. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  83868. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  83869. if (epsilon === void 0) { epsilon = 0.95; }
  83870. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  83871. this.edgesWidthScalerForOrthographic = 1000.0;
  83872. this.edgesWidthScalerForPerspective = 50.0;
  83873. this._linesPositions = new Array();
  83874. this._linesNormals = new Array();
  83875. this._linesIndices = new Array();
  83876. this._buffers = {};
  83877. this._checkVerticesInsteadOfIndices = false;
  83878. this._source = source;
  83879. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  83880. this._epsilon = epsilon;
  83881. this._prepareRessources();
  83882. this._generateEdgesLines();
  83883. }
  83884. EdgesRenderer.prototype._prepareRessources = function () {
  83885. if (this._lineShader) {
  83886. return;
  83887. }
  83888. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  83889. attributes: ["position", "normal"],
  83890. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  83891. });
  83892. this._lineShader.disableDepthWrite = true;
  83893. this._lineShader.backFaceCulling = false;
  83894. };
  83895. EdgesRenderer.prototype._rebuild = function () {
  83896. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  83897. if (buffer) {
  83898. buffer._rebuild();
  83899. }
  83900. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  83901. if (buffer) {
  83902. buffer._rebuild();
  83903. }
  83904. var scene = this._source.getScene();
  83905. var engine = scene.getEngine();
  83906. this._ib = engine.createIndexBuffer(this._linesIndices);
  83907. };
  83908. EdgesRenderer.prototype.dispose = function () {
  83909. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  83910. if (buffer) {
  83911. buffer.dispose();
  83912. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  83913. }
  83914. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  83915. if (buffer) {
  83916. buffer.dispose();
  83917. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  83918. }
  83919. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  83920. this._lineShader.dispose();
  83921. };
  83922. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  83923. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  83924. return 0;
  83925. }
  83926. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  83927. return 1;
  83928. }
  83929. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  83930. return 2;
  83931. }
  83932. return -1;
  83933. };
  83934. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  83935. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  83936. return 0;
  83937. }
  83938. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  83939. return 1;
  83940. }
  83941. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  83942. return 2;
  83943. }
  83944. return -1;
  83945. };
  83946. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  83947. var needToCreateLine;
  83948. if (edge === undefined) {
  83949. needToCreateLine = true;
  83950. }
  83951. else {
  83952. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  83953. needToCreateLine = dotProduct < this._epsilon;
  83954. }
  83955. if (needToCreateLine) {
  83956. var offset = this._linesPositions.length / 3;
  83957. var normal = p0.subtract(p1);
  83958. normal.normalize();
  83959. // Positions
  83960. this._linesPositions.push(p0.x);
  83961. this._linesPositions.push(p0.y);
  83962. this._linesPositions.push(p0.z);
  83963. this._linesPositions.push(p0.x);
  83964. this._linesPositions.push(p0.y);
  83965. this._linesPositions.push(p0.z);
  83966. this._linesPositions.push(p1.x);
  83967. this._linesPositions.push(p1.y);
  83968. this._linesPositions.push(p1.z);
  83969. this._linesPositions.push(p1.x);
  83970. this._linesPositions.push(p1.y);
  83971. this._linesPositions.push(p1.z);
  83972. // Normals
  83973. this._linesNormals.push(p1.x);
  83974. this._linesNormals.push(p1.y);
  83975. this._linesNormals.push(p1.z);
  83976. this._linesNormals.push(-1);
  83977. this._linesNormals.push(p1.x);
  83978. this._linesNormals.push(p1.y);
  83979. this._linesNormals.push(p1.z);
  83980. this._linesNormals.push(1);
  83981. this._linesNormals.push(p0.x);
  83982. this._linesNormals.push(p0.y);
  83983. this._linesNormals.push(p0.z);
  83984. this._linesNormals.push(-1);
  83985. this._linesNormals.push(p0.x);
  83986. this._linesNormals.push(p0.y);
  83987. this._linesNormals.push(p0.z);
  83988. this._linesNormals.push(1);
  83989. // Indices
  83990. this._linesIndices.push(offset);
  83991. this._linesIndices.push(offset + 1);
  83992. this._linesIndices.push(offset + 2);
  83993. this._linesIndices.push(offset);
  83994. this._linesIndices.push(offset + 2);
  83995. this._linesIndices.push(offset + 3);
  83996. }
  83997. };
  83998. EdgesRenderer.prototype._generateEdgesLines = function () {
  83999. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  84000. var indices = this._source.getIndices();
  84001. if (!indices || !positions) {
  84002. return;
  84003. }
  84004. // First let's find adjacencies
  84005. var adjacencies = new Array();
  84006. var faceNormals = new Array();
  84007. var index;
  84008. var faceAdjacencies;
  84009. // Prepare faces
  84010. for (index = 0; index < indices.length; index += 3) {
  84011. faceAdjacencies = new FaceAdjacencies();
  84012. var p0Index = indices[index];
  84013. var p1Index = indices[index + 1];
  84014. var p2Index = indices[index + 2];
  84015. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  84016. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  84017. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  84018. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  84019. faceNormal.normalize();
  84020. faceNormals.push(faceNormal);
  84021. adjacencies.push(faceAdjacencies);
  84022. }
  84023. // Scan
  84024. for (index = 0; index < adjacencies.length; index++) {
  84025. faceAdjacencies = adjacencies[index];
  84026. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  84027. var otherFaceAdjacencies = adjacencies[otherIndex];
  84028. if (faceAdjacencies.edgesConnectedCount === 3) {
  84029. break;
  84030. }
  84031. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  84032. continue;
  84033. }
  84034. var otherP0 = indices[otherIndex * 3];
  84035. var otherP1 = indices[otherIndex * 3 + 1];
  84036. var otherP2 = indices[otherIndex * 3 + 2];
  84037. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  84038. var otherEdgeIndex = 0;
  84039. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  84040. continue;
  84041. }
  84042. switch (edgeIndex) {
  84043. case 0:
  84044. if (this._checkVerticesInsteadOfIndices) {
  84045. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  84046. }
  84047. else {
  84048. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  84049. }
  84050. break;
  84051. case 1:
  84052. if (this._checkVerticesInsteadOfIndices) {
  84053. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  84054. }
  84055. else {
  84056. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  84057. }
  84058. break;
  84059. case 2:
  84060. if (this._checkVerticesInsteadOfIndices) {
  84061. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  84062. }
  84063. else {
  84064. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  84065. }
  84066. break;
  84067. }
  84068. if (otherEdgeIndex === -1) {
  84069. continue;
  84070. }
  84071. faceAdjacencies.edges[edgeIndex] = otherIndex;
  84072. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  84073. faceAdjacencies.edgesConnectedCount++;
  84074. otherFaceAdjacencies.edgesConnectedCount++;
  84075. if (faceAdjacencies.edgesConnectedCount === 3) {
  84076. break;
  84077. }
  84078. }
  84079. }
  84080. }
  84081. // Create lines
  84082. for (index = 0; index < adjacencies.length; index++) {
  84083. // 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
  84084. var current = adjacencies[index];
  84085. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  84086. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  84087. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  84088. }
  84089. // Merge into a single mesh
  84090. var engine = this._source.getScene().getEngine();
  84091. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  84092. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  84093. this._ib = engine.createIndexBuffer(this._linesIndices);
  84094. this._indicesCount = this._linesIndices.length;
  84095. };
  84096. EdgesRenderer.prototype.render = function () {
  84097. var scene = this._source.getScene();
  84098. if (!this._lineShader.isReady() || !scene.activeCamera) {
  84099. return;
  84100. }
  84101. var engine = scene.getEngine();
  84102. this._lineShader._preBind();
  84103. // VBOs
  84104. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  84105. scene.resetCachedMaterial();
  84106. this._lineShader.setColor4("color", this._source.edgesColor);
  84107. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  84108. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  84109. }
  84110. else {
  84111. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  84112. }
  84113. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  84114. this._lineShader.bind(this._source.getWorldMatrix());
  84115. // Draw order
  84116. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  84117. this._lineShader.unbind();
  84118. engine.setDepthWrite(true);
  84119. };
  84120. return EdgesRenderer;
  84121. }());
  84122. BABYLON.EdgesRenderer = EdgesRenderer;
  84123. })(BABYLON || (BABYLON = {}));
  84124. //# sourceMappingURL=babylon.edgesRenderer.js.map
  84125. var __assign = (this && this.__assign) || Object.assign || function(t) {
  84126. for (var s, i = 1, n = arguments.length; i < n; i++) {
  84127. s = arguments[i];
  84128. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  84129. t[p] = s[p];
  84130. }
  84131. return t;
  84132. };
  84133. var BABYLON;
  84134. (function (BABYLON) {
  84135. /**
  84136. * The effect layer Helps adding post process effect blended with the main pass.
  84137. *
  84138. * This can be for instance use to generate glow or higlight effects on the scene.
  84139. *
  84140. * The effect layer class can not be used directly and is intented to inherited from to be
  84141. * customized per effects.
  84142. */
  84143. var EffectLayer = /** @class */ (function () {
  84144. /**
  84145. * Instantiates a new effect Layer and references it in the scene.
  84146. * @param name The name of the layer
  84147. * @param scene The scene to use the layer in
  84148. */
  84149. function EffectLayer(
  84150. /** The Friendly of the effect in the scene */
  84151. name, scene) {
  84152. this.name = name;
  84153. this._vertexBuffers = {};
  84154. this._maxSize = 0;
  84155. this._mainTextureDesiredSize = { width: 0, height: 0 };
  84156. this._shouldRender = true;
  84157. this._postProcesses = [];
  84158. this._textures = [];
  84159. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  84160. /**
  84161. * The clear color of the texture used to generate the glow map.
  84162. */
  84163. this.neutralColor = new BABYLON.Color4();
  84164. /**
  84165. * Specifies wether the highlight layer is enabled or not.
  84166. */
  84167. this.isEnabled = true;
  84168. /**
  84169. * An event triggered when the effect layer has been disposed.
  84170. */
  84171. this.onDisposeObservable = new BABYLON.Observable();
  84172. /**
  84173. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  84174. */
  84175. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  84176. /**
  84177. * An event triggered when the generated texture is being merged in the scene.
  84178. */
  84179. this.onBeforeComposeObservable = new BABYLON.Observable();
  84180. /**
  84181. * An event triggered when the generated texture has been merged in the scene.
  84182. */
  84183. this.onAfterComposeObservable = new BABYLON.Observable();
  84184. /**
  84185. * An event triggered when the efffect layer changes its size.
  84186. */
  84187. this.onSizeChangedObservable = new BABYLON.Observable();
  84188. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  84189. this._engine = scene.getEngine();
  84190. this._maxSize = this._engine.getCaps().maxTextureSize;
  84191. this._scene.effectLayers.push(this);
  84192. // Generate Buffers
  84193. this._generateIndexBuffer();
  84194. this._genrateVertexBuffer();
  84195. }
  84196. Object.defineProperty(EffectLayer.prototype, "camera", {
  84197. /**
  84198. * Gets the camera attached to the layer.
  84199. */
  84200. get: function () {
  84201. return this._effectLayerOptions.camera;
  84202. },
  84203. enumerable: true,
  84204. configurable: true
  84205. });
  84206. /**
  84207. * Initializes the effect layer with the required options.
  84208. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  84209. */
  84210. EffectLayer.prototype._init = function (options) {
  84211. // Adapt options
  84212. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  84213. this._setMainTextureSize();
  84214. this._createMainTexture();
  84215. this._createTextureAndPostProcesses();
  84216. this._mergeEffect = this._createMergeEffect();
  84217. };
  84218. /**
  84219. * Generates the index buffer of the full screen quad blending to the main canvas.
  84220. */
  84221. EffectLayer.prototype._generateIndexBuffer = function () {
  84222. // Indices
  84223. var indices = [];
  84224. indices.push(0);
  84225. indices.push(1);
  84226. indices.push(2);
  84227. indices.push(0);
  84228. indices.push(2);
  84229. indices.push(3);
  84230. this._indexBuffer = this._engine.createIndexBuffer(indices);
  84231. };
  84232. /**
  84233. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  84234. */
  84235. EffectLayer.prototype._genrateVertexBuffer = function () {
  84236. // VBO
  84237. var vertices = [];
  84238. vertices.push(1, 1);
  84239. vertices.push(-1, 1);
  84240. vertices.push(-1, -1);
  84241. vertices.push(1, -1);
  84242. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  84243. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  84244. };
  84245. /**
  84246. * Sets the main texture desired size which is the closest power of two
  84247. * of the engine canvas size.
  84248. */
  84249. EffectLayer.prototype._setMainTextureSize = function () {
  84250. if (this._effectLayerOptions.mainTextureFixedSize) {
  84251. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  84252. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  84253. }
  84254. else {
  84255. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  84256. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  84257. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  84258. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  84259. }
  84260. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  84261. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  84262. };
  84263. /**
  84264. * Creates the main texture for the effect layer.
  84265. */
  84266. EffectLayer.prototype._createMainTexture = function () {
  84267. var _this = this;
  84268. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  84269. width: this._mainTextureDesiredSize.width,
  84270. height: this._mainTextureDesiredSize.height
  84271. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  84272. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  84273. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84274. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84275. this._mainTexture.anisotropicFilteringLevel = 1;
  84276. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  84277. this._mainTexture.renderParticles = false;
  84278. this._mainTexture.renderList = null;
  84279. this._mainTexture.ignoreCameraViewport = true;
  84280. // Custom render function
  84281. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  84282. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  84283. var index;
  84284. var engine = _this._scene.getEngine();
  84285. if (depthOnlySubMeshes.length) {
  84286. engine.setColorWrite(false);
  84287. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  84288. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  84289. }
  84290. engine.setColorWrite(true);
  84291. }
  84292. for (index = 0; index < opaqueSubMeshes.length; index++) {
  84293. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  84294. }
  84295. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  84296. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  84297. }
  84298. for (index = 0; index < transparentSubMeshes.length; index++) {
  84299. _this._renderSubMesh(transparentSubMeshes.data[index]);
  84300. }
  84301. };
  84302. this._mainTexture.onClearObservable.add(function (engine) {
  84303. engine.clear(_this.neutralColor, true, true, true);
  84304. });
  84305. };
  84306. /**
  84307. * Checks for the readiness of the element composing the layer.
  84308. * @param subMesh the mesh to check for
  84309. * @param useInstances specify wether or not to use instances to render the mesh
  84310. * @param emissiveTexture the associated emissive texture used to generate the glow
  84311. * @return true if ready otherwise, false
  84312. */
  84313. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  84314. var material = subMesh.getMaterial();
  84315. if (!material) {
  84316. return false;
  84317. }
  84318. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  84319. return false;
  84320. }
  84321. var defines = [];
  84322. var attribs = [BABYLON.VertexBuffer.PositionKind];
  84323. var mesh = subMesh.getMesh();
  84324. var uv1 = false;
  84325. var uv2 = false;
  84326. // Alpha test
  84327. if (material && material.needAlphaTesting()) {
  84328. var alphaTexture = material.getAlphaTestTexture();
  84329. if (alphaTexture) {
  84330. defines.push("#define ALPHATEST");
  84331. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  84332. alphaTexture.coordinatesIndex === 1) {
  84333. defines.push("#define DIFFUSEUV2");
  84334. uv2 = true;
  84335. }
  84336. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  84337. defines.push("#define DIFFUSEUV1");
  84338. uv1 = true;
  84339. }
  84340. }
  84341. }
  84342. // Emissive
  84343. if (emissiveTexture) {
  84344. defines.push("#define EMISSIVE");
  84345. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  84346. emissiveTexture.coordinatesIndex === 1) {
  84347. defines.push("#define EMISSIVEUV2");
  84348. uv2 = true;
  84349. }
  84350. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  84351. defines.push("#define EMISSIVEUV1");
  84352. uv1 = true;
  84353. }
  84354. }
  84355. if (uv1) {
  84356. attribs.push(BABYLON.VertexBuffer.UVKind);
  84357. defines.push("#define UV1");
  84358. }
  84359. if (uv2) {
  84360. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  84361. defines.push("#define UV2");
  84362. }
  84363. // Bones
  84364. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  84365. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  84366. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  84367. if (mesh.numBoneInfluencers > 4) {
  84368. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  84369. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  84370. }
  84371. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  84372. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  84373. }
  84374. else {
  84375. defines.push("#define NUM_BONE_INFLUENCERS 0");
  84376. }
  84377. // Instances
  84378. if (useInstances) {
  84379. defines.push("#define INSTANCES");
  84380. attribs.push("world0");
  84381. attribs.push("world1");
  84382. attribs.push("world2");
  84383. attribs.push("world3");
  84384. }
  84385. // Get correct effect
  84386. var join = defines.join("\n");
  84387. if (this._cachedDefines !== join) {
  84388. this._cachedDefines = join;
  84389. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  84390. }
  84391. return this._effectLayerMapGenerationEffect.isReady();
  84392. };
  84393. /**
  84394. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  84395. */
  84396. EffectLayer.prototype.render = function () {
  84397. var currentEffect = this._mergeEffect;
  84398. // Check
  84399. if (!currentEffect.isReady())
  84400. return;
  84401. for (var i = 0; i < this._postProcesses.length; i++) {
  84402. if (!this._postProcesses[i].isReady()) {
  84403. return;
  84404. }
  84405. }
  84406. var engine = this._scene.getEngine();
  84407. this.onBeforeComposeObservable.notifyObservers(this);
  84408. // Render
  84409. engine.enableEffect(currentEffect);
  84410. engine.setState(false);
  84411. // VBOs
  84412. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  84413. // Cache
  84414. var previousAlphaMode = engine.getAlphaMode();
  84415. // Go Blend.
  84416. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  84417. // Blends the map on the main canvas.
  84418. this._internalRender(currentEffect);
  84419. // Restore Alpha
  84420. engine.setAlphaMode(previousAlphaMode);
  84421. this.onAfterComposeObservable.notifyObservers(this);
  84422. // Handle size changes.
  84423. var size = this._mainTexture.getSize();
  84424. this._setMainTextureSize();
  84425. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  84426. // Recreate RTT and post processes on size change.
  84427. this.onSizeChangedObservable.notifyObservers(this);
  84428. this._disposeTextureAndPostProcesses();
  84429. this._createMainTexture();
  84430. this._createTextureAndPostProcesses();
  84431. }
  84432. };
  84433. /**
  84434. * Determine if a given mesh will be used in the current effect.
  84435. * @param mesh mesh to test
  84436. * @returns true if the mesh will be used
  84437. */
  84438. EffectLayer.prototype.hasMesh = function (mesh) {
  84439. return true;
  84440. };
  84441. /**
  84442. * Returns true if the layer contains information to display, otherwise false.
  84443. * @returns true if the glow layer should be rendered
  84444. */
  84445. EffectLayer.prototype.shouldRender = function () {
  84446. return this.isEnabled && this._shouldRender;
  84447. };
  84448. /**
  84449. * Returns true if the mesh should render, otherwise false.
  84450. * @param mesh The mesh to render
  84451. * @returns true if it should render otherwise false
  84452. */
  84453. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  84454. return true;
  84455. };
  84456. /**
  84457. * Returns true if the mesh should render, otherwise false.
  84458. * @param mesh The mesh to render
  84459. * @returns true if it should render otherwise false
  84460. */
  84461. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  84462. return true;
  84463. };
  84464. /**
  84465. * Renders the submesh passed in parameter to the generation map.
  84466. */
  84467. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  84468. var _this = this;
  84469. if (!this.shouldRender()) {
  84470. return;
  84471. }
  84472. var material = subMesh.getMaterial();
  84473. var mesh = subMesh.getRenderingMesh();
  84474. var scene = this._scene;
  84475. var engine = scene.getEngine();
  84476. if (!material) {
  84477. return;
  84478. }
  84479. // Do not block in blend mode.
  84480. if (material.needAlphaBlendingForMesh(mesh)) {
  84481. return;
  84482. }
  84483. // Culling
  84484. engine.setState(material.backFaceCulling);
  84485. // Managing instances
  84486. var batch = mesh._getInstancesRenderList(subMesh._id);
  84487. if (batch.mustReturn) {
  84488. return;
  84489. }
  84490. // Early Exit per mesh
  84491. if (!this._shouldRenderMesh(mesh)) {
  84492. return;
  84493. }
  84494. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  84495. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  84496. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  84497. engine.enableEffect(this._effectLayerMapGenerationEffect);
  84498. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  84499. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  84500. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  84501. // Alpha test
  84502. if (material && material.needAlphaTesting()) {
  84503. var alphaTexture = material.getAlphaTestTexture();
  84504. if (alphaTexture) {
  84505. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  84506. var textureMatrix = alphaTexture.getTextureMatrix();
  84507. if (textureMatrix) {
  84508. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  84509. }
  84510. }
  84511. }
  84512. // Glow emissive only
  84513. if (this._emissiveTextureAndColor.texture) {
  84514. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  84515. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  84516. }
  84517. // Bones
  84518. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  84519. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  84520. }
  84521. // Draw
  84522. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  84523. }
  84524. else {
  84525. // Need to reset refresh rate of the shadowMap
  84526. this._mainTexture.resetRefreshCounter();
  84527. }
  84528. };
  84529. /**
  84530. * Rebuild the required buffers.
  84531. * @ignore Internal use only.
  84532. */
  84533. EffectLayer.prototype._rebuild = function () {
  84534. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  84535. if (vb) {
  84536. vb._rebuild();
  84537. }
  84538. this._generateIndexBuffer();
  84539. };
  84540. /**
  84541. * Dispose only the render target textures and post process.
  84542. */
  84543. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  84544. this._mainTexture.dispose();
  84545. for (var i = 0; i < this._postProcesses.length; i++) {
  84546. if (this._postProcesses[i]) {
  84547. this._postProcesses[i].dispose();
  84548. }
  84549. }
  84550. this._postProcesses = [];
  84551. for (var i = 0; i < this._textures.length; i++) {
  84552. if (this._textures[i]) {
  84553. this._textures[i].dispose();
  84554. }
  84555. }
  84556. this._textures = [];
  84557. };
  84558. /**
  84559. * Dispose the highlight layer and free resources.
  84560. */
  84561. EffectLayer.prototype.dispose = function () {
  84562. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  84563. if (vertexBuffer) {
  84564. vertexBuffer.dispose();
  84565. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  84566. }
  84567. if (this._indexBuffer) {
  84568. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  84569. this._indexBuffer = null;
  84570. }
  84571. // Clean textures and post processes
  84572. this._disposeTextureAndPostProcesses();
  84573. // Remove from scene
  84574. var index = this._scene.effectLayers.indexOf(this, 0);
  84575. if (index > -1) {
  84576. this._scene.effectLayers.splice(index, 1);
  84577. }
  84578. // Callback
  84579. this.onDisposeObservable.notifyObservers(this);
  84580. this.onDisposeObservable.clear();
  84581. this.onBeforeRenderMainTextureObservable.clear();
  84582. this.onBeforeComposeObservable.clear();
  84583. this.onAfterComposeObservable.clear();
  84584. this.onSizeChangedObservable.clear();
  84585. };
  84586. return EffectLayer;
  84587. }());
  84588. BABYLON.EffectLayer = EffectLayer;
  84589. })(BABYLON || (BABYLON = {}));
  84590. //# sourceMappingURL=babylon.effectLayer.js.map
  84591. var BABYLON;
  84592. (function (BABYLON) {
  84593. /**
  84594. * Special Glow Blur post process only blurring the alpha channel
  84595. * It enforces keeping the most luminous color in the color channel.
  84596. */
  84597. var GlowBlurPostProcess = /** @class */ (function (_super) {
  84598. __extends(GlowBlurPostProcess, _super);
  84599. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  84600. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  84601. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  84602. _this.direction = direction;
  84603. _this.kernel = kernel;
  84604. _this.onApplyObservable.add(function (effect) {
  84605. effect.setFloat2("screenSize", _this.width, _this.height);
  84606. effect.setVector2("direction", _this.direction);
  84607. effect.setFloat("blurWidth", _this.kernel);
  84608. });
  84609. return _this;
  84610. }
  84611. return GlowBlurPostProcess;
  84612. }(BABYLON.PostProcess));
  84613. /**
  84614. * The highlight layer Helps adding a glow effect around a mesh.
  84615. *
  84616. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  84617. * glowy meshes to your scene.
  84618. *
  84619. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  84620. */
  84621. var HighlightLayer = /** @class */ (function (_super) {
  84622. __extends(HighlightLayer, _super);
  84623. /**
  84624. * Instantiates a new highlight Layer and references it to the scene..
  84625. * @param name The name of the layer
  84626. * @param scene The scene to use the layer in
  84627. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  84628. */
  84629. function HighlightLayer(name, scene, options) {
  84630. var _this = _super.call(this, name, scene) || this;
  84631. _this.name = name;
  84632. /**
  84633. * Specifies whether or not the inner glow is ACTIVE in the layer.
  84634. */
  84635. _this.innerGlow = true;
  84636. /**
  84637. * Specifies whether or not the outer glow is ACTIVE in the layer.
  84638. */
  84639. _this.outerGlow = true;
  84640. /**
  84641. * An event triggered when the highlight layer is being blurred.
  84642. */
  84643. _this.onBeforeBlurObservable = new BABYLON.Observable();
  84644. /**
  84645. * An event triggered when the highlight layer has been blurred.
  84646. */
  84647. _this.onAfterBlurObservable = new BABYLON.Observable();
  84648. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  84649. _this._meshes = {};
  84650. _this._excludedMeshes = {};
  84651. _this.neutralColor = HighlightLayer.NeutralColor;
  84652. // Warn on stencil
  84653. if (!_this._engine.isStencilEnable) {
  84654. 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 }");
  84655. }
  84656. // Adapt options
  84657. _this._options = __assign({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  84658. // Initialize the layer
  84659. _this._init({
  84660. alphaBlendingMode: _this._options.alphaBlendingMode,
  84661. camera: _this._options.camera,
  84662. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  84663. mainTextureRatio: _this._options.mainTextureRatio
  84664. });
  84665. // Do not render as long as no meshes have been added
  84666. _this._shouldRender = false;
  84667. return _this;
  84668. }
  84669. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  84670. /**
  84671. * Gets the horizontal size of the blur.
  84672. */
  84673. get: function () {
  84674. return this._horizontalBlurPostprocess.kernel;
  84675. },
  84676. /**
  84677. * Specifies the horizontal size of the blur.
  84678. */
  84679. set: function (value) {
  84680. this._horizontalBlurPostprocess.kernel = value;
  84681. },
  84682. enumerable: true,
  84683. configurable: true
  84684. });
  84685. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  84686. /**
  84687. * Gets the vertical size of the blur.
  84688. */
  84689. get: function () {
  84690. return this._verticalBlurPostprocess.kernel;
  84691. },
  84692. /**
  84693. * Specifies the vertical size of the blur.
  84694. */
  84695. set: function (value) {
  84696. this._verticalBlurPostprocess.kernel = value;
  84697. },
  84698. enumerable: true,
  84699. configurable: true
  84700. });
  84701. /**
  84702. * Get the effect name of the layer.
  84703. * @return The effect name
  84704. */
  84705. HighlightLayer.prototype.getEffectName = function () {
  84706. return HighlightLayer.EffectName;
  84707. };
  84708. /**
  84709. * Create the merge effect. This is the shader use to blit the information back
  84710. * to the main canvas at the end of the scene rendering.
  84711. */
  84712. HighlightLayer.prototype._createMergeEffect = function () {
  84713. // Effect
  84714. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  84715. };
  84716. /**
  84717. * Creates the render target textures and post processes used in the highlight layer.
  84718. */
  84719. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  84720. var _this = this;
  84721. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  84722. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  84723. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  84724. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  84725. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  84726. width: blurTextureWidth,
  84727. height: blurTextureHeight
  84728. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  84729. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84730. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84731. this._blurTexture.anisotropicFilteringLevel = 16;
  84732. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  84733. this._blurTexture.renderParticles = false;
  84734. this._blurTexture.ignoreCameraViewport = true;
  84735. this._textures = [this._blurTexture];
  84736. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  84737. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  84738. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  84739. effect.setTexture("textureSampler", _this._mainTexture);
  84740. });
  84741. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  84742. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  84743. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  84744. });
  84745. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  84746. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  84747. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  84748. });
  84749. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  84750. }
  84751. else {
  84752. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  84753. width: blurTextureWidth,
  84754. height: blurTextureHeight
  84755. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  84756. this._horizontalBlurPostprocess.width = blurTextureWidth;
  84757. this._horizontalBlurPostprocess.height = blurTextureHeight;
  84758. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  84759. effect.setTexture("textureSampler", _this._mainTexture);
  84760. });
  84761. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  84762. width: blurTextureWidth,
  84763. height: blurTextureHeight
  84764. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  84765. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  84766. }
  84767. this._mainTexture.onAfterUnbindObservable.add(function () {
  84768. _this.onBeforeBlurObservable.notifyObservers(_this);
  84769. var internalTexture = _this._blurTexture.getInternalTexture();
  84770. if (internalTexture) {
  84771. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  84772. }
  84773. _this.onAfterBlurObservable.notifyObservers(_this);
  84774. });
  84775. // Prevent autoClear.
  84776. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  84777. };
  84778. /**
  84779. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  84780. */
  84781. HighlightLayer.prototype.needStencil = function () {
  84782. return true;
  84783. };
  84784. /**
  84785. * Checks for the readiness of the element composing the layer.
  84786. * @param subMesh the mesh to check for
  84787. * @param useInstances specify wether or not to use instances to render the mesh
  84788. * @param emissiveTexture the associated emissive texture used to generate the glow
  84789. * @return true if ready otherwise, false
  84790. */
  84791. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  84792. var material = subMesh.getMaterial();
  84793. var mesh = subMesh.getRenderingMesh();
  84794. if (!material || !mesh || !this._meshes) {
  84795. return false;
  84796. }
  84797. var emissiveTexture = null;
  84798. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  84799. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  84800. emissiveTexture = material.emissiveTexture;
  84801. }
  84802. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  84803. };
  84804. /**
  84805. * Implementation specific of rendering the generating effect on the main canvas.
  84806. * @param effect The effect used to render through
  84807. */
  84808. HighlightLayer.prototype._internalRender = function (effect) {
  84809. // Texture
  84810. effect.setTexture("textureSampler", this._blurTexture);
  84811. // Cache
  84812. var engine = this._engine;
  84813. var previousStencilBuffer = engine.getStencilBuffer();
  84814. var previousStencilFunction = engine.getStencilFunction();
  84815. var previousStencilMask = engine.getStencilMask();
  84816. var previousStencilOperationPass = engine.getStencilOperationPass();
  84817. var previousStencilOperationFail = engine.getStencilOperationFail();
  84818. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  84819. var previousStencilReference = engine.getStencilFunctionReference();
  84820. // Stencil operations
  84821. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  84822. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  84823. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  84824. // Draw order
  84825. engine.setStencilMask(0x00);
  84826. engine.setStencilBuffer(true);
  84827. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  84828. // 2 passes inner outer
  84829. if (this.outerGlow) {
  84830. effect.setFloat("offset", 0);
  84831. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  84832. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  84833. }
  84834. if (this.innerGlow) {
  84835. effect.setFloat("offset", 1);
  84836. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  84837. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  84838. }
  84839. // Restore Cache
  84840. engine.setStencilFunction(previousStencilFunction);
  84841. engine.setStencilMask(previousStencilMask);
  84842. engine.setStencilBuffer(previousStencilBuffer);
  84843. engine.setStencilOperationPass(previousStencilOperationPass);
  84844. engine.setStencilOperationFail(previousStencilOperationFail);
  84845. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  84846. engine.setStencilFunctionReference(previousStencilReference);
  84847. };
  84848. /**
  84849. * Returns true if the layer contains information to display, otherwise false.
  84850. */
  84851. HighlightLayer.prototype.shouldRender = function () {
  84852. if (_super.prototype.shouldRender.call(this)) {
  84853. return this._meshes ? true : false;
  84854. }
  84855. return false;
  84856. };
  84857. /**
  84858. * Returns true if the mesh should render, otherwise false.
  84859. * @param mesh The mesh to render
  84860. * @returns true if it should render otherwise false
  84861. */
  84862. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  84863. // Excluded Mesh
  84864. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  84865. return false;
  84866. }
  84867. ;
  84868. return true;
  84869. };
  84870. /**
  84871. * Sets the required values for both the emissive texture and and the main color.
  84872. */
  84873. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  84874. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  84875. if (highlightLayerMesh) {
  84876. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  84877. }
  84878. else {
  84879. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  84880. }
  84881. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  84882. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  84883. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  84884. }
  84885. else {
  84886. this._emissiveTextureAndColor.texture = null;
  84887. }
  84888. };
  84889. /**
  84890. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  84891. * @param mesh The mesh to exclude from the highlight layer
  84892. */
  84893. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  84894. if (!this._excludedMeshes) {
  84895. return;
  84896. }
  84897. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  84898. if (!meshExcluded) {
  84899. this._excludedMeshes[mesh.uniqueId] = {
  84900. mesh: mesh,
  84901. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  84902. mesh.getEngine().setStencilBuffer(false);
  84903. }),
  84904. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  84905. mesh.getEngine().setStencilBuffer(true);
  84906. }),
  84907. };
  84908. }
  84909. };
  84910. /**
  84911. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  84912. * @param mesh The mesh to highlight
  84913. */
  84914. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  84915. if (!this._excludedMeshes) {
  84916. return;
  84917. }
  84918. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  84919. if (meshExcluded) {
  84920. if (meshExcluded.beforeRender) {
  84921. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  84922. }
  84923. if (meshExcluded.afterRender) {
  84924. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  84925. }
  84926. }
  84927. this._excludedMeshes[mesh.uniqueId] = null;
  84928. };
  84929. /**
  84930. * Determine if a given mesh will be highlighted by the current HighlightLayer
  84931. * @param mesh mesh to test
  84932. * @returns true if the mesh will be highlighted by the current HighlightLayer
  84933. */
  84934. HighlightLayer.prototype.hasMesh = function (mesh) {
  84935. if (!this._meshes) {
  84936. return false;
  84937. }
  84938. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  84939. };
  84940. /**
  84941. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  84942. * @param mesh The mesh to highlight
  84943. * @param color The color of the highlight
  84944. * @param glowEmissiveOnly Extract the glow from the emissive texture
  84945. */
  84946. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  84947. var _this = this;
  84948. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  84949. if (!this._meshes) {
  84950. return;
  84951. }
  84952. var meshHighlight = this._meshes[mesh.uniqueId];
  84953. if (meshHighlight) {
  84954. meshHighlight.color = color;
  84955. }
  84956. else {
  84957. this._meshes[mesh.uniqueId] = {
  84958. mesh: mesh,
  84959. color: color,
  84960. // Lambda required for capture due to Observable this context
  84961. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  84962. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  84963. _this._defaultStencilReference(mesh);
  84964. }
  84965. else {
  84966. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  84967. }
  84968. }),
  84969. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  84970. glowEmissiveOnly: glowEmissiveOnly
  84971. };
  84972. }
  84973. this._shouldRender = true;
  84974. };
  84975. /**
  84976. * Remove a mesh from the highlight layer in order to make it stop glowing.
  84977. * @param mesh The mesh to highlight
  84978. */
  84979. HighlightLayer.prototype.removeMesh = function (mesh) {
  84980. if (!this._meshes) {
  84981. return;
  84982. }
  84983. var meshHighlight = this._meshes[mesh.uniqueId];
  84984. if (meshHighlight) {
  84985. if (meshHighlight.observerHighlight) {
  84986. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  84987. }
  84988. if (meshHighlight.observerDefault) {
  84989. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  84990. }
  84991. delete this._meshes[mesh.uniqueId];
  84992. }
  84993. this._shouldRender = false;
  84994. for (var meshHighlightToCheck in this._meshes) {
  84995. if (this._meshes[meshHighlightToCheck]) {
  84996. this._shouldRender = true;
  84997. break;
  84998. }
  84999. }
  85000. };
  85001. /**
  85002. * Force the stencil to the normal expected value for none glowing parts
  85003. */
  85004. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  85005. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  85006. };
  85007. /**
  85008. * Free any resources and references associated to a mesh.
  85009. * Internal use
  85010. * @param mesh The mesh to free.
  85011. */
  85012. HighlightLayer.prototype._disposeMesh = function (mesh) {
  85013. this.removeMesh(mesh);
  85014. this.removeExcludedMesh(mesh);
  85015. };
  85016. /**
  85017. * Dispose the highlight layer and free resources.
  85018. */
  85019. HighlightLayer.prototype.dispose = function () {
  85020. if (this._meshes) {
  85021. // Clean mesh references
  85022. for (var id in this._meshes) {
  85023. var meshHighlight = this._meshes[id];
  85024. if (meshHighlight && meshHighlight.mesh) {
  85025. if (meshHighlight.observerHighlight) {
  85026. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  85027. }
  85028. if (meshHighlight.observerDefault) {
  85029. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  85030. }
  85031. }
  85032. }
  85033. this._meshes = null;
  85034. }
  85035. if (this._excludedMeshes) {
  85036. for (var id in this._excludedMeshes) {
  85037. var meshHighlight = this._excludedMeshes[id];
  85038. if (meshHighlight) {
  85039. if (meshHighlight.beforeRender) {
  85040. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  85041. }
  85042. if (meshHighlight.afterRender) {
  85043. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  85044. }
  85045. }
  85046. }
  85047. this._excludedMeshes = null;
  85048. }
  85049. _super.prototype.dispose.call(this);
  85050. };
  85051. /**
  85052. * Effect Name of the highlight layer.
  85053. */
  85054. HighlightLayer.EffectName = "HighlightLayer";
  85055. /**
  85056. * The neutral color used during the preparation of the glow effect.
  85057. * This is black by default as the blend operation is a blend operation.
  85058. */
  85059. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  85060. /**
  85061. * Stencil value used for glowing meshes.
  85062. */
  85063. HighlightLayer.GlowingMeshStencilReference = 0x02;
  85064. /**
  85065. * Stencil value used for the other meshes in the scene.
  85066. */
  85067. HighlightLayer.NormalMeshStencilReference = 0x01;
  85068. return HighlightLayer;
  85069. }(BABYLON.EffectLayer));
  85070. BABYLON.HighlightLayer = HighlightLayer;
  85071. })(BABYLON || (BABYLON = {}));
  85072. //# sourceMappingURL=babylon.highlightLayer.js.map
  85073. var BABYLON;
  85074. (function (BABYLON) {
  85075. /**
  85076. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  85077. *
  85078. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  85079. * glowy meshes to your scene.
  85080. *
  85081. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  85082. */
  85083. var GlowLayer = /** @class */ (function (_super) {
  85084. __extends(GlowLayer, _super);
  85085. /**
  85086. * Instantiates a new glow Layer and references it to the scene.
  85087. * @param name The name of the layer
  85088. * @param scene The scene to use the layer in
  85089. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  85090. */
  85091. function GlowLayer(name, scene, options) {
  85092. var _this = _super.call(this, name, scene) || this;
  85093. _this.name = name;
  85094. _this._intensity = 1.0;
  85095. _this._includedOnlyMeshes = [];
  85096. _this._excludedMeshes = [];
  85097. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  85098. // Adapt options
  85099. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1 }, options);
  85100. // Initialize the layer
  85101. _this._init({
  85102. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  85103. camera: _this._options.camera,
  85104. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  85105. mainTextureRatio: _this._options.mainTextureRatio
  85106. });
  85107. return _this;
  85108. }
  85109. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  85110. /**
  85111. * Gets the kernel size of the blur.
  85112. */
  85113. get: function () {
  85114. return this._horizontalBlurPostprocess1.kernel;
  85115. },
  85116. /**
  85117. * Sets the kernel size of the blur.
  85118. */
  85119. set: function (value) {
  85120. this._horizontalBlurPostprocess1.kernel = value;
  85121. this._verticalBlurPostprocess1.kernel = value;
  85122. this._horizontalBlurPostprocess2.kernel = value;
  85123. this._verticalBlurPostprocess2.kernel = value;
  85124. },
  85125. enumerable: true,
  85126. configurable: true
  85127. });
  85128. Object.defineProperty(GlowLayer.prototype, "intensity", {
  85129. /**
  85130. * Gets the glow intensity.
  85131. */
  85132. get: function () {
  85133. return this._intensity;
  85134. },
  85135. /**
  85136. * Sets the glow intensity.
  85137. */
  85138. set: function (value) {
  85139. this._intensity = value;
  85140. },
  85141. enumerable: true,
  85142. configurable: true
  85143. });
  85144. /**
  85145. * Get the effect name of the layer.
  85146. * @return The effect name
  85147. */
  85148. GlowLayer.prototype.getEffectName = function () {
  85149. return GlowLayer.EffectName;
  85150. };
  85151. /**
  85152. * Create the merge effect. This is the shader use to blit the information back
  85153. * to the main canvas at the end of the scene rendering.
  85154. */
  85155. GlowLayer.prototype._createMergeEffect = function () {
  85156. // Effect
  85157. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  85158. };
  85159. /**
  85160. * Creates the render target textures and post processes used in the glow layer.
  85161. */
  85162. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  85163. var _this = this;
  85164. var blurTextureWidth = this._mainTextureDesiredSize.width;
  85165. var blurTextureHeight = this._mainTextureDesiredSize.height;
  85166. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  85167. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  85168. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  85169. width: blurTextureWidth,
  85170. height: blurTextureHeight
  85171. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  85172. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85173. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85174. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  85175. this._blurTexture1.renderParticles = false;
  85176. this._blurTexture1.ignoreCameraViewport = true;
  85177. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  85178. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  85179. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  85180. width: blurTextureWidth2,
  85181. height: blurTextureHeight2
  85182. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  85183. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85184. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85185. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  85186. this._blurTexture2.renderParticles = false;
  85187. this._blurTexture2.ignoreCameraViewport = true;
  85188. this._textures = [this._blurTexture1, this._blurTexture2];
  85189. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  85190. width: blurTextureWidth,
  85191. height: blurTextureHeight
  85192. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  85193. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  85194. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  85195. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  85196. effect.setTexture("textureSampler", _this._mainTexture);
  85197. });
  85198. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  85199. width: blurTextureWidth,
  85200. height: blurTextureHeight
  85201. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  85202. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  85203. width: blurTextureWidth2,
  85204. height: blurTextureHeight2
  85205. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  85206. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  85207. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  85208. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  85209. effect.setTexture("textureSampler", _this._blurTexture1);
  85210. });
  85211. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  85212. width: blurTextureWidth2,
  85213. height: blurTextureHeight2
  85214. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  85215. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  85216. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  85217. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  85218. this._mainTexture.samples = this._options.mainTextureSamples;
  85219. this._mainTexture.onAfterUnbindObservable.add(function () {
  85220. var internalTexture = _this._blurTexture1.getInternalTexture();
  85221. if (internalTexture) {
  85222. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  85223. internalTexture = _this._blurTexture2.getInternalTexture();
  85224. if (internalTexture) {
  85225. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  85226. }
  85227. }
  85228. });
  85229. // Prevent autoClear.
  85230. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  85231. };
  85232. /**
  85233. * Checks for the readiness of the element composing the layer.
  85234. * @param subMesh the mesh to check for
  85235. * @param useInstances specify wether or not to use instances to render the mesh
  85236. * @param emissiveTexture the associated emissive texture used to generate the glow
  85237. * @return true if ready otherwise, false
  85238. */
  85239. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  85240. var material = subMesh.getMaterial();
  85241. var mesh = subMesh.getRenderingMesh();
  85242. if (!material || !mesh) {
  85243. return false;
  85244. }
  85245. var emissiveTexture = material.emissiveTexture;
  85246. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  85247. };
  85248. /**
  85249. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  85250. */
  85251. GlowLayer.prototype.needStencil = function () {
  85252. return false;
  85253. };
  85254. /**
  85255. * Implementation specific of rendering the generating effect on the main canvas.
  85256. * @param effect The effect used to render through
  85257. */
  85258. GlowLayer.prototype._internalRender = function (effect) {
  85259. // Texture
  85260. effect.setTexture("textureSampler", this._blurTexture1);
  85261. effect.setTexture("textureSampler2", this._blurTexture2);
  85262. effect.setFloat("offset", this._intensity);
  85263. // Cache
  85264. var engine = this._engine;
  85265. var previousStencilBuffer = engine.getStencilBuffer();
  85266. // Draw order
  85267. engine.setStencilBuffer(false);
  85268. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  85269. // Draw order
  85270. engine.setStencilBuffer(previousStencilBuffer);
  85271. };
  85272. /**
  85273. * Sets the required values for both the emissive texture and and the main color.
  85274. */
  85275. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  85276. var textureLevel = 1.0;
  85277. if (this.customEmissiveTextureSelector) {
  85278. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  85279. }
  85280. else {
  85281. if (material) {
  85282. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  85283. if (this._emissiveTextureAndColor.texture) {
  85284. textureLevel = this._emissiveTextureAndColor.texture.level;
  85285. }
  85286. }
  85287. else {
  85288. this._emissiveTextureAndColor.texture = null;
  85289. }
  85290. }
  85291. if (this.customEmissiveColorSelector) {
  85292. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  85293. }
  85294. else {
  85295. if (material.emissiveColor) {
  85296. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  85297. }
  85298. else {
  85299. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  85300. }
  85301. }
  85302. };
  85303. /**
  85304. * Returns true if the mesh should render, otherwise false.
  85305. * @param mesh The mesh to render
  85306. * @returns true if it should render otherwise false
  85307. */
  85308. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  85309. return this.hasMesh(mesh);
  85310. };
  85311. /**
  85312. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  85313. * @param mesh The mesh to exclude from the glow layer
  85314. */
  85315. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  85316. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  85317. this._excludedMeshes.push(mesh.uniqueId);
  85318. }
  85319. };
  85320. /**
  85321. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  85322. * @param mesh The mesh to remove
  85323. */
  85324. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  85325. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  85326. if (index !== -1) {
  85327. this._excludedMeshes.splice(index, 1);
  85328. }
  85329. };
  85330. /**
  85331. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  85332. * @param mesh The mesh to include in the glow layer
  85333. */
  85334. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  85335. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  85336. this._includedOnlyMeshes.push(mesh.uniqueId);
  85337. }
  85338. };
  85339. /**
  85340. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  85341. * @param mesh The mesh to remove
  85342. */
  85343. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  85344. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  85345. if (index !== -1) {
  85346. this._includedOnlyMeshes.splice(index, 1);
  85347. }
  85348. };
  85349. /**
  85350. * Determine if a given mesh will be used in the glow layer
  85351. * @param mesh The mesh to test
  85352. * @returns true if the mesh will be highlighted by the current glow layer
  85353. */
  85354. GlowLayer.prototype.hasMesh = function (mesh) {
  85355. // Included Mesh
  85356. if (this._includedOnlyMeshes.length) {
  85357. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  85358. }
  85359. ;
  85360. // Excluded Mesh
  85361. if (this._excludedMeshes.length) {
  85362. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  85363. }
  85364. ;
  85365. return true;
  85366. };
  85367. /**
  85368. * Free any resources and references associated to a mesh.
  85369. * Internal use
  85370. * @param mesh The mesh to free.
  85371. */
  85372. GlowLayer.prototype._disposeMesh = function (mesh) {
  85373. this.removeIncludedOnlyMesh(mesh);
  85374. this.removeExcludedMesh(mesh);
  85375. };
  85376. /**
  85377. * Effect Name of the layer.
  85378. */
  85379. GlowLayer.EffectName = "GlowLayer";
  85380. /**
  85381. * The default blur kernel size used for the glow.
  85382. */
  85383. GlowLayer.DefaultBlurKernelSize = 32;
  85384. /**
  85385. * The default texture size ratio used for the glow.
  85386. */
  85387. GlowLayer.DefaultTextureRatio = 0.5;
  85388. return GlowLayer;
  85389. }(BABYLON.EffectLayer));
  85390. BABYLON.GlowLayer = GlowLayer;
  85391. })(BABYLON || (BABYLON = {}));
  85392. //# sourceMappingURL=babylon.glowLayer.js.map
  85393. var BABYLON;
  85394. (function (BABYLON) {
  85395. /**
  85396. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  85397. */
  85398. var AssetTaskState;
  85399. (function (AssetTaskState) {
  85400. /**
  85401. * Initialization
  85402. */
  85403. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  85404. /**
  85405. * Running
  85406. */
  85407. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  85408. /**
  85409. * Done
  85410. */
  85411. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  85412. /**
  85413. * Error
  85414. */
  85415. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  85416. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  85417. /**
  85418. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  85419. */
  85420. var AbstractAssetTask = /** @class */ (function () {
  85421. /**
  85422. * Creates a new {BABYLON.AssetsManager}
  85423. * @param name defines the name of the task
  85424. */
  85425. function AbstractAssetTask(
  85426. /**
  85427. * Task name
  85428. */ name) {
  85429. this.name = name;
  85430. this._isCompleted = false;
  85431. this._taskState = AssetTaskState.INIT;
  85432. }
  85433. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  85434. /**
  85435. * Get if the task is completed
  85436. */
  85437. get: function () {
  85438. return this._isCompleted;
  85439. },
  85440. enumerable: true,
  85441. configurable: true
  85442. });
  85443. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  85444. /**
  85445. * Gets the current state of the task
  85446. */
  85447. get: function () {
  85448. return this._taskState;
  85449. },
  85450. enumerable: true,
  85451. configurable: true
  85452. });
  85453. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  85454. /**
  85455. * Gets the current error object (if task is in error)
  85456. */
  85457. get: function () {
  85458. return this._errorObject;
  85459. },
  85460. enumerable: true,
  85461. configurable: true
  85462. });
  85463. /**
  85464. * Internal only
  85465. * @ignore
  85466. */
  85467. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  85468. if (this._errorObject) {
  85469. return;
  85470. }
  85471. this._errorObject = {
  85472. message: message,
  85473. exception: exception
  85474. };
  85475. };
  85476. /**
  85477. * Execute the current task
  85478. * @param scene defines the scene where you want your assets to be loaded
  85479. * @param onSuccess is a callback called when the task is successfully executed
  85480. * @param onError is a callback called if an error occurs
  85481. */
  85482. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  85483. var _this = this;
  85484. this._taskState = AssetTaskState.RUNNING;
  85485. this.runTask(scene, function () {
  85486. _this.onDoneCallback(onSuccess, onError);
  85487. }, function (msg, exception) {
  85488. _this.onErrorCallback(onError, msg, exception);
  85489. });
  85490. };
  85491. /**
  85492. * Execute the current task
  85493. * @param scene defines the scene where you want your assets to be loaded
  85494. * @param onSuccess is a callback called when the task is successfully executed
  85495. * @param onError is a callback called if an error occurs
  85496. */
  85497. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  85498. throw new Error("runTask is not implemented");
  85499. };
  85500. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  85501. this._taskState = AssetTaskState.ERROR;
  85502. this._errorObject = {
  85503. message: message,
  85504. exception: exception
  85505. };
  85506. if (this.onError) {
  85507. this.onError(this, message, exception);
  85508. }
  85509. onError();
  85510. };
  85511. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  85512. try {
  85513. this._taskState = AssetTaskState.DONE;
  85514. this._isCompleted = true;
  85515. if (this.onSuccess) {
  85516. this.onSuccess(this);
  85517. }
  85518. onSuccess();
  85519. }
  85520. catch (e) {
  85521. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  85522. }
  85523. };
  85524. return AbstractAssetTask;
  85525. }());
  85526. BABYLON.AbstractAssetTask = AbstractAssetTask;
  85527. /**
  85528. * Class used to share progress information about assets loading
  85529. */
  85530. var AssetsProgressEvent = /** @class */ (function () {
  85531. /**
  85532. * Creates a {BABYLON.AssetsProgressEvent}
  85533. * @param remainingCount defines the number of remaining tasks to process
  85534. * @param totalCount defines the total number of tasks
  85535. * @param task defines the task that was just processed
  85536. */
  85537. function AssetsProgressEvent(remainingCount, totalCount, task) {
  85538. this.remainingCount = remainingCount;
  85539. this.totalCount = totalCount;
  85540. this.task = task;
  85541. }
  85542. return AssetsProgressEvent;
  85543. }());
  85544. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  85545. /**
  85546. * Define a task used by {BABYLON.AssetsManager} to load meshes
  85547. */
  85548. var MeshAssetTask = /** @class */ (function (_super) {
  85549. __extends(MeshAssetTask, _super);
  85550. /**
  85551. * Creates a new {BABYLON.MeshAssetTask}
  85552. * @param name defines the name of the task
  85553. * @param meshesNames defines the list of mesh's names you want to load
  85554. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  85555. * @param sceneFilename defines the filename of the scene to load from
  85556. */
  85557. function MeshAssetTask(
  85558. /**
  85559. * Defines the name of the task
  85560. */
  85561. name,
  85562. /**
  85563. * Defines the list of mesh's names you want to load
  85564. */
  85565. meshesNames,
  85566. /**
  85567. * Defines the root url to use as a base to load your meshes and associated resources
  85568. */
  85569. rootUrl,
  85570. /**
  85571. * Defines the filename of the scene to load from
  85572. */
  85573. sceneFilename) {
  85574. var _this = _super.call(this, name) || this;
  85575. _this.name = name;
  85576. _this.meshesNames = meshesNames;
  85577. _this.rootUrl = rootUrl;
  85578. _this.sceneFilename = sceneFilename;
  85579. return _this;
  85580. }
  85581. /**
  85582. * Execute the current task
  85583. * @param scene defines the scene where you want your assets to be loaded
  85584. * @param onSuccess is a callback called when the task is successfully executed
  85585. * @param onError is a callback called if an error occurs
  85586. */
  85587. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  85588. var _this = this;
  85589. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  85590. _this.loadedMeshes = meshes;
  85591. _this.loadedParticleSystems = particleSystems;
  85592. _this.loadedSkeletons = skeletons;
  85593. onSuccess();
  85594. }, null, function (scene, message, exception) {
  85595. onError(message, exception);
  85596. });
  85597. };
  85598. return MeshAssetTask;
  85599. }(AbstractAssetTask));
  85600. BABYLON.MeshAssetTask = MeshAssetTask;
  85601. /**
  85602. * Define a task used by {BABYLON.AssetsManager} to load text content
  85603. */
  85604. var TextFileAssetTask = /** @class */ (function (_super) {
  85605. __extends(TextFileAssetTask, _super);
  85606. /**
  85607. * Creates a new TextFileAssetTask object
  85608. * @param name defines the name of the task
  85609. * @param url defines the location of the file to load
  85610. */
  85611. function TextFileAssetTask(
  85612. /**
  85613. * Defines the name of the task
  85614. */
  85615. name,
  85616. /**
  85617. * Defines the location of the file to load
  85618. */
  85619. url) {
  85620. var _this = _super.call(this, name) || this;
  85621. _this.name = name;
  85622. _this.url = url;
  85623. return _this;
  85624. }
  85625. /**
  85626. * Execute the current task
  85627. * @param scene defines the scene where you want your assets to be loaded
  85628. * @param onSuccess is a callback called when the task is successfully executed
  85629. * @param onError is a callback called if an error occurs
  85630. */
  85631. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  85632. var _this = this;
  85633. scene._loadFile(this.url, function (data) {
  85634. _this.text = data;
  85635. onSuccess();
  85636. }, undefined, false, false, function (request, exception) {
  85637. if (request) {
  85638. onError(request.status + " " + request.statusText, exception);
  85639. }
  85640. });
  85641. };
  85642. return TextFileAssetTask;
  85643. }(AbstractAssetTask));
  85644. BABYLON.TextFileAssetTask = TextFileAssetTask;
  85645. /**
  85646. * Define a task used by {BABYLON.AssetsManager} to load binary data
  85647. */
  85648. var BinaryFileAssetTask = /** @class */ (function (_super) {
  85649. __extends(BinaryFileAssetTask, _super);
  85650. /**
  85651. * Creates a new BinaryFileAssetTask object
  85652. * @param name defines the name of the new task
  85653. * @param url defines the location of the file to load
  85654. */
  85655. function BinaryFileAssetTask(
  85656. /**
  85657. * Defines the name of the task
  85658. */
  85659. name,
  85660. /**
  85661. * Defines the location of the file to load
  85662. */
  85663. url) {
  85664. var _this = _super.call(this, name) || this;
  85665. _this.name = name;
  85666. _this.url = url;
  85667. return _this;
  85668. }
  85669. /**
  85670. * Execute the current task
  85671. * @param scene defines the scene where you want your assets to be loaded
  85672. * @param onSuccess is a callback called when the task is successfully executed
  85673. * @param onError is a callback called if an error occurs
  85674. */
  85675. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  85676. var _this = this;
  85677. scene._loadFile(this.url, function (data) {
  85678. _this.data = data;
  85679. onSuccess();
  85680. }, undefined, true, true, function (request, exception) {
  85681. if (request) {
  85682. onError(request.status + " " + request.statusText, exception);
  85683. }
  85684. });
  85685. };
  85686. return BinaryFileAssetTask;
  85687. }(AbstractAssetTask));
  85688. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  85689. /**
  85690. * Define a task used by {BABYLON.AssetsManager} to load images
  85691. */
  85692. var ImageAssetTask = /** @class */ (function (_super) {
  85693. __extends(ImageAssetTask, _super);
  85694. /**
  85695. * Creates a new ImageAssetTask
  85696. * @param name defines the name of the task
  85697. * @param url defines the location of the image to load
  85698. */
  85699. function ImageAssetTask(
  85700. /**
  85701. * Defines the name of the task
  85702. */
  85703. name,
  85704. /**
  85705. * Defines the location of the image to load
  85706. */
  85707. url) {
  85708. var _this = _super.call(this, name) || this;
  85709. _this.name = name;
  85710. _this.url = url;
  85711. return _this;
  85712. }
  85713. /**
  85714. * Execute the current task
  85715. * @param scene defines the scene where you want your assets to be loaded
  85716. * @param onSuccess is a callback called when the task is successfully executed
  85717. * @param onError is a callback called if an error occurs
  85718. */
  85719. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  85720. var _this = this;
  85721. var img = new Image();
  85722. BABYLON.Tools.SetCorsBehavior(this.url, img);
  85723. img.onload = function () {
  85724. _this.image = img;
  85725. onSuccess();
  85726. };
  85727. img.onerror = function (err) {
  85728. onError("Error loading image", err);
  85729. };
  85730. img.src = this.url;
  85731. };
  85732. return ImageAssetTask;
  85733. }(AbstractAssetTask));
  85734. BABYLON.ImageAssetTask = ImageAssetTask;
  85735. /**
  85736. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  85737. */
  85738. var TextureAssetTask = /** @class */ (function (_super) {
  85739. __extends(TextureAssetTask, _super);
  85740. /**
  85741. * Creates a new TextureAssetTask object
  85742. * @param name defines the name of the task
  85743. * @param url defines the location of the file to load
  85744. * @param noMipmap defines if mipmap should not be generated (default is false)
  85745. * @param invertY defines if texture must be inverted on Y axis (default is false)
  85746. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  85747. */
  85748. function TextureAssetTask(
  85749. /**
  85750. * Defines the name of the task
  85751. */
  85752. name,
  85753. /**
  85754. * Defines the location of the file to load
  85755. */
  85756. url,
  85757. /**
  85758. * Defines if mipmap should not be generated (default is false)
  85759. */
  85760. noMipmap,
  85761. /**
  85762. * Defines if texture must be inverted on Y axis (default is false)
  85763. */
  85764. invertY,
  85765. /**
  85766. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  85767. */
  85768. samplingMode) {
  85769. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  85770. var _this = _super.call(this, name) || this;
  85771. _this.name = name;
  85772. _this.url = url;
  85773. _this.noMipmap = noMipmap;
  85774. _this.invertY = invertY;
  85775. _this.samplingMode = samplingMode;
  85776. return _this;
  85777. }
  85778. /**
  85779. * Execute the current task
  85780. * @param scene defines the scene where you want your assets to be loaded
  85781. * @param onSuccess is a callback called when the task is successfully executed
  85782. * @param onError is a callback called if an error occurs
  85783. */
  85784. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  85785. var onload = function () {
  85786. onSuccess();
  85787. };
  85788. var onerror = function (message, exception) {
  85789. onError(message, exception);
  85790. };
  85791. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  85792. };
  85793. return TextureAssetTask;
  85794. }(AbstractAssetTask));
  85795. BABYLON.TextureAssetTask = TextureAssetTask;
  85796. /**
  85797. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  85798. */
  85799. var CubeTextureAssetTask = /** @class */ (function (_super) {
  85800. __extends(CubeTextureAssetTask, _super);
  85801. /**
  85802. * Creates a new CubeTextureAssetTask
  85803. * @param name defines the name of the task
  85804. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  85805. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  85806. * @param noMipmap defines if mipmaps should not be generated (default is false)
  85807. * @param files defines the explicit list of files (undefined by default)
  85808. */
  85809. function CubeTextureAssetTask(
  85810. /**
  85811. * Defines the name of the task
  85812. */
  85813. name,
  85814. /**
  85815. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  85816. */
  85817. url,
  85818. /**
  85819. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  85820. */
  85821. extensions,
  85822. /**
  85823. * Defines if mipmaps should not be generated (default is false)
  85824. */
  85825. noMipmap,
  85826. /**
  85827. * Defines the explicit list of files (undefined by default)
  85828. */
  85829. files) {
  85830. var _this = _super.call(this, name) || this;
  85831. _this.name = name;
  85832. _this.url = url;
  85833. _this.extensions = extensions;
  85834. _this.noMipmap = noMipmap;
  85835. _this.files = files;
  85836. return _this;
  85837. }
  85838. /**
  85839. * Execute the current task
  85840. * @param scene defines the scene where you want your assets to be loaded
  85841. * @param onSuccess is a callback called when the task is successfully executed
  85842. * @param onError is a callback called if an error occurs
  85843. */
  85844. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  85845. var onload = function () {
  85846. onSuccess();
  85847. };
  85848. var onerror = function (message, exception) {
  85849. onError(message, exception);
  85850. };
  85851. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  85852. };
  85853. return CubeTextureAssetTask;
  85854. }(AbstractAssetTask));
  85855. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  85856. /**
  85857. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  85858. */
  85859. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  85860. __extends(HDRCubeTextureAssetTask, _super);
  85861. /**
  85862. * Creates a new HDRCubeTextureAssetTask object
  85863. * @param name defines the name of the task
  85864. * @param url defines the location of the file to load
  85865. * @param size defines the desired size (the more it increases the longer the generation will be) If the size is omitted this implies you are using a preprocessed cubemap.
  85866. * @param noMipmap defines if mipmaps should not be generated (default is false)
  85867. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  85868. * @param useInGammaSpace specifies if the texture will be use in gamma or linear space (the PBR material requires those texture in linear space, but the standard material would require them in Gamma space) (default is false)
  85869. * @param usePMREMGenerator specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  85870. */
  85871. function HDRCubeTextureAssetTask(
  85872. /**
  85873. * Defines the name of the task
  85874. */
  85875. name,
  85876. /**
  85877. * Defines the location of the file to load
  85878. */
  85879. url,
  85880. /**
  85881. * Defines the desired size (the more it increases the longer the generation will be) If the size is omitted this implies you are using a preprocessed cubemap.
  85882. */
  85883. size,
  85884. /**
  85885. * Defines if mipmaps should not be generated (default is false)
  85886. */
  85887. noMipmap,
  85888. /**
  85889. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  85890. */
  85891. generateHarmonics,
  85892. /**
  85893. * Specifies if the texture will be use in gamma or linear space (the PBR material requires those texture in linear space, but the standard material would require them in Gamma space) (default is false)
  85894. */
  85895. useInGammaSpace,
  85896. /**
  85897. * Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  85898. */
  85899. usePMREMGenerator) {
  85900. if (noMipmap === void 0) { noMipmap = false; }
  85901. if (generateHarmonics === void 0) { generateHarmonics = true; }
  85902. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  85903. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  85904. var _this = _super.call(this, name) || this;
  85905. _this.name = name;
  85906. _this.url = url;
  85907. _this.size = size;
  85908. _this.noMipmap = noMipmap;
  85909. _this.generateHarmonics = generateHarmonics;
  85910. _this.useInGammaSpace = useInGammaSpace;
  85911. _this.usePMREMGenerator = usePMREMGenerator;
  85912. return _this;
  85913. }
  85914. /**
  85915. * Execute the current task
  85916. * @param scene defines the scene where you want your assets to be loaded
  85917. * @param onSuccess is a callback called when the task is successfully executed
  85918. * @param onError is a callback called if an error occurs
  85919. */
  85920. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  85921. var onload = function () {
  85922. onSuccess();
  85923. };
  85924. var onerror = function (message, exception) {
  85925. onError(message, exception);
  85926. };
  85927. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  85928. };
  85929. return HDRCubeTextureAssetTask;
  85930. }(AbstractAssetTask));
  85931. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  85932. /**
  85933. * This class can be used to easily import assets into a scene
  85934. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  85935. */
  85936. var AssetsManager = /** @class */ (function () {
  85937. /**
  85938. * Creates a new AssetsManager
  85939. * @param scene defines the scene to work on
  85940. */
  85941. function AssetsManager(scene) {
  85942. this._isLoading = false;
  85943. this._tasks = new Array();
  85944. this._waitingTasksCount = 0;
  85945. this._totalTasksCount = 0;
  85946. /**
  85947. * Observable called when all tasks are processed
  85948. */
  85949. this.onTaskSuccessObservable = new BABYLON.Observable();
  85950. /**
  85951. * Observable called when a task had an error
  85952. */
  85953. this.onTaskErrorObservable = new BABYLON.Observable();
  85954. /**
  85955. * Observable called when a task is successful
  85956. */
  85957. this.onTasksDoneObservable = new BABYLON.Observable();
  85958. /**
  85959. * Observable called when a task is done (whatever the result is)
  85960. */
  85961. this.onProgressObservable = new BABYLON.Observable();
  85962. /**
  85963. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  85964. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  85965. */
  85966. this.useDefaultLoadingScreen = true;
  85967. this._scene = scene;
  85968. }
  85969. /**
  85970. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  85971. * @param taskName defines the name of the new task
  85972. * @param meshesNames defines the name of meshes to load
  85973. * @param rootUrl defines the root url to use to locate files
  85974. * @param sceneFilename defines the filename of the scene file
  85975. * @returns a new {BABYLON.MeshAssetTask} object
  85976. */
  85977. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  85978. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  85979. this._tasks.push(task);
  85980. return task;
  85981. };
  85982. /**
  85983. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  85984. * @param taskName defines the name of the new task
  85985. * @param url defines the url of the file to load
  85986. * @returns a new {BABYLON.TextFileAssetTask} object
  85987. */
  85988. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  85989. var task = new TextFileAssetTask(taskName, url);
  85990. this._tasks.push(task);
  85991. return task;
  85992. };
  85993. /**
  85994. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  85995. * @param taskName defines the name of the new task
  85996. * @param url defines the url of the file to load
  85997. * @returns a new {BABYLON.BinaryFileAssetTask} object
  85998. */
  85999. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  86000. var task = new BinaryFileAssetTask(taskName, url);
  86001. this._tasks.push(task);
  86002. return task;
  86003. };
  86004. /**
  86005. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  86006. * @param taskName defines the name of the new task
  86007. * @param url defines the url of the file to load
  86008. * @returns a new {BABYLON.ImageAssetTask} object
  86009. */
  86010. AssetsManager.prototype.addImageTask = function (taskName, url) {
  86011. var task = new ImageAssetTask(taskName, url);
  86012. this._tasks.push(task);
  86013. return task;
  86014. };
  86015. /**
  86016. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  86017. * @param taskName defines the name of the new task
  86018. * @param url defines the url of the file to load
  86019. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  86020. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  86021. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  86022. * @returns a new {BABYLON.TextureAssetTask} object
  86023. */
  86024. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  86025. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  86026. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  86027. this._tasks.push(task);
  86028. return task;
  86029. };
  86030. /**
  86031. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  86032. * @param taskName defines the name of the new task
  86033. * @param url defines the url of the file to load
  86034. * @param extensions defines the extension to use to load the cube map (can be null)
  86035. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  86036. * @param files defines the list of files to load (can be null)
  86037. * @returns a new {BABYLON.CubeTextureAssetTask} object
  86038. */
  86039. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  86040. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  86041. this._tasks.push(task);
  86042. return task;
  86043. };
  86044. /**
  86045. *
  86046. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  86047. * @param taskName defines the name of the new task
  86048. * @param url defines the url of the file to load
  86049. * @param size defines the size you want for the cubemap (can be null)
  86050. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  86051. * @param generateHarmonics defines if you want to automatically generate (true by default)
  86052. * @param useInGammaSpace defines if the texture must be considered in gamma space (false by default)
  86053. * @param usePMREMGenerator is a reserved parameter and must be set to false or ignored
  86054. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  86055. */
  86056. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  86057. if (noMipmap === void 0) { noMipmap = false; }
  86058. if (generateHarmonics === void 0) { generateHarmonics = true; }
  86059. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  86060. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  86061. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator);
  86062. this._tasks.push(task);
  86063. return task;
  86064. };
  86065. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  86066. var _this = this;
  86067. this._waitingTasksCount--;
  86068. try {
  86069. if (task.taskState === AssetTaskState.DONE) {
  86070. // Let's remove successfull tasks
  86071. BABYLON.Tools.SetImmediate(function () {
  86072. var index = _this._tasks.indexOf(task);
  86073. if (index > -1) {
  86074. _this._tasks.splice(index, 1);
  86075. }
  86076. });
  86077. }
  86078. if (this.onProgress) {
  86079. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  86080. }
  86081. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  86082. }
  86083. catch (e) {
  86084. BABYLON.Tools.Error("Error running progress callbacks.");
  86085. console.log(e);
  86086. }
  86087. if (this._waitingTasksCount === 0) {
  86088. try {
  86089. if (this.onFinish) {
  86090. this.onFinish(this._tasks);
  86091. }
  86092. this.onTasksDoneObservable.notifyObservers(this._tasks);
  86093. }
  86094. catch (e) {
  86095. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  86096. console.log(e);
  86097. }
  86098. this._isLoading = false;
  86099. this._scene.getEngine().hideLoadingUI();
  86100. }
  86101. };
  86102. AssetsManager.prototype._runTask = function (task) {
  86103. var _this = this;
  86104. var done = function () {
  86105. try {
  86106. if (_this.onTaskSuccess) {
  86107. _this.onTaskSuccess(task);
  86108. }
  86109. _this.onTaskSuccessObservable.notifyObservers(task);
  86110. _this._decreaseWaitingTasksCount(task);
  86111. }
  86112. catch (e) {
  86113. error("Error executing task success callbacks", e);
  86114. }
  86115. };
  86116. var error = function (message, exception) {
  86117. task._setErrorObject(message, exception);
  86118. if (_this.onTaskError) {
  86119. _this.onTaskError(task);
  86120. }
  86121. _this.onTaskErrorObservable.notifyObservers(task);
  86122. _this._decreaseWaitingTasksCount(task);
  86123. };
  86124. task.run(this._scene, done, error);
  86125. };
  86126. /**
  86127. * Reset the {BABYLON.AssetsManager} and remove all tasks
  86128. * @return the current instance of the {BABYLON.AssetsManager}
  86129. */
  86130. AssetsManager.prototype.reset = function () {
  86131. this._isLoading = false;
  86132. this._tasks = new Array();
  86133. return this;
  86134. };
  86135. /**
  86136. * Start the loading process
  86137. * @return the current instance of the {BABYLON.AssetsManager}
  86138. */
  86139. AssetsManager.prototype.load = function () {
  86140. if (this._isLoading) {
  86141. return this;
  86142. }
  86143. this._isLoading = true;
  86144. this._waitingTasksCount = this._tasks.length;
  86145. this._totalTasksCount = this._tasks.length;
  86146. if (this._waitingTasksCount === 0) {
  86147. this._isLoading = false;
  86148. if (this.onFinish) {
  86149. this.onFinish(this._tasks);
  86150. }
  86151. this.onTasksDoneObservable.notifyObservers(this._tasks);
  86152. return this;
  86153. }
  86154. if (this.useDefaultLoadingScreen) {
  86155. this._scene.getEngine().displayLoadingUI();
  86156. }
  86157. for (var index = 0; index < this._tasks.length; index++) {
  86158. var task = this._tasks[index];
  86159. this._runTask(task);
  86160. }
  86161. return this;
  86162. };
  86163. return AssetsManager;
  86164. }());
  86165. BABYLON.AssetsManager = AssetsManager;
  86166. })(BABYLON || (BABYLON = {}));
  86167. //# sourceMappingURL=babylon.assetsManager.js.map
  86168. var BABYLON;
  86169. (function (BABYLON) {
  86170. var serializedGeometries = [];
  86171. var serializeGeometry = function (geometry, serializationGeometries) {
  86172. if (serializedGeometries[geometry.id]) {
  86173. return;
  86174. }
  86175. if (geometry.doNotSerialize) {
  86176. return;
  86177. }
  86178. if (geometry instanceof BABYLON.BoxGeometry) {
  86179. serializationGeometries.boxes.push(geometry.serialize());
  86180. }
  86181. else if (geometry instanceof BABYLON.SphereGeometry) {
  86182. serializationGeometries.spheres.push(geometry.serialize());
  86183. }
  86184. else if (geometry instanceof BABYLON.CylinderGeometry) {
  86185. serializationGeometries.cylinders.push(geometry.serialize());
  86186. }
  86187. else if (geometry instanceof BABYLON.TorusGeometry) {
  86188. serializationGeometries.toruses.push(geometry.serialize());
  86189. }
  86190. else if (geometry instanceof BABYLON.GroundGeometry) {
  86191. serializationGeometries.grounds.push(geometry.serialize());
  86192. }
  86193. else if (geometry instanceof BABYLON.Plane) {
  86194. serializationGeometries.planes.push(geometry.serialize());
  86195. }
  86196. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  86197. serializationGeometries.torusKnots.push(geometry.serialize());
  86198. }
  86199. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  86200. throw new Error("Unknown primitive type");
  86201. }
  86202. else {
  86203. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  86204. }
  86205. serializedGeometries[geometry.id] = true;
  86206. };
  86207. var serializeMesh = function (mesh, serializationScene) {
  86208. var serializationObject = {};
  86209. // Geometry
  86210. var geometry = mesh._geometry;
  86211. if (geometry) {
  86212. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  86213. // 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
  86214. serializeGeometry(geometry, serializationScene.geometries);
  86215. }
  86216. }
  86217. // Custom
  86218. if (mesh.serialize) {
  86219. mesh.serialize(serializationObject);
  86220. }
  86221. return serializationObject;
  86222. };
  86223. var finalizeSingleMesh = function (mesh, serializationObject) {
  86224. //only works if the mesh is already loaded
  86225. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  86226. //serialize material
  86227. if (mesh.material) {
  86228. if (mesh.material instanceof BABYLON.StandardMaterial) {
  86229. serializationObject.materials = serializationObject.materials || [];
  86230. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  86231. serializationObject.materials.push(mesh.material.serialize());
  86232. }
  86233. }
  86234. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  86235. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  86236. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  86237. serializationObject.multiMaterials.push(mesh.material.serialize());
  86238. }
  86239. }
  86240. }
  86241. //serialize geometry
  86242. var geometry = mesh._geometry;
  86243. if (geometry) {
  86244. if (!serializationObject.geometries) {
  86245. serializationObject.geometries = {};
  86246. serializationObject.geometries.boxes = [];
  86247. serializationObject.geometries.spheres = [];
  86248. serializationObject.geometries.cylinders = [];
  86249. serializationObject.geometries.toruses = [];
  86250. serializationObject.geometries.grounds = [];
  86251. serializationObject.geometries.planes = [];
  86252. serializationObject.geometries.torusKnots = [];
  86253. serializationObject.geometries.vertexData = [];
  86254. }
  86255. serializeGeometry(geometry, serializationObject.geometries);
  86256. }
  86257. // Skeletons
  86258. if (mesh.skeleton) {
  86259. serializationObject.skeletons = serializationObject.skeletons || [];
  86260. serializationObject.skeletons.push(mesh.skeleton.serialize());
  86261. }
  86262. //serialize the actual mesh
  86263. serializationObject.meshes = serializationObject.meshes || [];
  86264. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  86265. }
  86266. };
  86267. var SceneSerializer = /** @class */ (function () {
  86268. function SceneSerializer() {
  86269. }
  86270. SceneSerializer.ClearCache = function () {
  86271. serializedGeometries = [];
  86272. };
  86273. SceneSerializer.Serialize = function (scene) {
  86274. var serializationObject = {};
  86275. SceneSerializer.ClearCache();
  86276. // Scene
  86277. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  86278. serializationObject.autoClear = scene.autoClear;
  86279. serializationObject.clearColor = scene.clearColor.asArray();
  86280. serializationObject.ambientColor = scene.ambientColor.asArray();
  86281. serializationObject.gravity = scene.gravity.asArray();
  86282. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  86283. serializationObject.workerCollisions = scene.workerCollisions;
  86284. // Fog
  86285. if (scene.fogMode && scene.fogMode !== 0) {
  86286. serializationObject.fogMode = scene.fogMode;
  86287. serializationObject.fogColor = scene.fogColor.asArray();
  86288. serializationObject.fogStart = scene.fogStart;
  86289. serializationObject.fogEnd = scene.fogEnd;
  86290. serializationObject.fogDensity = scene.fogDensity;
  86291. }
  86292. //Physics
  86293. if (scene.isPhysicsEnabled()) {
  86294. var physicEngine = scene.getPhysicsEngine();
  86295. if (physicEngine) {
  86296. serializationObject.physicsEnabled = true;
  86297. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  86298. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  86299. }
  86300. }
  86301. // Metadata
  86302. if (scene.metadata) {
  86303. serializationObject.metadata = scene.metadata;
  86304. }
  86305. // Morph targets
  86306. serializationObject.morphTargetManagers = [];
  86307. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  86308. var abstractMesh = _a[_i];
  86309. var manager = abstractMesh.morphTargetManager;
  86310. if (manager) {
  86311. serializationObject.morphTargetManagers.push(manager.serialize());
  86312. }
  86313. }
  86314. // Lights
  86315. serializationObject.lights = [];
  86316. var index;
  86317. var light;
  86318. for (index = 0; index < scene.lights.length; index++) {
  86319. light = scene.lights[index];
  86320. if (!light.doNotSerialize) {
  86321. serializationObject.lights.push(light.serialize());
  86322. }
  86323. }
  86324. // Cameras
  86325. serializationObject.cameras = [];
  86326. for (index = 0; index < scene.cameras.length; index++) {
  86327. var camera = scene.cameras[index];
  86328. if (!camera.doNotSerialize) {
  86329. serializationObject.cameras.push(camera.serialize());
  86330. }
  86331. }
  86332. if (scene.activeCamera) {
  86333. serializationObject.activeCameraID = scene.activeCamera.id;
  86334. }
  86335. // Animations
  86336. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  86337. // Materials
  86338. serializationObject.materials = [];
  86339. serializationObject.multiMaterials = [];
  86340. var material;
  86341. for (index = 0; index < scene.materials.length; index++) {
  86342. material = scene.materials[index];
  86343. if (!material.doNotSerialize) {
  86344. serializationObject.materials.push(material.serialize());
  86345. }
  86346. }
  86347. // MultiMaterials
  86348. serializationObject.multiMaterials = [];
  86349. for (index = 0; index < scene.multiMaterials.length; index++) {
  86350. var multiMaterial = scene.multiMaterials[index];
  86351. serializationObject.multiMaterials.push(multiMaterial.serialize());
  86352. }
  86353. // Environment texture
  86354. if (scene.environmentTexture) {
  86355. serializationObject.environmentTexture = scene.environmentTexture.name;
  86356. }
  86357. // Skeletons
  86358. serializationObject.skeletons = [];
  86359. for (index = 0; index < scene.skeletons.length; index++) {
  86360. var skeleton = scene.skeletons[index];
  86361. if (!skeleton.doNotSerialize) {
  86362. serializationObject.skeletons.push(skeleton.serialize());
  86363. }
  86364. }
  86365. // Transform nodes
  86366. serializationObject.transformNodes = [];
  86367. for (index = 0; index < scene.transformNodes.length; index++) {
  86368. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  86369. }
  86370. // Geometries
  86371. serializationObject.geometries = {};
  86372. serializationObject.geometries.boxes = [];
  86373. serializationObject.geometries.spheres = [];
  86374. serializationObject.geometries.cylinders = [];
  86375. serializationObject.geometries.toruses = [];
  86376. serializationObject.geometries.grounds = [];
  86377. serializationObject.geometries.planes = [];
  86378. serializationObject.geometries.torusKnots = [];
  86379. serializationObject.geometries.vertexData = [];
  86380. serializedGeometries = [];
  86381. var geometries = scene.getGeometries();
  86382. for (index = 0; index < geometries.length; index++) {
  86383. var geometry = geometries[index];
  86384. if (geometry.isReady()) {
  86385. serializeGeometry(geometry, serializationObject.geometries);
  86386. }
  86387. }
  86388. // Meshes
  86389. serializationObject.meshes = [];
  86390. for (index = 0; index < scene.meshes.length; index++) {
  86391. var abstractMesh = scene.meshes[index];
  86392. if (abstractMesh instanceof BABYLON.Mesh) {
  86393. var mesh = abstractMesh;
  86394. if (!mesh.doNotSerialize) {
  86395. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  86396. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  86397. }
  86398. }
  86399. }
  86400. }
  86401. // Particles Systems
  86402. serializationObject.particleSystems = [];
  86403. for (index = 0; index < scene.particleSystems.length; index++) {
  86404. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  86405. }
  86406. // Lens flares
  86407. serializationObject.lensFlareSystems = [];
  86408. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  86409. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  86410. }
  86411. // Shadows
  86412. serializationObject.shadowGenerators = [];
  86413. for (index = 0; index < scene.lights.length; index++) {
  86414. light = scene.lights[index];
  86415. var shadowGenerator = light.getShadowGenerator();
  86416. if (shadowGenerator) {
  86417. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  86418. }
  86419. }
  86420. // Action Manager
  86421. if (scene.actionManager) {
  86422. serializationObject.actions = scene.actionManager.serialize("scene");
  86423. }
  86424. // Audio
  86425. serializationObject.sounds = [];
  86426. for (index = 0; index < scene.soundTracks.length; index++) {
  86427. var soundtrack = scene.soundTracks[index];
  86428. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  86429. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  86430. }
  86431. }
  86432. return serializationObject;
  86433. };
  86434. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  86435. if (withParents === void 0) { withParents = false; }
  86436. if (withChildren === void 0) { withChildren = false; }
  86437. var serializationObject = {};
  86438. SceneSerializer.ClearCache();
  86439. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  86440. if (withParents || withChildren) {
  86441. //deliberate for loop! not for each, appended should be processed as well.
  86442. for (var i = 0; i < toSerialize.length; ++i) {
  86443. if (withChildren) {
  86444. toSerialize[i].getDescendants().forEach(function (node) {
  86445. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  86446. toSerialize.push(node);
  86447. }
  86448. });
  86449. }
  86450. //make sure the array doesn't contain the object already
  86451. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  86452. toSerialize.push(toSerialize[i].parent);
  86453. }
  86454. }
  86455. }
  86456. toSerialize.forEach(function (mesh) {
  86457. finalizeSingleMesh(mesh, serializationObject);
  86458. });
  86459. return serializationObject;
  86460. };
  86461. return SceneSerializer;
  86462. }());
  86463. BABYLON.SceneSerializer = SceneSerializer;
  86464. })(BABYLON || (BABYLON = {}));
  86465. //# sourceMappingURL=babylon.sceneSerializer.js.map
  86466. var BABYLON;
  86467. (function (BABYLON) {
  86468. var ReflectionProbe = /** @class */ (function () {
  86469. function ReflectionProbe(name, size, scene, generateMipMaps) {
  86470. if (generateMipMaps === void 0) { generateMipMaps = true; }
  86471. var _this = this;
  86472. this.name = name;
  86473. this._viewMatrix = BABYLON.Matrix.Identity();
  86474. this._target = BABYLON.Vector3.Zero();
  86475. this._add = BABYLON.Vector3.Zero();
  86476. this.invertYAxis = false;
  86477. this.position = BABYLON.Vector3.Zero();
  86478. this._scene = scene;
  86479. this._scene.reflectionProbes.push(this);
  86480. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  86481. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  86482. switch (faceIndex) {
  86483. case 0:
  86484. _this._add.copyFromFloats(1, 0, 0);
  86485. break;
  86486. case 1:
  86487. _this._add.copyFromFloats(-1, 0, 0);
  86488. break;
  86489. case 2:
  86490. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  86491. break;
  86492. case 3:
  86493. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  86494. break;
  86495. case 4:
  86496. _this._add.copyFromFloats(0, 0, 1);
  86497. break;
  86498. case 5:
  86499. _this._add.copyFromFloats(0, 0, -1);
  86500. break;
  86501. }
  86502. if (_this._attachedMesh) {
  86503. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  86504. }
  86505. _this.position.addToRef(_this._add, _this._target);
  86506. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  86507. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  86508. scene._forcedViewPosition = _this.position;
  86509. });
  86510. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  86511. scene._forcedViewPosition = null;
  86512. scene.updateTransformMatrix(true);
  86513. });
  86514. if (scene.activeCamera) {
  86515. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  86516. }
  86517. }
  86518. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  86519. get: function () {
  86520. return this._renderTargetTexture.samples;
  86521. },
  86522. set: function (value) {
  86523. this._renderTargetTexture.samples = value;
  86524. },
  86525. enumerable: true,
  86526. configurable: true
  86527. });
  86528. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  86529. get: function () {
  86530. return this._renderTargetTexture.refreshRate;
  86531. },
  86532. set: function (value) {
  86533. this._renderTargetTexture.refreshRate = value;
  86534. },
  86535. enumerable: true,
  86536. configurable: true
  86537. });
  86538. ReflectionProbe.prototype.getScene = function () {
  86539. return this._scene;
  86540. };
  86541. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  86542. get: function () {
  86543. return this._renderTargetTexture;
  86544. },
  86545. enumerable: true,
  86546. configurable: true
  86547. });
  86548. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  86549. get: function () {
  86550. return this._renderTargetTexture.renderList;
  86551. },
  86552. enumerable: true,
  86553. configurable: true
  86554. });
  86555. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  86556. this._attachedMesh = mesh;
  86557. };
  86558. /**
  86559. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  86560. *
  86561. * @param renderingGroupId The rendering group id corresponding to its index
  86562. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  86563. */
  86564. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  86565. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  86566. };
  86567. ReflectionProbe.prototype.dispose = function () {
  86568. var index = this._scene.reflectionProbes.indexOf(this);
  86569. if (index !== -1) {
  86570. // Remove from the scene if found
  86571. this._scene.reflectionProbes.splice(index, 1);
  86572. }
  86573. if (this._renderTargetTexture) {
  86574. this._renderTargetTexture.dispose();
  86575. this._renderTargetTexture = null;
  86576. }
  86577. };
  86578. return ReflectionProbe;
  86579. }());
  86580. BABYLON.ReflectionProbe = ReflectionProbe;
  86581. })(BABYLON || (BABYLON = {}));
  86582. //# sourceMappingURL=babylon.reflectionProbe.js.map
  86583. var BABYLON;
  86584. (function (BABYLON) {
  86585. var Layer = /** @class */ (function () {
  86586. function Layer(name, imgUrl, scene, isBackground, color) {
  86587. this.name = name;
  86588. this.scale = new BABYLON.Vector2(1, 1);
  86589. this.offset = new BABYLON.Vector2(0, 0);
  86590. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  86591. this.layerMask = 0x0FFFFFFF;
  86592. this._vertexBuffers = {};
  86593. // Events
  86594. /**
  86595. * An event triggered when the layer is disposed.
  86596. * @type {BABYLON.Observable}
  86597. */
  86598. this.onDisposeObservable = new BABYLON.Observable();
  86599. /**
  86600. * An event triggered before rendering the scene
  86601. * @type {BABYLON.Observable}
  86602. */
  86603. this.onBeforeRenderObservable = new BABYLON.Observable();
  86604. /**
  86605. * An event triggered after rendering the scene
  86606. * @type {BABYLON.Observable}
  86607. */
  86608. this.onAfterRenderObservable = new BABYLON.Observable();
  86609. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  86610. this.isBackground = isBackground === undefined ? true : isBackground;
  86611. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  86612. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  86613. this._scene.layers.push(this);
  86614. var engine = this._scene.getEngine();
  86615. // VBO
  86616. var vertices = [];
  86617. vertices.push(1, 1);
  86618. vertices.push(-1, 1);
  86619. vertices.push(-1, -1);
  86620. vertices.push(1, -1);
  86621. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  86622. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  86623. this._createIndexBuffer();
  86624. // Effects
  86625. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  86626. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  86627. }
  86628. Object.defineProperty(Layer.prototype, "onDispose", {
  86629. set: function (callback) {
  86630. if (this._onDisposeObserver) {
  86631. this.onDisposeObservable.remove(this._onDisposeObserver);
  86632. }
  86633. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  86634. },
  86635. enumerable: true,
  86636. configurable: true
  86637. });
  86638. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  86639. set: function (callback) {
  86640. if (this._onBeforeRenderObserver) {
  86641. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  86642. }
  86643. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  86644. },
  86645. enumerable: true,
  86646. configurable: true
  86647. });
  86648. Object.defineProperty(Layer.prototype, "onAfterRender", {
  86649. set: function (callback) {
  86650. if (this._onAfterRenderObserver) {
  86651. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  86652. }
  86653. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  86654. },
  86655. enumerable: true,
  86656. configurable: true
  86657. });
  86658. Layer.prototype._createIndexBuffer = function () {
  86659. var engine = this._scene.getEngine();
  86660. // Indices
  86661. var indices = [];
  86662. indices.push(0);
  86663. indices.push(1);
  86664. indices.push(2);
  86665. indices.push(0);
  86666. indices.push(2);
  86667. indices.push(3);
  86668. this._indexBuffer = engine.createIndexBuffer(indices);
  86669. };
  86670. Layer.prototype._rebuild = function () {
  86671. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  86672. if (vb) {
  86673. vb._rebuild();
  86674. }
  86675. this._createIndexBuffer();
  86676. };
  86677. Layer.prototype.render = function () {
  86678. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  86679. // Check
  86680. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  86681. return;
  86682. var engine = this._scene.getEngine();
  86683. this.onBeforeRenderObservable.notifyObservers(this);
  86684. // Render
  86685. engine.enableEffect(currentEffect);
  86686. engine.setState(false);
  86687. // Texture
  86688. currentEffect.setTexture("textureSampler", this.texture);
  86689. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  86690. // Color
  86691. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  86692. // Scale / offset
  86693. currentEffect.setVector2("offset", this.offset);
  86694. currentEffect.setVector2("scale", this.scale);
  86695. // VBOs
  86696. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  86697. // Draw order
  86698. if (!this.alphaTest) {
  86699. engine.setAlphaMode(this.alphaBlendingMode);
  86700. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  86701. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  86702. }
  86703. else {
  86704. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  86705. }
  86706. this.onAfterRenderObservable.notifyObservers(this);
  86707. };
  86708. Layer.prototype.dispose = function () {
  86709. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  86710. if (vertexBuffer) {
  86711. vertexBuffer.dispose();
  86712. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  86713. }
  86714. if (this._indexBuffer) {
  86715. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  86716. this._indexBuffer = null;
  86717. }
  86718. if (this.texture) {
  86719. this.texture.dispose();
  86720. this.texture = null;
  86721. }
  86722. // Remove from scene
  86723. var index = this._scene.layers.indexOf(this);
  86724. this._scene.layers.splice(index, 1);
  86725. // Callback
  86726. this.onDisposeObservable.notifyObservers(this);
  86727. this.onDisposeObservable.clear();
  86728. this.onAfterRenderObservable.clear();
  86729. this.onBeforeRenderObservable.clear();
  86730. };
  86731. return Layer;
  86732. }());
  86733. BABYLON.Layer = Layer;
  86734. })(BABYLON || (BABYLON = {}));
  86735. //# sourceMappingURL=babylon.layer.js.map
  86736. var BABYLON;
  86737. (function (BABYLON) {
  86738. var TextureTools = /** @class */ (function () {
  86739. function TextureTools() {
  86740. }
  86741. /**
  86742. * Uses the GPU to create a copy texture rescaled at a given size
  86743. * @param texture Texture to copy from
  86744. * @param width Desired width
  86745. * @param height Desired height
  86746. * @return Generated texture
  86747. */
  86748. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  86749. if (useBilinearMode === void 0) { useBilinearMode = true; }
  86750. var scene = texture.getScene();
  86751. var engine = scene.getEngine();
  86752. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  86753. rtt.wrapU = texture.wrapU;
  86754. rtt.wrapV = texture.wrapV;
  86755. rtt.uOffset = texture.uOffset;
  86756. rtt.vOffset = texture.vOffset;
  86757. rtt.uScale = texture.uScale;
  86758. rtt.vScale = texture.vScale;
  86759. rtt.uAng = texture.uAng;
  86760. rtt.vAng = texture.vAng;
  86761. rtt.wAng = texture.wAng;
  86762. rtt.coordinatesIndex = texture.coordinatesIndex;
  86763. rtt.level = texture.level;
  86764. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  86765. rtt._texture.isReady = false;
  86766. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86767. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86768. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  86769. passPostProcess.getEffect().executeWhenCompiled(function () {
  86770. passPostProcess.onApply = function (effect) {
  86771. effect.setTexture("textureSampler", texture);
  86772. };
  86773. var internalTexture = rtt.getInternalTexture();
  86774. if (internalTexture) {
  86775. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  86776. engine.unBindFramebuffer(internalTexture);
  86777. rtt.disposeFramebufferObjects();
  86778. passPostProcess.dispose();
  86779. internalTexture.isReady = true;
  86780. }
  86781. });
  86782. return rtt;
  86783. };
  86784. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  86785. if (!scene._environmentBRDFTexture) {
  86786. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  86787. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86788. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86789. scene._environmentBRDFTexture = texture;
  86790. }
  86791. return scene._environmentBRDFTexture;
  86792. };
  86793. 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=";
  86794. return TextureTools;
  86795. }());
  86796. BABYLON.TextureTools = TextureTools;
  86797. })(BABYLON || (BABYLON = {}));
  86798. //# sourceMappingURL=babylon.textureTools.js.map
  86799. var BABYLON;
  86800. (function (BABYLON) {
  86801. var FramingBehavior = /** @class */ (function () {
  86802. function FramingBehavior() {
  86803. this._mode = FramingBehavior.FitFrustumSidesMode;
  86804. this._radiusScale = 1.0;
  86805. this._positionScale = 0.5;
  86806. this._defaultElevation = 0.3;
  86807. this._elevationReturnTime = 1500;
  86808. this._elevationReturnWaitTime = 1000;
  86809. this._zoomStopsAnimation = false;
  86810. this._framingTime = 1500;
  86811. this._isPointerDown = false;
  86812. this._lastInteractionTime = -Infinity;
  86813. // Framing control
  86814. this._animatables = new Array();
  86815. this._betaIsAnimating = false;
  86816. }
  86817. Object.defineProperty(FramingBehavior.prototype, "name", {
  86818. get: function () {
  86819. return "Framing";
  86820. },
  86821. enumerable: true,
  86822. configurable: true
  86823. });
  86824. Object.defineProperty(FramingBehavior.prototype, "mode", {
  86825. /**
  86826. * Gets current mode used by the behavior.
  86827. */
  86828. get: function () {
  86829. return this._mode;
  86830. },
  86831. /**
  86832. * Sets the current mode used by the behavior
  86833. */
  86834. set: function (mode) {
  86835. this._mode = mode;
  86836. },
  86837. enumerable: true,
  86838. configurable: true
  86839. });
  86840. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  86841. /**
  86842. * Gets the scale applied to the radius
  86843. */
  86844. get: function () {
  86845. return this._radiusScale;
  86846. },
  86847. /**
  86848. * Sets the scale applied to the radius (1 by default)
  86849. */
  86850. set: function (radius) {
  86851. this._radiusScale = radius;
  86852. },
  86853. enumerable: true,
  86854. configurable: true
  86855. });
  86856. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  86857. /**
  86858. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  86859. */
  86860. get: function () {
  86861. return this._positionScale;
  86862. },
  86863. /**
  86864. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  86865. */
  86866. set: function (scale) {
  86867. this._positionScale = scale;
  86868. },
  86869. enumerable: true,
  86870. configurable: true
  86871. });
  86872. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  86873. /**
  86874. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  86875. * behaviour is triggered, in radians.
  86876. */
  86877. get: function () {
  86878. return this._defaultElevation;
  86879. },
  86880. /**
  86881. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  86882. * behaviour is triggered, in radians.
  86883. */
  86884. set: function (elevation) {
  86885. this._defaultElevation = elevation;
  86886. },
  86887. enumerable: true,
  86888. configurable: true
  86889. });
  86890. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  86891. /**
  86892. * Gets the time (in milliseconds) taken to return to the default beta position.
  86893. * Negative value indicates camera should not return to default.
  86894. */
  86895. get: function () {
  86896. return this._elevationReturnTime;
  86897. },
  86898. /**
  86899. * Sets the time (in milliseconds) taken to return to the default beta position.
  86900. * Negative value indicates camera should not return to default.
  86901. */
  86902. set: function (speed) {
  86903. this._elevationReturnTime = speed;
  86904. },
  86905. enumerable: true,
  86906. configurable: true
  86907. });
  86908. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  86909. /**
  86910. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  86911. */
  86912. get: function () {
  86913. return this._elevationReturnWaitTime;
  86914. },
  86915. /**
  86916. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  86917. */
  86918. set: function (time) {
  86919. this._elevationReturnWaitTime = time;
  86920. },
  86921. enumerable: true,
  86922. configurable: true
  86923. });
  86924. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  86925. /**
  86926. * Gets the flag that indicates if user zooming should stop animation.
  86927. */
  86928. get: function () {
  86929. return this._zoomStopsAnimation;
  86930. },
  86931. /**
  86932. * Sets the flag that indicates if user zooming should stop animation.
  86933. */
  86934. set: function (flag) {
  86935. this._zoomStopsAnimation = flag;
  86936. },
  86937. enumerable: true,
  86938. configurable: true
  86939. });
  86940. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  86941. /**
  86942. * Gets the transition time when framing the mesh, in milliseconds
  86943. */
  86944. get: function () {
  86945. return this._framingTime;
  86946. },
  86947. /**
  86948. * Sets the transition time when framing the mesh, in milliseconds
  86949. */
  86950. set: function (time) {
  86951. this._framingTime = time;
  86952. },
  86953. enumerable: true,
  86954. configurable: true
  86955. });
  86956. FramingBehavior.prototype.init = function () {
  86957. // Do notihng
  86958. };
  86959. FramingBehavior.prototype.attach = function (camera) {
  86960. var _this = this;
  86961. this._attachedCamera = camera;
  86962. var scene = this._attachedCamera.getScene();
  86963. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  86964. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  86965. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  86966. _this._isPointerDown = true;
  86967. return;
  86968. }
  86969. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  86970. _this._isPointerDown = false;
  86971. }
  86972. });
  86973. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  86974. if (mesh) {
  86975. _this.zoomOnMesh(mesh);
  86976. }
  86977. });
  86978. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  86979. // Stop the animation if there is user interaction and the animation should stop for this interaction
  86980. _this._applyUserInteraction();
  86981. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  86982. // back to the default position after a given timeout
  86983. _this._maintainCameraAboveGround();
  86984. });
  86985. };
  86986. FramingBehavior.prototype.detach = function () {
  86987. if (!this._attachedCamera) {
  86988. return;
  86989. }
  86990. var scene = this._attachedCamera.getScene();
  86991. if (this._onPrePointerObservableObserver) {
  86992. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  86993. }
  86994. if (this._onAfterCheckInputsObserver) {
  86995. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  86996. }
  86997. if (this._onMeshTargetChangedObserver) {
  86998. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  86999. }
  87000. this._attachedCamera = null;
  87001. };
  87002. /**
  87003. * Targets the given mesh and updates zoom level accordingly.
  87004. * @param mesh The mesh to target.
  87005. * @param radius Optional. If a cached radius position already exists, overrides default.
  87006. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  87007. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  87008. * @param onAnimationEnd Callback triggered at the end of the framing animation
  87009. */
  87010. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  87011. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  87012. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  87013. mesh.computeWorldMatrix(true);
  87014. var boundingBox = mesh.getBoundingInfo().boundingBox;
  87015. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  87016. };
  87017. /**
  87018. * Targets the given mesh with its children and updates zoom level accordingly.
  87019. * @param mesh The mesh to target.
  87020. * @param radius Optional. If a cached radius position already exists, overrides default.
  87021. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  87022. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  87023. * @param onAnimationEnd Callback triggered at the end of the framing animation
  87024. */
  87025. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  87026. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  87027. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  87028. mesh.computeWorldMatrix(true);
  87029. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  87030. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  87031. };
  87032. /**
  87033. * Targets the given meshes with their children and updates zoom level accordingly.
  87034. * @param meshes The mesh to target.
  87035. * @param radius Optional. If a cached radius position already exists, overrides default.
  87036. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  87037. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  87038. * @param onAnimationEnd Callback triggered at the end of the framing animation
  87039. */
  87040. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  87041. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  87042. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  87043. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  87044. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  87045. for (var i = 0; i < meshes.length; i++) {
  87046. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  87047. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  87048. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  87049. }
  87050. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  87051. };
  87052. /**
  87053. * Targets the given mesh and updates zoom level accordingly.
  87054. * @param mesh The mesh to target.
  87055. * @param radius Optional. If a cached radius position already exists, overrides default.
  87056. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  87057. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  87058. * @param onAnimationEnd Callback triggered at the end of the framing animation
  87059. */
  87060. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  87061. var _this = this;
  87062. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  87063. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  87064. var zoomTarget;
  87065. if (!this._attachedCamera) {
  87066. return;
  87067. }
  87068. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  87069. var bottom = minimumWorld.y;
  87070. var top = maximumWorld.y;
  87071. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  87072. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  87073. if (focusOnOriginXZ) {
  87074. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  87075. }
  87076. else {
  87077. var centerWorld = minimumWorld.add(radiusWorld);
  87078. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  87079. }
  87080. if (!this._vectorTransition) {
  87081. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  87082. }
  87083. this._betaIsAnimating = true;
  87084. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  87085. if (animatable) {
  87086. this._animatables.push(animatable);
  87087. }
  87088. // sets the radius and lower radius bounds
  87089. // Small delta ensures camera is not always at lower zoom limit.
  87090. var radius = 0;
  87091. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  87092. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  87093. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  87094. radius = position;
  87095. }
  87096. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  87097. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  87098. if (this._attachedCamera.lowerRadiusLimit === null) {
  87099. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  87100. }
  87101. }
  87102. // Set sensibilities
  87103. var extend = maximumWorld.subtract(minimumWorld).length();
  87104. this._attachedCamera.panningSensibility = 5000 / extend;
  87105. this._attachedCamera.wheelPrecision = 100 / radius;
  87106. // transition to new radius
  87107. if (!this._radiusTransition) {
  87108. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  87109. }
  87110. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  87111. if (onAnimationEnd) {
  87112. onAnimationEnd();
  87113. }
  87114. if (_this._attachedCamera) {
  87115. _this._attachedCamera.storeState();
  87116. }
  87117. });
  87118. if (animatable) {
  87119. this._animatables.push(animatable);
  87120. }
  87121. };
  87122. /**
  87123. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  87124. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  87125. * frustum width.
  87126. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  87127. * to fully enclose the mesh in the viewing frustum.
  87128. */
  87129. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  87130. var size = maximumWorld.subtract(minimumWorld);
  87131. var boxVectorGlobalDiagonal = size.length();
  87132. var frustumSlope = this._getFrustumSlope();
  87133. // Formula for setting distance
  87134. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  87135. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  87136. // Horizon distance
  87137. var radius = radiusWithoutFraming * this._radiusScale;
  87138. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  87139. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  87140. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  87141. var camera = this._attachedCamera;
  87142. if (!camera) {
  87143. return 0;
  87144. }
  87145. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  87146. // Don't exceed the requested limit
  87147. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  87148. }
  87149. // Don't exceed the upper radius limit
  87150. if (camera.upperRadiusLimit) {
  87151. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  87152. }
  87153. return distance;
  87154. };
  87155. /**
  87156. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  87157. * is automatically returned to its default position (expected to be above ground plane).
  87158. */
  87159. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  87160. var _this = this;
  87161. if (this._elevationReturnTime < 0) {
  87162. return;
  87163. }
  87164. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  87165. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  87166. var limitBeta = Math.PI * 0.5;
  87167. // Bring the camera back up if below the ground plane
  87168. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  87169. this._betaIsAnimating = true;
  87170. //Transition to new position
  87171. this.stopAllAnimations();
  87172. if (!this._betaTransition) {
  87173. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  87174. }
  87175. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  87176. _this._clearAnimationLocks();
  87177. _this.stopAllAnimations();
  87178. });
  87179. if (animatabe) {
  87180. this._animatables.push(animatabe);
  87181. }
  87182. }
  87183. };
  87184. /**
  87185. * Returns the frustum slope based on the canvas ratio and camera FOV
  87186. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  87187. */
  87188. FramingBehavior.prototype._getFrustumSlope = function () {
  87189. // Calculate the viewport ratio
  87190. // Aspect Ratio is Height/Width.
  87191. var camera = this._attachedCamera;
  87192. if (!camera) {
  87193. return BABYLON.Vector2.Zero();
  87194. }
  87195. var engine = camera.getScene().getEngine();
  87196. var aspectRatio = engine.getAspectRatio(camera);
  87197. // Camera FOV is the vertical field of view (top-bottom) in radians.
  87198. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  87199. var frustumSlopeY = Math.tan(camera.fov / 2);
  87200. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  87201. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  87202. // along the forward vector.
  87203. var frustumSlopeX = frustumSlopeY * aspectRatio;
  87204. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  87205. };
  87206. /**
  87207. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  87208. */
  87209. FramingBehavior.prototype._clearAnimationLocks = function () {
  87210. this._betaIsAnimating = false;
  87211. };
  87212. /**
  87213. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  87214. */
  87215. FramingBehavior.prototype._applyUserInteraction = function () {
  87216. if (this.isUserIsMoving) {
  87217. this._lastInteractionTime = BABYLON.Tools.Now;
  87218. this.stopAllAnimations();
  87219. this._clearAnimationLocks();
  87220. }
  87221. };
  87222. /**
  87223. * Stops and removes all animations that have been applied to the camera
  87224. */
  87225. FramingBehavior.prototype.stopAllAnimations = function () {
  87226. if (this._attachedCamera) {
  87227. this._attachedCamera.animations = [];
  87228. }
  87229. while (this._animatables.length) {
  87230. if (this._animatables[0]) {
  87231. this._animatables[0].onAnimationEnd = null;
  87232. this._animatables[0].stop();
  87233. }
  87234. this._animatables.shift();
  87235. }
  87236. };
  87237. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  87238. /**
  87239. * Gets a value indicating if the user is moving the camera
  87240. */
  87241. get: function () {
  87242. if (!this._attachedCamera) {
  87243. return false;
  87244. }
  87245. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  87246. this._attachedCamera.inertialBetaOffset !== 0 ||
  87247. this._attachedCamera.inertialRadiusOffset !== 0 ||
  87248. this._attachedCamera.inertialPanningX !== 0 ||
  87249. this._attachedCamera.inertialPanningY !== 0 ||
  87250. this._isPointerDown;
  87251. },
  87252. enumerable: true,
  87253. configurable: true
  87254. });
  87255. /**
  87256. * The easing function used by animations
  87257. */
  87258. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  87259. /**
  87260. * The easing mode used by animations
  87261. */
  87262. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  87263. // Statics
  87264. /**
  87265. * The camera can move all the way towards the mesh.
  87266. */
  87267. FramingBehavior.IgnoreBoundsSizeMode = 0;
  87268. /**
  87269. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  87270. */
  87271. FramingBehavior.FitFrustumSidesMode = 1;
  87272. return FramingBehavior;
  87273. }());
  87274. BABYLON.FramingBehavior = FramingBehavior;
  87275. })(BABYLON || (BABYLON = {}));
  87276. //# sourceMappingURL=babylon.framingBehavior.js.map
  87277. var BABYLON;
  87278. (function (BABYLON) {
  87279. /**
  87280. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  87281. */
  87282. var BouncingBehavior = /** @class */ (function () {
  87283. function BouncingBehavior() {
  87284. /**
  87285. * The duration of the animation, in milliseconds
  87286. */
  87287. this.transitionDuration = 450;
  87288. /**
  87289. * Length of the distance animated by the transition when lower radius is reached
  87290. */
  87291. this.lowerRadiusTransitionRange = 2;
  87292. /**
  87293. * Length of the distance animated by the transition when upper radius is reached
  87294. */
  87295. this.upperRadiusTransitionRange = -2;
  87296. this._autoTransitionRange = false;
  87297. // Animations
  87298. this._radiusIsAnimating = false;
  87299. this._radiusBounceTransition = null;
  87300. this._animatables = new Array();
  87301. }
  87302. Object.defineProperty(BouncingBehavior.prototype, "name", {
  87303. get: function () {
  87304. return "Bouncing";
  87305. },
  87306. enumerable: true,
  87307. configurable: true
  87308. });
  87309. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  87310. /**
  87311. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  87312. */
  87313. get: function () {
  87314. return this._autoTransitionRange;
  87315. },
  87316. /**
  87317. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  87318. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  87319. */
  87320. set: function (value) {
  87321. var _this = this;
  87322. if (this._autoTransitionRange === value) {
  87323. return;
  87324. }
  87325. this._autoTransitionRange = value;
  87326. var camera = this._attachedCamera;
  87327. if (!camera) {
  87328. return;
  87329. }
  87330. if (value) {
  87331. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  87332. if (!mesh) {
  87333. return;
  87334. }
  87335. mesh.computeWorldMatrix(true);
  87336. var diagonal = mesh.getBoundingInfo().diagonalLength;
  87337. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  87338. _this.upperRadiusTransitionRange = diagonal * 0.05;
  87339. });
  87340. }
  87341. else if (this._onMeshTargetChangedObserver) {
  87342. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  87343. }
  87344. },
  87345. enumerable: true,
  87346. configurable: true
  87347. });
  87348. BouncingBehavior.prototype.init = function () {
  87349. // Do notihng
  87350. };
  87351. BouncingBehavior.prototype.attach = function (camera) {
  87352. var _this = this;
  87353. this._attachedCamera = camera;
  87354. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  87355. if (!_this._attachedCamera) {
  87356. return;
  87357. }
  87358. // Add the bounce animation to the lower radius limit
  87359. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  87360. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  87361. }
  87362. // Add the bounce animation to the upper radius limit
  87363. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  87364. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  87365. }
  87366. });
  87367. };
  87368. BouncingBehavior.prototype.detach = function () {
  87369. if (!this._attachedCamera) {
  87370. return;
  87371. }
  87372. if (this._onAfterCheckInputsObserver) {
  87373. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  87374. }
  87375. if (this._onMeshTargetChangedObserver) {
  87376. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  87377. }
  87378. this._attachedCamera = null;
  87379. };
  87380. /**
  87381. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  87382. * @param radiusLimit The limit to check against.
  87383. * @return Bool to indicate if at limit.
  87384. */
  87385. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  87386. if (!this._attachedCamera) {
  87387. return false;
  87388. }
  87389. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  87390. return true;
  87391. }
  87392. return false;
  87393. };
  87394. /**
  87395. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  87396. * @param radiusDelta The delta by which to animate to. Can be negative.
  87397. */
  87398. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  87399. var _this = this;
  87400. if (!this._attachedCamera) {
  87401. return;
  87402. }
  87403. if (!this._radiusBounceTransition) {
  87404. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  87405. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  87406. }
  87407. // Prevent zoom until bounce has completed
  87408. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  87409. this._attachedCamera.wheelPrecision = Infinity;
  87410. this._attachedCamera.inertialRadiusOffset = 0;
  87411. // Animate to the radius limit
  87412. this.stopAllAnimations();
  87413. this._radiusIsAnimating = true;
  87414. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  87415. if (animatable) {
  87416. this._animatables.push(animatable);
  87417. }
  87418. };
  87419. /**
  87420. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  87421. */
  87422. BouncingBehavior.prototype._clearAnimationLocks = function () {
  87423. this._radiusIsAnimating = false;
  87424. if (this._attachedCamera) {
  87425. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  87426. }
  87427. };
  87428. /**
  87429. * Stops and removes all animations that have been applied to the camera
  87430. */
  87431. BouncingBehavior.prototype.stopAllAnimations = function () {
  87432. if (this._attachedCamera) {
  87433. this._attachedCamera.animations = [];
  87434. }
  87435. while (this._animatables.length) {
  87436. this._animatables[0].onAnimationEnd = null;
  87437. this._animatables[0].stop();
  87438. this._animatables.shift();
  87439. }
  87440. };
  87441. /**
  87442. * The easing function used by animations
  87443. */
  87444. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  87445. /**
  87446. * The easing mode used by animations
  87447. */
  87448. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  87449. return BouncingBehavior;
  87450. }());
  87451. BABYLON.BouncingBehavior = BouncingBehavior;
  87452. })(BABYLON || (BABYLON = {}));
  87453. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  87454. var BABYLON;
  87455. (function (BABYLON) {
  87456. var AutoRotationBehavior = /** @class */ (function () {
  87457. function AutoRotationBehavior() {
  87458. this._zoomStopsAnimation = false;
  87459. this._idleRotationSpeed = 0.05;
  87460. this._idleRotationWaitTime = 2000;
  87461. this._idleRotationSpinupTime = 2000;
  87462. this._isPointerDown = false;
  87463. this._lastFrameTime = null;
  87464. this._lastInteractionTime = -Infinity;
  87465. this._cameraRotationSpeed = 0;
  87466. this._lastFrameRadius = 0;
  87467. }
  87468. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  87469. get: function () {
  87470. return "AutoRotation";
  87471. },
  87472. enumerable: true,
  87473. configurable: true
  87474. });
  87475. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  87476. /**
  87477. * Gets the flag that indicates if user zooming should stop animation.
  87478. */
  87479. get: function () {
  87480. return this._zoomStopsAnimation;
  87481. },
  87482. /**
  87483. * Sets the flag that indicates if user zooming should stop animation.
  87484. */
  87485. set: function (flag) {
  87486. this._zoomStopsAnimation = flag;
  87487. },
  87488. enumerable: true,
  87489. configurable: true
  87490. });
  87491. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  87492. /**
  87493. * Gets the default speed at which the camera rotates around the model.
  87494. */
  87495. get: function () {
  87496. return this._idleRotationSpeed;
  87497. },
  87498. /**
  87499. * Sets the default speed at which the camera rotates around the model.
  87500. */
  87501. set: function (speed) {
  87502. this._idleRotationSpeed = speed;
  87503. },
  87504. enumerable: true,
  87505. configurable: true
  87506. });
  87507. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  87508. /**
  87509. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  87510. */
  87511. get: function () {
  87512. return this._idleRotationWaitTime;
  87513. },
  87514. /**
  87515. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  87516. */
  87517. set: function (time) {
  87518. this._idleRotationWaitTime = time;
  87519. },
  87520. enumerable: true,
  87521. configurable: true
  87522. });
  87523. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  87524. /**
  87525. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  87526. */
  87527. get: function () {
  87528. return this._idleRotationSpinupTime;
  87529. },
  87530. /**
  87531. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  87532. */
  87533. set: function (time) {
  87534. this._idleRotationSpinupTime = time;
  87535. },
  87536. enumerable: true,
  87537. configurable: true
  87538. });
  87539. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  87540. /**
  87541. * Gets a value indicating if the camera is currently rotating because of this behavior
  87542. */
  87543. get: function () {
  87544. return Math.abs(this._cameraRotationSpeed) > 0;
  87545. },
  87546. enumerable: true,
  87547. configurable: true
  87548. });
  87549. AutoRotationBehavior.prototype.init = function () {
  87550. // Do notihng
  87551. };
  87552. AutoRotationBehavior.prototype.attach = function (camera) {
  87553. var _this = this;
  87554. this._attachedCamera = camera;
  87555. var scene = this._attachedCamera.getScene();
  87556. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  87557. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  87558. _this._isPointerDown = true;
  87559. return;
  87560. }
  87561. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  87562. _this._isPointerDown = false;
  87563. }
  87564. });
  87565. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  87566. var now = BABYLON.Tools.Now;
  87567. var dt = 0;
  87568. if (_this._lastFrameTime != null) {
  87569. dt = now - _this._lastFrameTime;
  87570. }
  87571. _this._lastFrameTime = now;
  87572. // Stop the animation if there is user interaction and the animation should stop for this interaction
  87573. _this._applyUserInteraction();
  87574. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  87575. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  87576. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  87577. // Step camera rotation by rotation speed
  87578. if (_this._attachedCamera) {
  87579. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  87580. }
  87581. });
  87582. };
  87583. AutoRotationBehavior.prototype.detach = function () {
  87584. if (!this._attachedCamera) {
  87585. return;
  87586. }
  87587. var scene = this._attachedCamera.getScene();
  87588. if (this._onPrePointerObservableObserver) {
  87589. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  87590. }
  87591. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  87592. this._attachedCamera = null;
  87593. };
  87594. /**
  87595. * Returns true if user is scrolling.
  87596. * @return true if user is scrolling.
  87597. */
  87598. AutoRotationBehavior.prototype._userIsZooming = function () {
  87599. if (!this._attachedCamera) {
  87600. return false;
  87601. }
  87602. return this._attachedCamera.inertialRadiusOffset !== 0;
  87603. };
  87604. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  87605. if (!this._attachedCamera) {
  87606. return false;
  87607. }
  87608. var zoomHasHitLimit = false;
  87609. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  87610. zoomHasHitLimit = true;
  87611. }
  87612. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  87613. this._lastFrameRadius = this._attachedCamera.radius;
  87614. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  87615. };
  87616. /**
  87617. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  87618. */
  87619. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  87620. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  87621. this._lastInteractionTime = BABYLON.Tools.Now;
  87622. }
  87623. };
  87624. // Tools
  87625. AutoRotationBehavior.prototype._userIsMoving = function () {
  87626. if (!this._attachedCamera) {
  87627. return false;
  87628. }
  87629. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  87630. this._attachedCamera.inertialBetaOffset !== 0 ||
  87631. this._attachedCamera.inertialRadiusOffset !== 0 ||
  87632. this._attachedCamera.inertialPanningX !== 0 ||
  87633. this._attachedCamera.inertialPanningY !== 0 ||
  87634. this._isPointerDown;
  87635. };
  87636. return AutoRotationBehavior;
  87637. }());
  87638. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  87639. })(BABYLON || (BABYLON = {}));
  87640. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  87641. var BABYLON;
  87642. (function (BABYLON) {
  87643. var NullEngineOptions = /** @class */ (function () {
  87644. function NullEngineOptions() {
  87645. this.renderWidth = 512;
  87646. this.renderHeight = 256;
  87647. this.textureSize = 512;
  87648. this.deterministicLockstep = false;
  87649. this.lockstepMaxSteps = 4;
  87650. }
  87651. return NullEngineOptions;
  87652. }());
  87653. BABYLON.NullEngineOptions = NullEngineOptions;
  87654. /**
  87655. * The null engine class provides support for headless version of babylon.js.
  87656. * This can be used in server side scenario or for testing purposes
  87657. */
  87658. var NullEngine = /** @class */ (function (_super) {
  87659. __extends(NullEngine, _super);
  87660. function NullEngine(options) {
  87661. if (options === void 0) { options = new NullEngineOptions(); }
  87662. var _this = _super.call(this, null) || this;
  87663. if (options.deterministicLockstep === undefined) {
  87664. options.deterministicLockstep = false;
  87665. }
  87666. if (options.lockstepMaxSteps === undefined) {
  87667. options.lockstepMaxSteps = 4;
  87668. }
  87669. _this._options = options;
  87670. // Init caps
  87671. // We consider we are on a webgl1 capable device
  87672. _this._caps = new BABYLON.EngineCapabilities();
  87673. _this._caps.maxTexturesImageUnits = 16;
  87674. _this._caps.maxVertexTextureImageUnits = 16;
  87675. _this._caps.maxTextureSize = 512;
  87676. _this._caps.maxCubemapTextureSize = 512;
  87677. _this._caps.maxRenderTextureSize = 512;
  87678. _this._caps.maxVertexAttribs = 16;
  87679. _this._caps.maxVaryingVectors = 16;
  87680. _this._caps.maxFragmentUniformVectors = 16;
  87681. _this._caps.maxVertexUniformVectors = 16;
  87682. // Extensions
  87683. _this._caps.standardDerivatives = false;
  87684. _this._caps.astc = null;
  87685. _this._caps.s3tc = null;
  87686. _this._caps.pvrtc = null;
  87687. _this._caps.etc1 = null;
  87688. _this._caps.etc2 = null;
  87689. _this._caps.textureAnisotropicFilterExtension = null;
  87690. _this._caps.maxAnisotropy = 0;
  87691. _this._caps.uintIndices = false;
  87692. _this._caps.fragmentDepthSupported = false;
  87693. _this._caps.highPrecisionShaderSupported = true;
  87694. _this._caps.colorBufferFloat = false;
  87695. _this._caps.textureFloat = false;
  87696. _this._caps.textureFloatLinearFiltering = false;
  87697. _this._caps.textureFloatRender = false;
  87698. _this._caps.textureHalfFloat = false;
  87699. _this._caps.textureHalfFloatLinearFiltering = false;
  87700. _this._caps.textureHalfFloatRender = false;
  87701. _this._caps.textureLOD = false;
  87702. _this._caps.drawBuffersExtension = false;
  87703. _this._caps.depthTextureExtension = false;
  87704. _this._caps.vertexArrayObject = false;
  87705. _this._caps.instancedArrays = false;
  87706. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  87707. // Wrappers
  87708. if (typeof URL === "undefined") {
  87709. URL = {
  87710. createObjectURL: function () { },
  87711. revokeObjectURL: function () { }
  87712. };
  87713. }
  87714. if (typeof Blob === "undefined") {
  87715. Blob = function () { };
  87716. }
  87717. return _this;
  87718. }
  87719. NullEngine.prototype.isDeterministicLockStep = function () {
  87720. return this._options.deterministicLockstep;
  87721. };
  87722. NullEngine.prototype.getLockstepMaxSteps = function () {
  87723. return this._options.lockstepMaxSteps;
  87724. };
  87725. NullEngine.prototype.getHardwareScalingLevel = function () {
  87726. return 1.0;
  87727. };
  87728. NullEngine.prototype.createVertexBuffer = function (vertices) {
  87729. return {
  87730. capacity: 0,
  87731. references: 1,
  87732. is32Bits: false
  87733. };
  87734. };
  87735. NullEngine.prototype.createIndexBuffer = function (indices) {
  87736. return {
  87737. capacity: 0,
  87738. references: 1,
  87739. is32Bits: false
  87740. };
  87741. };
  87742. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  87743. if (stencil === void 0) { stencil = false; }
  87744. };
  87745. NullEngine.prototype.getRenderWidth = function (useScreen) {
  87746. if (useScreen === void 0) { useScreen = false; }
  87747. if (!useScreen && this._currentRenderTarget) {
  87748. return this._currentRenderTarget.width;
  87749. }
  87750. return this._options.renderWidth;
  87751. };
  87752. NullEngine.prototype.getRenderHeight = function (useScreen) {
  87753. if (useScreen === void 0) { useScreen = false; }
  87754. if (!useScreen && this._currentRenderTarget) {
  87755. return this._currentRenderTarget.height;
  87756. }
  87757. return this._options.renderHeight;
  87758. };
  87759. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  87760. this._cachedViewport = viewport;
  87761. };
  87762. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  87763. return {
  87764. transformFeedback: null,
  87765. __SPECTOR_rebuildProgram: null
  87766. };
  87767. };
  87768. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  87769. return [];
  87770. };
  87771. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  87772. return [];
  87773. };
  87774. NullEngine.prototype.bindSamplers = function (effect) {
  87775. this._currentEffect = null;
  87776. };
  87777. NullEngine.prototype.enableEffect = function (effect) {
  87778. this._currentEffect = effect;
  87779. if (effect.onBind) {
  87780. effect.onBind(effect);
  87781. }
  87782. effect.onBindObservable.notifyObservers(effect);
  87783. };
  87784. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  87785. if (zOffset === void 0) { zOffset = 0; }
  87786. if (reverseSide === void 0) { reverseSide = false; }
  87787. };
  87788. NullEngine.prototype.setIntArray = function (uniform, array) {
  87789. };
  87790. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  87791. };
  87792. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  87793. };
  87794. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  87795. };
  87796. NullEngine.prototype.setFloatArray = function (uniform, array) {
  87797. };
  87798. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  87799. };
  87800. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  87801. };
  87802. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  87803. };
  87804. NullEngine.prototype.setArray = function (uniform, array) {
  87805. };
  87806. NullEngine.prototype.setArray2 = function (uniform, array) {
  87807. };
  87808. NullEngine.prototype.setArray3 = function (uniform, array) {
  87809. };
  87810. NullEngine.prototype.setArray4 = function (uniform, array) {
  87811. };
  87812. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  87813. };
  87814. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  87815. };
  87816. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  87817. };
  87818. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  87819. };
  87820. NullEngine.prototype.setFloat = function (uniform, value) {
  87821. };
  87822. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  87823. };
  87824. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  87825. };
  87826. NullEngine.prototype.setBool = function (uniform, bool) {
  87827. };
  87828. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  87829. };
  87830. NullEngine.prototype.setColor3 = function (uniform, color3) {
  87831. };
  87832. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  87833. };
  87834. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  87835. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  87836. if (this._alphaMode === mode) {
  87837. return;
  87838. }
  87839. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  87840. if (!noDepthWriteChange) {
  87841. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  87842. }
  87843. this._alphaMode = mode;
  87844. };
  87845. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  87846. };
  87847. NullEngine.prototype.wipeCaches = function (bruteForce) {
  87848. if (this.preventCacheWipeBetweenFrames) {
  87849. return;
  87850. }
  87851. this.resetTextureCache();
  87852. this._currentEffect = null;
  87853. if (bruteForce) {
  87854. this._currentProgram = null;
  87855. this._stencilState.reset();
  87856. this._depthCullingState.reset();
  87857. this._alphaState.reset();
  87858. }
  87859. this._cachedVertexBuffers = null;
  87860. this._cachedIndexBuffer = null;
  87861. this._cachedEffectForVertexBuffers = null;
  87862. };
  87863. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  87864. };
  87865. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  87866. };
  87867. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  87868. };
  87869. NullEngine.prototype._createTexture = function () {
  87870. return {};
  87871. };
  87872. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  87873. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  87874. if (onLoad === void 0) { onLoad = null; }
  87875. if (onError === void 0) { onError = null; }
  87876. if (buffer === void 0) { buffer = null; }
  87877. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  87878. var url = String(urlArg);
  87879. texture.url = url;
  87880. texture.generateMipMaps = !noMipmap;
  87881. texture.samplingMode = samplingMode;
  87882. texture.invertY = invertY;
  87883. texture.baseWidth = this._options.textureSize;
  87884. texture.baseHeight = this._options.textureSize;
  87885. texture.width = this._options.textureSize;
  87886. texture.height = this._options.textureSize;
  87887. if (format) {
  87888. texture.format = format;
  87889. }
  87890. texture.isReady = true;
  87891. if (onLoad) {
  87892. onLoad();
  87893. }
  87894. return texture;
  87895. };
  87896. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  87897. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  87898. if (options !== undefined && typeof options === "object") {
  87899. fullOptions.generateMipMaps = options.generateMipMaps;
  87900. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  87901. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  87902. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  87903. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  87904. }
  87905. else {
  87906. fullOptions.generateMipMaps = options;
  87907. fullOptions.generateDepthBuffer = true;
  87908. fullOptions.generateStencilBuffer = false;
  87909. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  87910. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  87911. }
  87912. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  87913. var width = size.width || size;
  87914. var height = size.height || size;
  87915. texture._depthStencilBuffer = {};
  87916. texture._framebuffer = {};
  87917. texture.baseWidth = width;
  87918. texture.baseHeight = height;
  87919. texture.width = width;
  87920. texture.height = height;
  87921. texture.isReady = true;
  87922. texture.samples = 1;
  87923. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  87924. texture.samplingMode = fullOptions.samplingMode;
  87925. texture.type = fullOptions.type;
  87926. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  87927. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  87928. return texture;
  87929. };
  87930. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  87931. texture.samplingMode = samplingMode;
  87932. };
  87933. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  87934. if (this._currentRenderTarget) {
  87935. this.unBindFramebuffer(this._currentRenderTarget);
  87936. }
  87937. this._currentRenderTarget = texture;
  87938. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  87939. if (this._cachedViewport && !forceFullscreenViewport) {
  87940. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  87941. }
  87942. };
  87943. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  87944. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  87945. this._currentRenderTarget = null;
  87946. if (onBeforeUnbind) {
  87947. if (texture._MSAAFramebuffer) {
  87948. this._currentFramebuffer = texture._framebuffer;
  87949. }
  87950. onBeforeUnbind();
  87951. }
  87952. this._currentFramebuffer = null;
  87953. };
  87954. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  87955. var vbo = {
  87956. capacity: 1,
  87957. references: 1,
  87958. is32Bits: false
  87959. };
  87960. return vbo;
  87961. };
  87962. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  87963. if (offset === void 0) { offset = 0; }
  87964. };
  87965. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  87966. };
  87967. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  87968. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  87969. this._boundTexturesCache[this._activeChannel] = texture;
  87970. }
  87971. };
  87972. NullEngine.prototype._bindTexture = function (channel, texture) {
  87973. if (channel < 0) {
  87974. return;
  87975. }
  87976. this._bindTextureDirectly(0, texture);
  87977. };
  87978. NullEngine.prototype._releaseBuffer = function (buffer) {
  87979. buffer.references--;
  87980. if (buffer.references === 0) {
  87981. return true;
  87982. }
  87983. return false;
  87984. };
  87985. return NullEngine;
  87986. }(BABYLON.Engine));
  87987. BABYLON.NullEngine = NullEngine;
  87988. })(BABYLON || (BABYLON = {}));
  87989. //# sourceMappingURL=babylon.nullEngine.js.map
  87990. var BABYLON;
  87991. (function (BABYLON) {
  87992. /**
  87993. * This class can be used to get instrumentation data from a Babylon engine
  87994. */
  87995. var EngineInstrumentation = /** @class */ (function () {
  87996. function EngineInstrumentation(engine) {
  87997. this.engine = engine;
  87998. this._captureGPUFrameTime = false;
  87999. this._gpuFrameTime = new BABYLON.PerfCounter();
  88000. this._captureShaderCompilationTime = false;
  88001. this._shaderCompilationTime = new BABYLON.PerfCounter();
  88002. // Observers
  88003. this._onBeginFrameObserver = null;
  88004. this._onEndFrameObserver = null;
  88005. this._onBeforeShaderCompilationObserver = null;
  88006. this._onAfterShaderCompilationObserver = null;
  88007. }
  88008. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  88009. // Properties
  88010. /**
  88011. * Gets the perf counter used for GPU frame time
  88012. */
  88013. get: function () {
  88014. return this._gpuFrameTime;
  88015. },
  88016. enumerable: true,
  88017. configurable: true
  88018. });
  88019. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  88020. /**
  88021. * Gets the GPU frame time capture status
  88022. */
  88023. get: function () {
  88024. return this._captureGPUFrameTime;
  88025. },
  88026. /**
  88027. * Enable or disable the GPU frame time capture
  88028. */
  88029. set: function (value) {
  88030. var _this = this;
  88031. if (value === this._captureGPUFrameTime) {
  88032. return;
  88033. }
  88034. this._captureGPUFrameTime = value;
  88035. if (value) {
  88036. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  88037. if (!_this._gpuFrameTimeToken) {
  88038. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  88039. }
  88040. });
  88041. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  88042. if (!_this._gpuFrameTimeToken) {
  88043. return;
  88044. }
  88045. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  88046. if (time > -1) {
  88047. _this._gpuFrameTimeToken = null;
  88048. _this._gpuFrameTime.fetchNewFrame();
  88049. _this._gpuFrameTime.addCount(time, true);
  88050. }
  88051. });
  88052. }
  88053. else {
  88054. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  88055. this._onBeginFrameObserver = null;
  88056. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  88057. this._onEndFrameObserver = null;
  88058. }
  88059. },
  88060. enumerable: true,
  88061. configurable: true
  88062. });
  88063. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  88064. /**
  88065. * Gets the perf counter used for shader compilation time
  88066. */
  88067. get: function () {
  88068. return this._shaderCompilationTime;
  88069. },
  88070. enumerable: true,
  88071. configurable: true
  88072. });
  88073. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  88074. /**
  88075. * Gets the shader compilation time capture status
  88076. */
  88077. get: function () {
  88078. return this._captureShaderCompilationTime;
  88079. },
  88080. /**
  88081. * Enable or disable the shader compilation time capture
  88082. */
  88083. set: function (value) {
  88084. var _this = this;
  88085. if (value === this._captureShaderCompilationTime) {
  88086. return;
  88087. }
  88088. this._captureShaderCompilationTime = value;
  88089. if (value) {
  88090. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  88091. _this._shaderCompilationTime.fetchNewFrame();
  88092. _this._shaderCompilationTime.beginMonitoring();
  88093. });
  88094. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  88095. _this._shaderCompilationTime.endMonitoring();
  88096. });
  88097. }
  88098. else {
  88099. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  88100. this._onBeforeShaderCompilationObserver = null;
  88101. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  88102. this._onAfterShaderCompilationObserver = null;
  88103. }
  88104. },
  88105. enumerable: true,
  88106. configurable: true
  88107. });
  88108. EngineInstrumentation.prototype.dispose = function () {
  88109. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  88110. this._onBeginFrameObserver = null;
  88111. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  88112. this._onEndFrameObserver = null;
  88113. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  88114. this._onBeforeShaderCompilationObserver = null;
  88115. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  88116. this._onAfterShaderCompilationObserver = null;
  88117. this.engine = null;
  88118. };
  88119. return EngineInstrumentation;
  88120. }());
  88121. BABYLON.EngineInstrumentation = EngineInstrumentation;
  88122. })(BABYLON || (BABYLON = {}));
  88123. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  88124. var BABYLON;
  88125. (function (BABYLON) {
  88126. /**
  88127. * This class can be used to get instrumentation data from a Babylon engine
  88128. */
  88129. var SceneInstrumentation = /** @class */ (function () {
  88130. function SceneInstrumentation(scene) {
  88131. var _this = this;
  88132. this.scene = scene;
  88133. this._captureActiveMeshesEvaluationTime = false;
  88134. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  88135. this._captureRenderTargetsRenderTime = false;
  88136. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  88137. this._captureFrameTime = false;
  88138. this._frameTime = new BABYLON.PerfCounter();
  88139. this._captureRenderTime = false;
  88140. this._renderTime = new BABYLON.PerfCounter();
  88141. this._captureInterFrameTime = false;
  88142. this._interFrameTime = new BABYLON.PerfCounter();
  88143. this._captureParticlesRenderTime = false;
  88144. this._particlesRenderTime = new BABYLON.PerfCounter();
  88145. this._captureSpritesRenderTime = false;
  88146. this._spritesRenderTime = new BABYLON.PerfCounter();
  88147. this._capturePhysicsTime = false;
  88148. this._physicsTime = new BABYLON.PerfCounter();
  88149. this._captureAnimationsTime = false;
  88150. this._animationsTime = new BABYLON.PerfCounter();
  88151. // Observers
  88152. this._onBeforeActiveMeshesEvaluationObserver = null;
  88153. this._onAfterActiveMeshesEvaluationObserver = null;
  88154. this._onBeforeRenderTargetsRenderObserver = null;
  88155. this._onAfterRenderTargetsRenderObserver = null;
  88156. this._onAfterRenderObserver = null;
  88157. this._onBeforeDrawPhaseObserver = null;
  88158. this._onAfterDrawPhaseObserver = null;
  88159. this._onBeforeAnimationsObserver = null;
  88160. this._onBeforeParticlesRenderingObserver = null;
  88161. this._onAfterParticlesRenderingObserver = null;
  88162. this._onBeforeSpritesRenderingObserver = null;
  88163. this._onAfterSpritesRenderingObserver = null;
  88164. this._onBeforePhysicsObserver = null;
  88165. this._onAfterPhysicsObserver = null;
  88166. this._onAfterAnimationsObserver = null;
  88167. // Before render
  88168. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  88169. if (_this._captureActiveMeshesEvaluationTime) {
  88170. _this._activeMeshesEvaluationTime.fetchNewFrame();
  88171. }
  88172. if (_this._captureRenderTargetsRenderTime) {
  88173. _this._renderTargetsRenderTime.fetchNewFrame();
  88174. }
  88175. if (_this._captureFrameTime) {
  88176. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  88177. _this._frameTime.beginMonitoring();
  88178. }
  88179. if (_this._captureInterFrameTime) {
  88180. _this._interFrameTime.endMonitoring();
  88181. }
  88182. if (_this._captureParticlesRenderTime) {
  88183. _this._particlesRenderTime.fetchNewFrame();
  88184. }
  88185. if (_this._captureSpritesRenderTime) {
  88186. _this._spritesRenderTime.fetchNewFrame();
  88187. }
  88188. if (_this._captureAnimationsTime) {
  88189. _this._animationsTime.beginMonitoring();
  88190. }
  88191. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  88192. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  88193. });
  88194. // After render
  88195. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  88196. if (_this._captureFrameTime) {
  88197. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  88198. _this._frameTime.endMonitoring();
  88199. }
  88200. if (_this._captureRenderTime) {
  88201. _this._renderTime.endMonitoring(false);
  88202. }
  88203. if (_this._captureInterFrameTime) {
  88204. _this._interFrameTime.beginMonitoring();
  88205. }
  88206. });
  88207. }
  88208. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  88209. // Properties
  88210. /**
  88211. * Gets the perf counter used for active meshes evaluation time
  88212. */
  88213. get: function () {
  88214. return this._activeMeshesEvaluationTime;
  88215. },
  88216. enumerable: true,
  88217. configurable: true
  88218. });
  88219. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  88220. /**
  88221. * Gets the active meshes evaluation time capture status
  88222. */
  88223. get: function () {
  88224. return this._captureActiveMeshesEvaluationTime;
  88225. },
  88226. /**
  88227. * Enable or disable the active meshes evaluation time capture
  88228. */
  88229. set: function (value) {
  88230. var _this = this;
  88231. if (value === this._captureActiveMeshesEvaluationTime) {
  88232. return;
  88233. }
  88234. this._captureActiveMeshesEvaluationTime = value;
  88235. if (value) {
  88236. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  88237. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  88238. _this._activeMeshesEvaluationTime.beginMonitoring();
  88239. });
  88240. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  88241. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  88242. _this._activeMeshesEvaluationTime.endMonitoring();
  88243. });
  88244. }
  88245. else {
  88246. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  88247. this._onBeforeActiveMeshesEvaluationObserver = null;
  88248. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  88249. this._onAfterActiveMeshesEvaluationObserver = null;
  88250. }
  88251. },
  88252. enumerable: true,
  88253. configurable: true
  88254. });
  88255. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  88256. /**
  88257. * Gets the perf counter used for render targets render time
  88258. */
  88259. get: function () {
  88260. return this._renderTargetsRenderTime;
  88261. },
  88262. enumerable: true,
  88263. configurable: true
  88264. });
  88265. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  88266. /**
  88267. * Gets the render targets render time capture status
  88268. */
  88269. get: function () {
  88270. return this._captureRenderTargetsRenderTime;
  88271. },
  88272. /**
  88273. * Enable or disable the render targets render time capture
  88274. */
  88275. set: function (value) {
  88276. var _this = this;
  88277. if (value === this._captureRenderTargetsRenderTime) {
  88278. return;
  88279. }
  88280. this._captureRenderTargetsRenderTime = value;
  88281. if (value) {
  88282. this._onBeforeRenderTargetsRenderObserver = this.scene.OnBeforeRenderTargetsRenderObservable.add(function () {
  88283. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  88284. _this._renderTargetsRenderTime.beginMonitoring();
  88285. });
  88286. this._onAfterRenderTargetsRenderObserver = this.scene.OnAfterRenderTargetsRenderObservable.add(function () {
  88287. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  88288. _this._renderTargetsRenderTime.endMonitoring(false);
  88289. });
  88290. }
  88291. else {
  88292. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  88293. this._onBeforeRenderTargetsRenderObserver = null;
  88294. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  88295. this._onAfterRenderTargetsRenderObserver = null;
  88296. }
  88297. },
  88298. enumerable: true,
  88299. configurable: true
  88300. });
  88301. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  88302. /**
  88303. * Gets the perf counter used for particles render time
  88304. */
  88305. get: function () {
  88306. return this._particlesRenderTime;
  88307. },
  88308. enumerable: true,
  88309. configurable: true
  88310. });
  88311. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  88312. /**
  88313. * Gets the particles render time capture status
  88314. */
  88315. get: function () {
  88316. return this._captureParticlesRenderTime;
  88317. },
  88318. /**
  88319. * Enable or disable the particles render time capture
  88320. */
  88321. set: function (value) {
  88322. var _this = this;
  88323. if (value === this._captureParticlesRenderTime) {
  88324. return;
  88325. }
  88326. this._captureParticlesRenderTime = value;
  88327. if (value) {
  88328. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  88329. BABYLON.Tools.StartPerformanceCounter("Particles");
  88330. _this._particlesRenderTime.beginMonitoring();
  88331. });
  88332. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  88333. BABYLON.Tools.EndPerformanceCounter("Particles");
  88334. _this._particlesRenderTime.endMonitoring(false);
  88335. });
  88336. }
  88337. else {
  88338. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  88339. this._onBeforeParticlesRenderingObserver = null;
  88340. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  88341. this._onAfterParticlesRenderingObserver = null;
  88342. }
  88343. },
  88344. enumerable: true,
  88345. configurable: true
  88346. });
  88347. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  88348. /**
  88349. * Gets the perf counter used for sprites render time
  88350. */
  88351. get: function () {
  88352. return this._spritesRenderTime;
  88353. },
  88354. enumerable: true,
  88355. configurable: true
  88356. });
  88357. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  88358. /**
  88359. * Gets the sprites render time capture status
  88360. */
  88361. get: function () {
  88362. return this._captureSpritesRenderTime;
  88363. },
  88364. /**
  88365. * Enable or disable the sprites render time capture
  88366. */
  88367. set: function (value) {
  88368. var _this = this;
  88369. if (value === this._captureSpritesRenderTime) {
  88370. return;
  88371. }
  88372. this._captureSpritesRenderTime = value;
  88373. if (value) {
  88374. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  88375. BABYLON.Tools.StartPerformanceCounter("Sprites");
  88376. _this._spritesRenderTime.beginMonitoring();
  88377. });
  88378. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  88379. BABYLON.Tools.EndPerformanceCounter("Sprites");
  88380. _this._spritesRenderTime.endMonitoring(false);
  88381. });
  88382. }
  88383. else {
  88384. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  88385. this._onBeforeSpritesRenderingObserver = null;
  88386. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  88387. this._onAfterSpritesRenderingObserver = null;
  88388. }
  88389. },
  88390. enumerable: true,
  88391. configurable: true
  88392. });
  88393. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  88394. /**
  88395. * Gets the perf counter used for physics time
  88396. */
  88397. get: function () {
  88398. return this._physicsTime;
  88399. },
  88400. enumerable: true,
  88401. configurable: true
  88402. });
  88403. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  88404. /**
  88405. * Gets the physics time capture status
  88406. */
  88407. get: function () {
  88408. return this._capturePhysicsTime;
  88409. },
  88410. /**
  88411. * Enable or disable the physics time capture
  88412. */
  88413. set: function (value) {
  88414. var _this = this;
  88415. if (value === this._capturePhysicsTime) {
  88416. return;
  88417. }
  88418. this._capturePhysicsTime = value;
  88419. if (value) {
  88420. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  88421. BABYLON.Tools.StartPerformanceCounter("Physics");
  88422. _this._physicsTime.beginMonitoring();
  88423. });
  88424. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  88425. BABYLON.Tools.EndPerformanceCounter("Physics");
  88426. _this._physicsTime.endMonitoring();
  88427. });
  88428. }
  88429. else {
  88430. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  88431. this._onBeforePhysicsObserver = null;
  88432. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  88433. this._onAfterPhysicsObserver = null;
  88434. }
  88435. },
  88436. enumerable: true,
  88437. configurable: true
  88438. });
  88439. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  88440. /**
  88441. * Gets the perf counter used for animations time
  88442. */
  88443. get: function () {
  88444. return this._animationsTime;
  88445. },
  88446. enumerable: true,
  88447. configurable: true
  88448. });
  88449. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  88450. /**
  88451. * Gets the animations time capture status
  88452. */
  88453. get: function () {
  88454. return this._captureAnimationsTime;
  88455. },
  88456. /**
  88457. * Enable or disable the animations time capture
  88458. */
  88459. set: function (value) {
  88460. var _this = this;
  88461. if (value === this._captureAnimationsTime) {
  88462. return;
  88463. }
  88464. this._captureAnimationsTime = value;
  88465. if (value) {
  88466. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  88467. _this._animationsTime.endMonitoring();
  88468. });
  88469. }
  88470. else {
  88471. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  88472. this._onAfterAnimationsObserver = null;
  88473. }
  88474. },
  88475. enumerable: true,
  88476. configurable: true
  88477. });
  88478. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  88479. /**
  88480. * Gets the perf counter used for frame time capture
  88481. */
  88482. get: function () {
  88483. return this._frameTime;
  88484. },
  88485. enumerable: true,
  88486. configurable: true
  88487. });
  88488. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  88489. /**
  88490. * Gets the frame time capture status
  88491. */
  88492. get: function () {
  88493. return this._captureFrameTime;
  88494. },
  88495. /**
  88496. * Enable or disable the frame time capture
  88497. */
  88498. set: function (value) {
  88499. this._captureFrameTime = value;
  88500. },
  88501. enumerable: true,
  88502. configurable: true
  88503. });
  88504. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  88505. /**
  88506. * Gets the perf counter used for inter-frames time capture
  88507. */
  88508. get: function () {
  88509. return this._interFrameTime;
  88510. },
  88511. enumerable: true,
  88512. configurable: true
  88513. });
  88514. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  88515. /**
  88516. * Gets the inter-frames time capture status
  88517. */
  88518. get: function () {
  88519. return this._captureInterFrameTime;
  88520. },
  88521. /**
  88522. * Enable or disable the inter-frames time capture
  88523. */
  88524. set: function (value) {
  88525. this._captureInterFrameTime = value;
  88526. },
  88527. enumerable: true,
  88528. configurable: true
  88529. });
  88530. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  88531. /**
  88532. * Gets the perf counter used for render time capture
  88533. */
  88534. get: function () {
  88535. return this._renderTime;
  88536. },
  88537. enumerable: true,
  88538. configurable: true
  88539. });
  88540. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  88541. /**
  88542. * Gets the render time capture status
  88543. */
  88544. get: function () {
  88545. return this._captureRenderTime;
  88546. },
  88547. /**
  88548. * Enable or disable the render time capture
  88549. */
  88550. set: function (value) {
  88551. var _this = this;
  88552. if (value === this._captureRenderTime) {
  88553. return;
  88554. }
  88555. this._captureRenderTime = value;
  88556. if (value) {
  88557. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  88558. _this._renderTime.beginMonitoring();
  88559. BABYLON.Tools.StartPerformanceCounter("Main render");
  88560. });
  88561. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  88562. _this._renderTime.endMonitoring(false);
  88563. BABYLON.Tools.EndPerformanceCounter("Main render");
  88564. });
  88565. }
  88566. else {
  88567. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  88568. this._onBeforeDrawPhaseObserver = null;
  88569. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  88570. this._onAfterDrawPhaseObserver = null;
  88571. }
  88572. },
  88573. enumerable: true,
  88574. configurable: true
  88575. });
  88576. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  88577. /**
  88578. * Gets the perf counter used for draw calls
  88579. */
  88580. get: function () {
  88581. return this.scene.getEngine()._drawCalls;
  88582. },
  88583. enumerable: true,
  88584. configurable: true
  88585. });
  88586. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  88587. /**
  88588. * Gets the perf counter used for texture collisions
  88589. */
  88590. get: function () {
  88591. return this.scene.getEngine()._textureCollisions;
  88592. },
  88593. enumerable: true,
  88594. configurable: true
  88595. });
  88596. SceneInstrumentation.prototype.dispose = function () {
  88597. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  88598. this._onAfterRenderObserver = null;
  88599. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  88600. this._onBeforeActiveMeshesEvaluationObserver = null;
  88601. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  88602. this._onAfterActiveMeshesEvaluationObserver = null;
  88603. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  88604. this._onBeforeRenderTargetsRenderObserver = null;
  88605. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  88606. this._onAfterRenderTargetsRenderObserver = null;
  88607. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  88608. this._onBeforeAnimationsObserver = null;
  88609. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  88610. this._onBeforeParticlesRenderingObserver = null;
  88611. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  88612. this._onAfterParticlesRenderingObserver = null;
  88613. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  88614. this._onBeforeSpritesRenderingObserver = null;
  88615. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  88616. this._onAfterSpritesRenderingObserver = null;
  88617. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  88618. this._onBeforeDrawPhaseObserver = null;
  88619. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  88620. this._onAfterDrawPhaseObserver = null;
  88621. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  88622. this._onBeforePhysicsObserver = null;
  88623. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  88624. this._onAfterPhysicsObserver = null;
  88625. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  88626. this._onAfterAnimationsObserver = null;
  88627. this.scene = null;
  88628. };
  88629. return SceneInstrumentation;
  88630. }());
  88631. BABYLON.SceneInstrumentation = SceneInstrumentation;
  88632. })(BABYLON || (BABYLON = {}));
  88633. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  88634. var BABYLON;
  88635. (function (BABYLON) {
  88636. var _TimeToken = /** @class */ (function () {
  88637. function _TimeToken() {
  88638. this._timeElapsedQueryEnded = false;
  88639. }
  88640. return _TimeToken;
  88641. }());
  88642. BABYLON._TimeToken = _TimeToken;
  88643. })(BABYLON || (BABYLON = {}));
  88644. //# sourceMappingURL=babylon.timeToken.js.map
  88645. var BABYLON;
  88646. (function (BABYLON) {
  88647. /**
  88648. * Background material defines definition.
  88649. * @ignore Mainly internal Use
  88650. */
  88651. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  88652. __extends(BackgroundMaterialDefines, _super);
  88653. /**
  88654. * Constructor of the defines.
  88655. */
  88656. function BackgroundMaterialDefines() {
  88657. var _this = _super.call(this) || this;
  88658. /**
  88659. * True if the diffuse texture is in use.
  88660. */
  88661. _this.DIFFUSE = false;
  88662. /**
  88663. * The direct UV channel to use.
  88664. */
  88665. _this.DIFFUSEDIRECTUV = 0;
  88666. /**
  88667. * True if the diffuse texture is in gamma space.
  88668. */
  88669. _this.GAMMADIFFUSE = false;
  88670. /**
  88671. * True if the diffuse texture has opacity in the alpha channel.
  88672. */
  88673. _this.DIFFUSEHASALPHA = false;
  88674. /**
  88675. * True if you want the material to fade to transparent at grazing angle.
  88676. */
  88677. _this.OPACITYFRESNEL = false;
  88678. /**
  88679. * True if an extra blur needs to be added in the reflection.
  88680. */
  88681. _this.REFLECTIONBLUR = false;
  88682. /**
  88683. * True if you want the material to fade to reflection at grazing angle.
  88684. */
  88685. _this.REFLECTIONFRESNEL = false;
  88686. /**
  88687. * True if you want the material to falloff as far as you move away from the scene center.
  88688. */
  88689. _this.REFLECTIONFALLOFF = false;
  88690. /**
  88691. * False if the current Webgl implementation does not support the texture lod extension.
  88692. */
  88693. _this.TEXTURELODSUPPORT = false;
  88694. /**
  88695. * True to ensure the data are premultiplied.
  88696. */
  88697. _this.PREMULTIPLYALPHA = false;
  88698. /**
  88699. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  88700. */
  88701. _this.USERGBCOLOR = false;
  88702. /**
  88703. * True to add noise in order to reduce the banding effect.
  88704. */
  88705. _this.NOISE = false;
  88706. /**
  88707. * is the reflection texture in BGR color scheme?
  88708. * Mainly used to solve a bug in ios10 video tag
  88709. */
  88710. _this.REFLECTIONBGR = false;
  88711. _this.IMAGEPROCESSING = false;
  88712. _this.VIGNETTE = false;
  88713. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  88714. _this.VIGNETTEBLENDMODEOPAQUE = false;
  88715. _this.TONEMAPPING = false;
  88716. _this.CONTRAST = false;
  88717. _this.COLORCURVES = false;
  88718. _this.COLORGRADING = false;
  88719. _this.COLORGRADING3D = false;
  88720. _this.SAMPLER3DGREENDEPTH = false;
  88721. _this.SAMPLER3DBGRMAP = false;
  88722. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  88723. _this.EXPOSURE = false;
  88724. // Reflection.
  88725. _this.REFLECTION = false;
  88726. _this.REFLECTIONMAP_3D = false;
  88727. _this.REFLECTIONMAP_SPHERICAL = false;
  88728. _this.REFLECTIONMAP_PLANAR = false;
  88729. _this.REFLECTIONMAP_CUBIC = false;
  88730. _this.REFLECTIONMAP_PROJECTION = false;
  88731. _this.REFLECTIONMAP_SKYBOX = false;
  88732. _this.REFLECTIONMAP_EXPLICIT = false;
  88733. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  88734. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  88735. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  88736. _this.INVERTCUBICMAP = false;
  88737. _this.REFLECTIONMAP_OPPOSITEZ = false;
  88738. _this.LODINREFLECTIONALPHA = false;
  88739. _this.GAMMAREFLECTION = false;
  88740. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  88741. // Default BJS.
  88742. _this.MAINUV1 = false;
  88743. _this.MAINUV2 = false;
  88744. _this.UV1 = false;
  88745. _this.UV2 = false;
  88746. _this.CLIPPLANE = false;
  88747. _this.POINTSIZE = false;
  88748. _this.FOG = false;
  88749. _this.NORMAL = false;
  88750. _this.NUM_BONE_INFLUENCERS = 0;
  88751. _this.BonesPerMesh = 0;
  88752. _this.INSTANCES = false;
  88753. _this.SHADOWFLOAT = false;
  88754. _this.rebuild();
  88755. return _this;
  88756. }
  88757. return BackgroundMaterialDefines;
  88758. }(BABYLON.MaterialDefines));
  88759. /**
  88760. * Background material used to create an efficient environement around your scene.
  88761. */
  88762. var BackgroundMaterial = /** @class */ (function (_super) {
  88763. __extends(BackgroundMaterial, _super);
  88764. /**
  88765. * Instantiates a Background Material in the given scene
  88766. * @param name The friendly name of the material
  88767. * @param scene The scene to add the material to
  88768. */
  88769. function BackgroundMaterial(name, scene) {
  88770. var _this = _super.call(this, name, scene) || this;
  88771. /**
  88772. * Key light Color (multiply against the R channel of the environement texture)
  88773. */
  88774. _this.primaryColor = BABYLON.Color3.White();
  88775. /**
  88776. * Key light Level (allowing HDR output of the background)
  88777. */
  88778. _this.primaryLevel = 1;
  88779. /**
  88780. * Secondary light Color (multiply against the G channel of the environement texture)
  88781. */
  88782. _this.secondaryColor = BABYLON.Color3.Gray();
  88783. /**
  88784. * Secondary light Level (allowing HDR output of the background)
  88785. */
  88786. _this.secondaryLevel = 1;
  88787. /**
  88788. * Tertiary light Color (multiply against the B channel of the environement texture)
  88789. */
  88790. _this.tertiaryColor = BABYLON.Color3.Black();
  88791. /**
  88792. * Tertiary light Level (allowing HDR output of the background)
  88793. */
  88794. _this.tertiaryLevel = 1;
  88795. /**
  88796. * Reflection Texture used in the material.
  88797. * Should be author in a specific way for the best result (refer to the documentation).
  88798. */
  88799. _this.reflectionTexture = null;
  88800. /**
  88801. * Reflection Texture level of blur.
  88802. *
  88803. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  88804. * texture twice.
  88805. */
  88806. _this.reflectionBlur = 0;
  88807. /**
  88808. * Diffuse Texture used in the material.
  88809. * Should be author in a specific way for the best result (refer to the documentation).
  88810. */
  88811. _this.diffuseTexture = null;
  88812. _this._shadowLights = null;
  88813. /**
  88814. * Specify the list of lights casting shadow on the material.
  88815. * All scene shadow lights will be included if null.
  88816. */
  88817. _this.shadowLights = null;
  88818. /**
  88819. * For the lights having a blurred shadow generator, this can add a second blur pass in order to reach
  88820. * soft lighting on the background.
  88821. */
  88822. _this.shadowBlurScale = 1;
  88823. /**
  88824. * Helps adjusting the shadow to a softer level if required.
  88825. * 0 means black shadows and 1 means no shadows.
  88826. */
  88827. _this.shadowLevel = 0;
  88828. /**
  88829. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  88830. * It is usually zero but might be interesting to modify according to your setup.
  88831. */
  88832. _this.sceneCenter = BABYLON.Vector3.Zero();
  88833. /**
  88834. * This helps specifying that the material is falling off to the sky box at grazing angle.
  88835. * This helps ensuring a nice transition when the camera goes under the ground.
  88836. */
  88837. _this.opacityFresnel = true;
  88838. /**
  88839. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  88840. * This helps adding a mirror texture on the ground.
  88841. */
  88842. _this.reflectionFresnel = false;
  88843. /**
  88844. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  88845. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  88846. */
  88847. _this.reflectionFalloffDistance = 0.0;
  88848. /**
  88849. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  88850. */
  88851. _this.reflectionAmount = 1.0;
  88852. /**
  88853. * This specifies the weight of the reflection at grazing angle.
  88854. */
  88855. _this.reflectionReflectance0 = 0.05;
  88856. /**
  88857. * This specifies the weight of the reflection at a perpendicular point of view.
  88858. */
  88859. _this.reflectionReflectance90 = 0.5;
  88860. /**
  88861. * Helps to directly use the maps channels instead of their level.
  88862. */
  88863. _this.useRGBColor = true;
  88864. /**
  88865. * This helps reducing the banding effect that could occur on the background.
  88866. */
  88867. _this.enableNoise = false;
  88868. _this._fovMultiplier = 1.0;
  88869. /**
  88870. * Enable the FOV adjustment feature controlled by fovMultiplier.
  88871. * @type {boolean}
  88872. */
  88873. _this.useEquirectangularFOV = false;
  88874. _this._maxSimultaneousLights = 4;
  88875. /**
  88876. * Number of Simultaneous lights allowed on the material.
  88877. */
  88878. _this.maxSimultaneousLights = 4;
  88879. /**
  88880. * Keep track of the image processing observer to allow dispose and replace.
  88881. */
  88882. _this._imageProcessingObserver = null;
  88883. /**
  88884. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  88885. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  88886. */
  88887. _this.switchToBGR = false;
  88888. // Temp values kept as cache in the material.
  88889. _this._renderTargets = new BABYLON.SmartArray(16);
  88890. _this._reflectionControls = BABYLON.Vector4.Zero();
  88891. // Setup the default processing configuration to the scene.
  88892. _this._attachImageProcessingConfiguration(null);
  88893. _this.getRenderTargetTextures = function () {
  88894. _this._renderTargets.reset();
  88895. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  88896. _this._renderTargets.push(_this._diffuseTexture);
  88897. }
  88898. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  88899. _this._renderTargets.push(_this._reflectionTexture);
  88900. }
  88901. return _this._renderTargets;
  88902. };
  88903. return _this;
  88904. }
  88905. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  88906. /**
  88907. * Sets the reflection reflectance fresnel values according to the default standard
  88908. * empirically know to work well :-)
  88909. */
  88910. set: function (value) {
  88911. var reflectionWeight = value;
  88912. if (reflectionWeight < 0.5) {
  88913. reflectionWeight = reflectionWeight * 2.0;
  88914. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  88915. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  88916. }
  88917. else {
  88918. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  88919. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  88920. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  88921. }
  88922. },
  88923. enumerable: true,
  88924. configurable: true
  88925. });
  88926. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  88927. /**
  88928. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  88929. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  88930. * Recommended to be keep at 1.0 except for special cases.
  88931. */
  88932. get: function () {
  88933. return this._fovMultiplier;
  88934. },
  88935. set: function (value) {
  88936. if (isNaN(value)) {
  88937. value = 1.0;
  88938. }
  88939. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  88940. },
  88941. enumerable: true,
  88942. configurable: true
  88943. });
  88944. /**
  88945. * Attaches a new image processing configuration to the PBR Material.
  88946. * @param configuration (if null the scene configuration will be use)
  88947. */
  88948. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  88949. var _this = this;
  88950. if (configuration === this._imageProcessingConfiguration) {
  88951. return;
  88952. }
  88953. // Detaches observer.
  88954. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  88955. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  88956. }
  88957. // Pick the scene configuration if needed.
  88958. if (!configuration) {
  88959. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  88960. }
  88961. else {
  88962. this._imageProcessingConfiguration = configuration;
  88963. }
  88964. // Attaches observer.
  88965. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  88966. _this._markAllSubMeshesAsImageProcessingDirty();
  88967. });
  88968. };
  88969. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  88970. /**
  88971. * Gets the image processing configuration used either in this material.
  88972. */
  88973. get: function () {
  88974. return this._imageProcessingConfiguration;
  88975. },
  88976. /**
  88977. * Sets the Default image processing configuration used either in the this material.
  88978. *
  88979. * If sets to null, the scene one is in use.
  88980. */
  88981. set: function (value) {
  88982. this._attachImageProcessingConfiguration(value);
  88983. // Ensure the effect will be rebuilt.
  88984. this._markAllSubMeshesAsTexturesDirty();
  88985. },
  88986. enumerable: true,
  88987. configurable: true
  88988. });
  88989. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  88990. /**
  88991. * Gets wether the color curves effect is enabled.
  88992. */
  88993. get: function () {
  88994. return this.imageProcessingConfiguration.colorCurvesEnabled;
  88995. },
  88996. /**
  88997. * Sets wether the color curves effect is enabled.
  88998. */
  88999. set: function (value) {
  89000. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  89001. },
  89002. enumerable: true,
  89003. configurable: true
  89004. });
  89005. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  89006. /**
  89007. * Gets wether the color grading effect is enabled.
  89008. */
  89009. get: function () {
  89010. return this.imageProcessingConfiguration.colorGradingEnabled;
  89011. },
  89012. /**
  89013. * Gets wether the color grading effect is enabled.
  89014. */
  89015. set: function (value) {
  89016. this.imageProcessingConfiguration.colorGradingEnabled = value;
  89017. },
  89018. enumerable: true,
  89019. configurable: true
  89020. });
  89021. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  89022. /**
  89023. * Gets wether tonemapping is enabled or not.
  89024. */
  89025. get: function () {
  89026. return this._imageProcessingConfiguration.toneMappingEnabled;
  89027. },
  89028. /**
  89029. * Sets wether tonemapping is enabled or not
  89030. */
  89031. set: function (value) {
  89032. this._imageProcessingConfiguration.toneMappingEnabled = value;
  89033. },
  89034. enumerable: true,
  89035. configurable: true
  89036. });
  89037. ;
  89038. ;
  89039. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  89040. /**
  89041. * The camera exposure used on this material.
  89042. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  89043. * This corresponds to a photographic exposure.
  89044. */
  89045. get: function () {
  89046. return this._imageProcessingConfiguration.exposure;
  89047. },
  89048. /**
  89049. * The camera exposure used on this material.
  89050. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  89051. * This corresponds to a photographic exposure.
  89052. */
  89053. set: function (value) {
  89054. this._imageProcessingConfiguration.exposure = value;
  89055. },
  89056. enumerable: true,
  89057. configurable: true
  89058. });
  89059. ;
  89060. ;
  89061. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  89062. /**
  89063. * Gets The camera contrast used on this material.
  89064. */
  89065. get: function () {
  89066. return this._imageProcessingConfiguration.contrast;
  89067. },
  89068. /**
  89069. * Sets The camera contrast used on this material.
  89070. */
  89071. set: function (value) {
  89072. this._imageProcessingConfiguration.contrast = value;
  89073. },
  89074. enumerable: true,
  89075. configurable: true
  89076. });
  89077. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  89078. /**
  89079. * Gets the Color Grading 2D Lookup Texture.
  89080. */
  89081. get: function () {
  89082. return this._imageProcessingConfiguration.colorGradingTexture;
  89083. },
  89084. /**
  89085. * Sets the Color Grading 2D Lookup Texture.
  89086. */
  89087. set: function (value) {
  89088. this.imageProcessingConfiguration.colorGradingTexture = value;
  89089. },
  89090. enumerable: true,
  89091. configurable: true
  89092. });
  89093. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  89094. /**
  89095. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  89096. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  89097. * 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;
  89098. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  89099. */
  89100. get: function () {
  89101. return this.imageProcessingConfiguration.colorCurves;
  89102. },
  89103. /**
  89104. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  89105. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  89106. * 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;
  89107. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  89108. */
  89109. set: function (value) {
  89110. this.imageProcessingConfiguration.colorCurves = value;
  89111. },
  89112. enumerable: true,
  89113. configurable: true
  89114. });
  89115. /**
  89116. * The entire material has been created in order to prevent overdraw.
  89117. * @returns false
  89118. */
  89119. BackgroundMaterial.prototype.needAlphaTesting = function () {
  89120. return true;
  89121. };
  89122. /**
  89123. * The entire material has been created in order to prevent overdraw.
  89124. * @returns true if blending is enable
  89125. */
  89126. BackgroundMaterial.prototype.needAlphaBlending = function () {
  89127. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  89128. };
  89129. /**
  89130. * Checks wether the material is ready to be rendered for a given mesh.
  89131. * @param mesh The mesh to render
  89132. * @param subMesh The submesh to check against
  89133. * @param useInstances Specify wether or not the material is used with instances
  89134. * @returns true if all the dependencies are ready (Textures, Effects...)
  89135. */
  89136. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  89137. var _this = this;
  89138. if (useInstances === void 0) { useInstances = false; }
  89139. if (subMesh.effect && this.isFrozen) {
  89140. if (this._wasPreviouslyReady) {
  89141. return true;
  89142. }
  89143. }
  89144. if (!subMesh._materialDefines) {
  89145. subMesh._materialDefines = new BackgroundMaterialDefines();
  89146. }
  89147. var scene = this.getScene();
  89148. var defines = subMesh._materialDefines;
  89149. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  89150. if (defines._renderId === scene.getRenderId()) {
  89151. return true;
  89152. }
  89153. }
  89154. var engine = scene.getEngine();
  89155. // Lights
  89156. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  89157. defines._needNormals = true;
  89158. // Textures
  89159. if (defines._areTexturesDirty) {
  89160. defines._needUVs = false;
  89161. if (scene.texturesEnabled) {
  89162. if (scene.getEngine().getCaps().textureLOD) {
  89163. defines.TEXTURELODSUPPORT = true;
  89164. }
  89165. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  89166. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  89167. return false;
  89168. }
  89169. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  89170. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  89171. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  89172. defines.OPACITYFRESNEL = this._opacityFresnel;
  89173. }
  89174. else {
  89175. defines.DIFFUSE = false;
  89176. defines.DIFFUSEHASALPHA = false;
  89177. defines.GAMMADIFFUSE = false;
  89178. defines.OPACITYFRESNEL = false;
  89179. }
  89180. var reflectionTexture = this._reflectionTexture;
  89181. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  89182. if (!reflectionTexture.isReadyOrNotBlocking()) {
  89183. return false;
  89184. }
  89185. defines.REFLECTION = true;
  89186. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  89187. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  89188. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  89189. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  89190. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  89191. defines.REFLECTIONBGR = this.switchToBGR;
  89192. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  89193. defines.INVERTCUBICMAP = true;
  89194. }
  89195. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  89196. switch (reflectionTexture.coordinatesMode) {
  89197. case BABYLON.Texture.CUBIC_MODE:
  89198. case BABYLON.Texture.INVCUBIC_MODE:
  89199. defines.REFLECTIONMAP_CUBIC = true;
  89200. break;
  89201. case BABYLON.Texture.EXPLICIT_MODE:
  89202. defines.REFLECTIONMAP_EXPLICIT = true;
  89203. break;
  89204. case BABYLON.Texture.PLANAR_MODE:
  89205. defines.REFLECTIONMAP_PLANAR = true;
  89206. break;
  89207. case BABYLON.Texture.PROJECTION_MODE:
  89208. defines.REFLECTIONMAP_PROJECTION = true;
  89209. break;
  89210. case BABYLON.Texture.SKYBOX_MODE:
  89211. defines.REFLECTIONMAP_SKYBOX = true;
  89212. break;
  89213. case BABYLON.Texture.SPHERICAL_MODE:
  89214. defines.REFLECTIONMAP_SPHERICAL = true;
  89215. break;
  89216. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  89217. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  89218. break;
  89219. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  89220. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  89221. break;
  89222. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  89223. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  89224. break;
  89225. }
  89226. if (this.reflectionFresnel) {
  89227. defines.REFLECTIONFRESNEL = true;
  89228. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  89229. this._reflectionControls.x = this.reflectionAmount;
  89230. this._reflectionControls.y = this.reflectionReflectance0;
  89231. this._reflectionControls.z = this.reflectionReflectance90;
  89232. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  89233. }
  89234. else {
  89235. defines.REFLECTIONFRESNEL = false;
  89236. defines.REFLECTIONFALLOFF = false;
  89237. }
  89238. }
  89239. else {
  89240. defines.REFLECTION = false;
  89241. defines.REFLECTIONFALLOFF = false;
  89242. defines.REFLECTIONBLUR = false;
  89243. defines.REFLECTIONMAP_3D = false;
  89244. defines.REFLECTIONMAP_SPHERICAL = false;
  89245. defines.REFLECTIONMAP_PLANAR = false;
  89246. defines.REFLECTIONMAP_CUBIC = false;
  89247. defines.REFLECTIONMAP_PROJECTION = false;
  89248. defines.REFLECTIONMAP_SKYBOX = false;
  89249. defines.REFLECTIONMAP_EXPLICIT = false;
  89250. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  89251. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  89252. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  89253. defines.INVERTCUBICMAP = false;
  89254. defines.REFLECTIONMAP_OPPOSITEZ = false;
  89255. defines.LODINREFLECTIONALPHA = false;
  89256. defines.GAMMAREFLECTION = false;
  89257. }
  89258. }
  89259. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  89260. defines.USERGBCOLOR = this._useRGBColor;
  89261. defines.NOISE = this._enableNoise;
  89262. }
  89263. if (defines._areImageProcessingDirty) {
  89264. if (!this._imageProcessingConfiguration.isReady()) {
  89265. return false;
  89266. }
  89267. this._imageProcessingConfiguration.prepareDefines(defines);
  89268. }
  89269. // Misc.
  89270. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  89271. // Values that need to be evaluated on every frame
  89272. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  89273. // Attribs
  89274. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  89275. if (mesh) {
  89276. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  89277. mesh.createNormals(true);
  89278. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  89279. }
  89280. }
  89281. }
  89282. // Get correct effect
  89283. if (defines.isDirty) {
  89284. defines.markAsProcessed();
  89285. scene.resetCachedMaterial();
  89286. // Fallbacks
  89287. var fallbacks = new BABYLON.EffectFallbacks();
  89288. if (defines.FOG) {
  89289. fallbacks.addFallback(0, "FOG");
  89290. }
  89291. if (defines.POINTSIZE) {
  89292. fallbacks.addFallback(1, "POINTSIZE");
  89293. }
  89294. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  89295. if (defines.NUM_BONE_INFLUENCERS > 0) {
  89296. fallbacks.addCPUSkinningFallback(0, mesh);
  89297. }
  89298. //Attributes
  89299. var attribs = [BABYLON.VertexBuffer.PositionKind];
  89300. if (defines.NORMAL) {
  89301. attribs.push(BABYLON.VertexBuffer.NormalKind);
  89302. }
  89303. if (defines.UV1) {
  89304. attribs.push(BABYLON.VertexBuffer.UVKind);
  89305. }
  89306. if (defines.UV2) {
  89307. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  89308. }
  89309. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  89310. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  89311. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  89312. "vFogInfos", "vFogColor", "pointSize",
  89313. "vClipPlane", "mBones",
  89314. "vPrimaryColor", "vSecondaryColor", "vTertiaryColor",
  89315. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  89316. "shadowLevel", "alpha",
  89317. "vBackgroundCenter", "vReflectionControl",
  89318. "vDiffuseInfos", "diffuseMatrix",
  89319. ];
  89320. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  89321. var uniformBuffers = ["Material", "Scene"];
  89322. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  89323. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  89324. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  89325. uniformsNames: uniforms,
  89326. uniformBuffersNames: uniformBuffers,
  89327. samplers: samplers,
  89328. defines: defines,
  89329. maxSimultaneousLights: this._maxSimultaneousLights
  89330. });
  89331. var onCompiled = function (effect) {
  89332. if (_this.onCompiled) {
  89333. _this.onCompiled(effect);
  89334. }
  89335. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  89336. };
  89337. var join = defines.toString();
  89338. subMesh.setEffect(scene.getEngine().createEffect("background", {
  89339. attributes: attribs,
  89340. uniformsNames: uniforms,
  89341. uniformBuffersNames: uniformBuffers,
  89342. samplers: samplers,
  89343. defines: join,
  89344. fallbacks: fallbacks,
  89345. onCompiled: onCompiled,
  89346. onError: this.onError,
  89347. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  89348. }, engine), defines);
  89349. this.buildUniformLayout();
  89350. }
  89351. if (!subMesh.effect || !subMesh.effect.isReady()) {
  89352. return false;
  89353. }
  89354. defines._renderId = scene.getRenderId();
  89355. this._wasPreviouslyReady = true;
  89356. return true;
  89357. };
  89358. /**
  89359. * Build the uniform buffer used in the material.
  89360. */
  89361. BackgroundMaterial.prototype.buildUniformLayout = function () {
  89362. // Order is important !
  89363. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  89364. this._uniformBuffer.addUniform("vSecondaryColor", 4);
  89365. this._uniformBuffer.addUniform("vTertiaryColor", 4);
  89366. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  89367. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  89368. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  89369. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  89370. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  89371. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  89372. this._uniformBuffer.addUniform("pointSize", 1);
  89373. this._uniformBuffer.addUniform("shadowLevel", 1);
  89374. this._uniformBuffer.addUniform("alpha", 1);
  89375. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  89376. this._uniformBuffer.addUniform("vReflectionControl", 4);
  89377. this._uniformBuffer.create();
  89378. };
  89379. /**
  89380. * Unbind the material.
  89381. */
  89382. BackgroundMaterial.prototype.unbind = function () {
  89383. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  89384. this._uniformBuffer.setTexture("diffuseSampler", null);
  89385. }
  89386. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  89387. this._uniformBuffer.setTexture("reflectionSampler", null);
  89388. }
  89389. _super.prototype.unbind.call(this);
  89390. };
  89391. /**
  89392. * Bind only the world matrix to the material.
  89393. * @param world The world matrix to bind.
  89394. */
  89395. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  89396. this._activeEffect.setMatrix("world", world);
  89397. };
  89398. /**
  89399. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  89400. * @param world The world matrix to bind.
  89401. * @param subMesh The submesh to bind for.
  89402. */
  89403. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  89404. var scene = this.getScene();
  89405. var defines = subMesh._materialDefines;
  89406. if (!defines) {
  89407. return;
  89408. }
  89409. var effect = subMesh.effect;
  89410. if (!effect) {
  89411. return;
  89412. }
  89413. this._activeEffect = effect;
  89414. // Matrices
  89415. this.bindOnlyWorldMatrix(world);
  89416. // Bones
  89417. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  89418. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  89419. if (mustRebind) {
  89420. this._uniformBuffer.bindToEffect(effect, "Material");
  89421. this.bindViewProjection(effect);
  89422. var reflectionTexture = this._reflectionTexture;
  89423. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  89424. // Texture uniforms
  89425. if (scene.texturesEnabled) {
  89426. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  89427. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  89428. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  89429. }
  89430. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  89431. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  89432. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  89433. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  89434. }
  89435. }
  89436. if (this.shadowLevel > 0) {
  89437. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  89438. }
  89439. this._uniformBuffer.updateFloat("alpha", this.alpha);
  89440. // Point size
  89441. if (this.pointsCloud) {
  89442. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  89443. }
  89444. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, this._primaryLevel);
  89445. this._uniformBuffer.updateColor4("vSecondaryColor", this._secondaryColor, this._secondaryLevel);
  89446. this._uniformBuffer.updateColor4("vTertiaryColor", this._tertiaryColor, this._tertiaryLevel);
  89447. }
  89448. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  89449. // Textures
  89450. if (scene.texturesEnabled) {
  89451. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  89452. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  89453. }
  89454. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  89455. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  89456. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  89457. }
  89458. else if (!defines.REFLECTIONBLUR) {
  89459. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  89460. }
  89461. else {
  89462. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  89463. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  89464. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  89465. }
  89466. if (defines.REFLECTIONFRESNEL) {
  89467. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  89468. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  89469. }
  89470. }
  89471. }
  89472. // Clip plane
  89473. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  89474. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  89475. }
  89476. if (mustRebind || !this.isFrozen) {
  89477. if (scene.lightsEnabled) {
  89478. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  89479. }
  89480. // View
  89481. this.bindView(effect);
  89482. // Fog
  89483. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  89484. // image processing
  89485. this._imageProcessingConfiguration.bind(this._activeEffect);
  89486. }
  89487. this._uniformBuffer.update();
  89488. this._afterBind(mesh);
  89489. };
  89490. /**
  89491. * Dispose the material.
  89492. * @param forceDisposeEffect Force disposal of the associated effect.
  89493. * @param forceDisposeTextures Force disposal of the associated textures.
  89494. */
  89495. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  89496. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  89497. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  89498. if (forceDisposeTextures) {
  89499. if (this.diffuseTexture) {
  89500. this.diffuseTexture.dispose();
  89501. }
  89502. if (this.reflectionTexture) {
  89503. this.reflectionTexture.dispose();
  89504. }
  89505. }
  89506. this._renderTargets.dispose();
  89507. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  89508. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  89509. }
  89510. _super.prototype.dispose.call(this, forceDisposeEffect);
  89511. };
  89512. /**
  89513. * Clones the material.
  89514. * @param name The cloned name.
  89515. * @returns The cloned material.
  89516. */
  89517. BackgroundMaterial.prototype.clone = function (name) {
  89518. var _this = this;
  89519. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  89520. };
  89521. /**
  89522. * Serializes the current material to its JSON representation.
  89523. * @returns The JSON representation.
  89524. */
  89525. BackgroundMaterial.prototype.serialize = function () {
  89526. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  89527. serializationObject.customType = "BABYLON.BackgroundMaterial";
  89528. return serializationObject;
  89529. };
  89530. /**
  89531. * Gets the class name of the material
  89532. * @returns "BackgroundMaterial"
  89533. */
  89534. BackgroundMaterial.prototype.getClassName = function () {
  89535. return "BackgroundMaterial";
  89536. };
  89537. /**
  89538. * Parse a JSON input to create back a background material.
  89539. * @param source The JSON data to parse
  89540. * @param scene The scene to create the parsed material in
  89541. * @param rootUrl The root url of the assets the material depends upon
  89542. * @returns the instantiated BackgroundMaterial.
  89543. */
  89544. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  89545. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  89546. };
  89547. /**
  89548. * Standard reflectance value at parallel view angle.
  89549. */
  89550. BackgroundMaterial.StandardReflectance0 = 0.05;
  89551. /**
  89552. * Standard reflectance value at grazing angle.
  89553. */
  89554. BackgroundMaterial.StandardReflectance90 = 0.5;
  89555. __decorate([
  89556. BABYLON.serializeAsColor3()
  89557. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  89558. __decorate([
  89559. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  89560. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  89561. __decorate([
  89562. BABYLON.serialize()
  89563. ], BackgroundMaterial.prototype, "_primaryLevel", void 0);
  89564. __decorate([
  89565. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  89566. ], BackgroundMaterial.prototype, "primaryLevel", void 0);
  89567. __decorate([
  89568. BABYLON.serializeAsColor3()
  89569. ], BackgroundMaterial.prototype, "_secondaryColor", void 0);
  89570. __decorate([
  89571. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  89572. ], BackgroundMaterial.prototype, "secondaryColor", void 0);
  89573. __decorate([
  89574. BABYLON.serialize()
  89575. ], BackgroundMaterial.prototype, "_secondaryLevel", void 0);
  89576. __decorate([
  89577. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  89578. ], BackgroundMaterial.prototype, "secondaryLevel", void 0);
  89579. __decorate([
  89580. BABYLON.serializeAsColor3()
  89581. ], BackgroundMaterial.prototype, "_tertiaryColor", void 0);
  89582. __decorate([
  89583. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  89584. ], BackgroundMaterial.prototype, "tertiaryColor", void 0);
  89585. __decorate([
  89586. BABYLON.serialize()
  89587. ], BackgroundMaterial.prototype, "_tertiaryLevel", void 0);
  89588. __decorate([
  89589. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  89590. ], BackgroundMaterial.prototype, "tertiaryLevel", void 0);
  89591. __decorate([
  89592. BABYLON.serializeAsTexture()
  89593. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  89594. __decorate([
  89595. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89596. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  89597. __decorate([
  89598. BABYLON.serialize()
  89599. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  89600. __decorate([
  89601. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89602. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  89603. __decorate([
  89604. BABYLON.serializeAsTexture()
  89605. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  89606. __decorate([
  89607. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89608. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  89609. __decorate([
  89610. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89611. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  89612. __decorate([
  89613. BABYLON.serialize()
  89614. ], BackgroundMaterial.prototype, "_shadowBlurScale", void 0);
  89615. __decorate([
  89616. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89617. ], BackgroundMaterial.prototype, "shadowBlurScale", void 0);
  89618. __decorate([
  89619. BABYLON.serialize()
  89620. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  89621. __decorate([
  89622. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89623. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  89624. __decorate([
  89625. BABYLON.serializeAsVector3()
  89626. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  89627. __decorate([
  89628. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89629. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  89630. __decorate([
  89631. BABYLON.serialize()
  89632. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  89633. __decorate([
  89634. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89635. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  89636. __decorate([
  89637. BABYLON.serialize()
  89638. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  89639. __decorate([
  89640. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89641. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  89642. __decorate([
  89643. BABYLON.serialize()
  89644. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  89645. __decorate([
  89646. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89647. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  89648. __decorate([
  89649. BABYLON.serialize()
  89650. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  89651. __decorate([
  89652. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89653. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  89654. __decorate([
  89655. BABYLON.serialize()
  89656. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  89657. __decorate([
  89658. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89659. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  89660. __decorate([
  89661. BABYLON.serialize()
  89662. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  89663. __decorate([
  89664. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89665. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  89666. __decorate([
  89667. BABYLON.serialize()
  89668. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  89669. __decorate([
  89670. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89671. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  89672. __decorate([
  89673. BABYLON.serialize()
  89674. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  89675. __decorate([
  89676. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89677. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  89678. __decorate([
  89679. BABYLON.serialize()
  89680. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  89681. __decorate([
  89682. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89683. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  89684. __decorate([
  89685. BABYLON.serializeAsImageProcessingConfiguration()
  89686. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  89687. return BackgroundMaterial;
  89688. }(BABYLON.PushMaterial));
  89689. BABYLON.BackgroundMaterial = BackgroundMaterial;
  89690. })(BABYLON || (BABYLON = {}));
  89691. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  89692. var __assign = (this && this.__assign) || Object.assign || function(t) {
  89693. for (var s, i = 1, n = arguments.length; i < n; i++) {
  89694. s = arguments[i];
  89695. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  89696. t[p] = s[p];
  89697. }
  89698. return t;
  89699. };
  89700. var BABYLON;
  89701. (function (BABYLON) {
  89702. /**
  89703. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  89704. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  89705. * It also helps with the default setup of your imageProcessing configuration.
  89706. */
  89707. var EnvironmentHelper = /** @class */ (function () {
  89708. /**
  89709. * constructor
  89710. * @param options
  89711. * @param scene The scene to add the material to
  89712. */
  89713. function EnvironmentHelper(options, scene) {
  89714. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  89715. this._scene = scene;
  89716. this._setupBackground();
  89717. this._setupImageProcessing();
  89718. }
  89719. /**
  89720. * Creates the default options for the helper.
  89721. */
  89722. EnvironmentHelper._getDefaultOptions = function () {
  89723. return {
  89724. createGround: true,
  89725. groundSize: 15,
  89726. groundTexture: this._groundTextureCDNUrl,
  89727. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  89728. groundOpacity: 0.9,
  89729. enableGroundShadow: true,
  89730. groundShadowLevel: 0.5,
  89731. enableGroundMirror: false,
  89732. groundMirrorSizeRatio: 0.3,
  89733. groundMirrorBlurKernel: 64,
  89734. groundMirrorAmount: 1,
  89735. groundMirrorFresnelWeight: 1,
  89736. groundMirrorFallOffDistance: 0,
  89737. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  89738. groundYBias: 0.00001,
  89739. createSkybox: true,
  89740. skyboxSize: 20,
  89741. skyboxTexture: this._skyboxTextureCDNUrl,
  89742. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  89743. backgroundYRotation: 0,
  89744. sizeAuto: true,
  89745. rootPosition: BABYLON.Vector3.Zero(),
  89746. setupImageProcessing: true,
  89747. environmentTexture: this._environmentTextureCDNUrl,
  89748. cameraExposure: 0.8,
  89749. cameraContrast: 1.2,
  89750. toneMappingEnabled: true,
  89751. };
  89752. };
  89753. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  89754. /**
  89755. * Gets the root mesh created by the helper.
  89756. */
  89757. get: function () {
  89758. return this._rootMesh;
  89759. },
  89760. enumerable: true,
  89761. configurable: true
  89762. });
  89763. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  89764. /**
  89765. * Gets the skybox created by the helper.
  89766. */
  89767. get: function () {
  89768. return this._skybox;
  89769. },
  89770. enumerable: true,
  89771. configurable: true
  89772. });
  89773. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  89774. /**
  89775. * Gets the skybox texture created by the helper.
  89776. */
  89777. get: function () {
  89778. return this._skyboxTexture;
  89779. },
  89780. enumerable: true,
  89781. configurable: true
  89782. });
  89783. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  89784. /**
  89785. * Gets the skybox material created by the helper.
  89786. */
  89787. get: function () {
  89788. return this._skyboxMaterial;
  89789. },
  89790. enumerable: true,
  89791. configurable: true
  89792. });
  89793. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  89794. /**
  89795. * Gets the ground mesh created by the helper.
  89796. */
  89797. get: function () {
  89798. return this._ground;
  89799. },
  89800. enumerable: true,
  89801. configurable: true
  89802. });
  89803. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  89804. /**
  89805. * Gets the ground texture created by the helper.
  89806. */
  89807. get: function () {
  89808. return this._groundTexture;
  89809. },
  89810. enumerable: true,
  89811. configurable: true
  89812. });
  89813. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  89814. /**
  89815. * Gets the ground mirror created by the helper.
  89816. */
  89817. get: function () {
  89818. return this._groundMirror;
  89819. },
  89820. enumerable: true,
  89821. configurable: true
  89822. });
  89823. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  89824. /**
  89825. * Gets the ground mirror render list to helps pushing the meshes
  89826. * you wish in the ground reflection.
  89827. */
  89828. get: function () {
  89829. if (this._groundMirror) {
  89830. return this._groundMirror.renderList;
  89831. }
  89832. return null;
  89833. },
  89834. enumerable: true,
  89835. configurable: true
  89836. });
  89837. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  89838. /**
  89839. * Gets the ground material created by the helper.
  89840. */
  89841. get: function () {
  89842. return this._groundMaterial;
  89843. },
  89844. enumerable: true,
  89845. configurable: true
  89846. });
  89847. /**
  89848. * Updates the background according to the new options
  89849. * @param options
  89850. */
  89851. EnvironmentHelper.prototype.updateOptions = function (options) {
  89852. var newOptions = __assign({}, this._options, options);
  89853. if (this._ground && !newOptions.createGround) {
  89854. this._ground.dispose();
  89855. this._ground = null;
  89856. }
  89857. if (this._groundMaterial && !newOptions.createGround) {
  89858. this._groundMaterial.dispose();
  89859. this._groundMaterial = null;
  89860. }
  89861. if (this._groundTexture) {
  89862. if (this._options.groundTexture != newOptions.groundTexture) {
  89863. this._groundTexture.dispose();
  89864. this._groundTexture = null;
  89865. }
  89866. }
  89867. if (this._skybox && !newOptions.createSkybox) {
  89868. this._skybox.dispose();
  89869. this._skybox = null;
  89870. }
  89871. if (this._skyboxMaterial && !newOptions.createSkybox) {
  89872. this._skyboxMaterial.dispose();
  89873. this._skyboxMaterial = null;
  89874. }
  89875. if (this._skyboxTexture) {
  89876. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  89877. this._skyboxTexture.dispose();
  89878. this._skyboxTexture = null;
  89879. }
  89880. }
  89881. if (this._groundMirror && !newOptions.enableGroundMirror) {
  89882. this._groundMirror.dispose();
  89883. this._groundMirror = null;
  89884. }
  89885. if (this._scene.environmentTexture) {
  89886. if (this._options.environmentTexture != newOptions.environmentTexture) {
  89887. this._scene.environmentTexture.dispose();
  89888. }
  89889. }
  89890. this._options = newOptions;
  89891. this._setupBackground();
  89892. this._setupImageProcessing();
  89893. };
  89894. /**
  89895. * Sets the primary color of all the available elements.
  89896. * @param color
  89897. */
  89898. EnvironmentHelper.prototype.setMainColor = function (color) {
  89899. if (this.groundMaterial) {
  89900. this.groundMaterial.primaryColor = color;
  89901. }
  89902. if (this.skyboxMaterial) {
  89903. this.skyboxMaterial.primaryColor = color;
  89904. }
  89905. if (this.groundMirror) {
  89906. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  89907. }
  89908. };
  89909. /**
  89910. * Setup the image processing according to the specified options.
  89911. */
  89912. EnvironmentHelper.prototype._setupImageProcessing = function () {
  89913. if (this._options.setupImageProcessing) {
  89914. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  89915. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  89916. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  89917. this._setupEnvironmentTexture();
  89918. }
  89919. };
  89920. /**
  89921. * Setup the environment texture according to the specified options.
  89922. */
  89923. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  89924. if (this._scene.environmentTexture) {
  89925. return;
  89926. }
  89927. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  89928. this._scene.environmentTexture = this._options.environmentTexture;
  89929. return;
  89930. }
  89931. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  89932. this._scene.environmentTexture = environmentTexture;
  89933. };
  89934. /**
  89935. * Setup the background according to the specified options.
  89936. */
  89937. EnvironmentHelper.prototype._setupBackground = function () {
  89938. if (!this._rootMesh) {
  89939. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  89940. }
  89941. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  89942. var sceneSize = this._getSceneSize();
  89943. if (this._options.createGround) {
  89944. this._setupGround(sceneSize);
  89945. this._setupGroundMaterial();
  89946. this._setupGroundDiffuseTexture();
  89947. if (this._options.enableGroundMirror) {
  89948. this._setupGroundMirrorTexture(sceneSize);
  89949. }
  89950. this._setupMirrorInGroundMaterial();
  89951. }
  89952. if (this._options.createSkybox) {
  89953. this._setupSkybox(sceneSize);
  89954. this._setupSkyboxMaterial();
  89955. this._setupSkyboxReflectionTexture();
  89956. }
  89957. this._rootMesh.position.x = sceneSize.rootPosition.x;
  89958. this._rootMesh.position.z = sceneSize.rootPosition.z;
  89959. this._rootMesh.position.y = sceneSize.rootPosition.y;
  89960. };
  89961. /**
  89962. * Get the scene sizes according to the setup.
  89963. */
  89964. EnvironmentHelper.prototype._getSceneSize = function () {
  89965. var _this = this;
  89966. var groundSize = this._options.groundSize;
  89967. var skyboxSize = this._options.skyboxSize;
  89968. var rootPosition = this._options.rootPosition;
  89969. if (!this._scene.meshes || this._scene.meshes.length === 1) {
  89970. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  89971. }
  89972. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  89973. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  89974. });
  89975. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  89976. if (this._options.sizeAuto) {
  89977. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  89978. this._scene.activeCamera.upperRadiusLimit) {
  89979. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  89980. skyboxSize = groundSize;
  89981. }
  89982. var sceneDiagonalLenght = sceneDiagonal.length();
  89983. if (sceneDiagonalLenght > groundSize) {
  89984. groundSize = sceneDiagonalLenght * 2;
  89985. skyboxSize = groundSize;
  89986. }
  89987. // 10 % bigger.
  89988. groundSize *= 1.1;
  89989. skyboxSize *= 1.5;
  89990. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  89991. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  89992. }
  89993. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  89994. };
  89995. /**
  89996. * Setup the ground according to the specified options.
  89997. */
  89998. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  89999. var _this = this;
  90000. if (!this._ground) {
  90001. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  90002. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  90003. this._ground.parent = this._rootMesh;
  90004. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  90005. }
  90006. this._ground.receiveShadows = this._options.enableGroundShadow;
  90007. };
  90008. /**
  90009. * Setup the ground material according to the specified options.
  90010. */
  90011. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  90012. if (!this._groundMaterial) {
  90013. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  90014. }
  90015. this._groundMaterial.alpha = this._options.groundOpacity;
  90016. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  90017. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  90018. this._groundMaterial.primaryLevel = 1;
  90019. this._groundMaterial.primaryColor = this._options.groundColor;
  90020. this._groundMaterial.secondaryLevel = 0;
  90021. this._groundMaterial.tertiaryLevel = 0;
  90022. this._groundMaterial.useRGBColor = false;
  90023. this._groundMaterial.enableNoise = true;
  90024. if (this._ground) {
  90025. this._ground.material = this._groundMaterial;
  90026. }
  90027. };
  90028. /**
  90029. * Setup the ground diffuse texture according to the specified options.
  90030. */
  90031. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  90032. if (!this._groundMaterial) {
  90033. return;
  90034. }
  90035. if (this._groundTexture) {
  90036. return;
  90037. }
  90038. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  90039. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  90040. return;
  90041. }
  90042. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene);
  90043. diffuseTexture.gammaSpace = false;
  90044. diffuseTexture.hasAlpha = true;
  90045. this._groundMaterial.diffuseTexture = diffuseTexture;
  90046. };
  90047. /**
  90048. * Setup the ground mirror texture according to the specified options.
  90049. */
  90050. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  90051. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  90052. if (!this._groundMirror) {
  90053. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  90054. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  90055. this._groundMirror.anisotropicFilteringLevel = 1;
  90056. this._groundMirror.wrapU = wrapping;
  90057. this._groundMirror.wrapV = wrapping;
  90058. this._groundMirror.gammaSpace = false;
  90059. if (this._groundMirror.renderList) {
  90060. for (var i = 0; i < this._scene.meshes.length; i++) {
  90061. var mesh = this._scene.meshes[i];
  90062. if (mesh !== this._ground &&
  90063. mesh !== this._skybox &&
  90064. mesh !== this._rootMesh) {
  90065. this._groundMirror.renderList.push(mesh);
  90066. }
  90067. }
  90068. }
  90069. }
  90070. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  90071. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  90072. };
  90073. /**
  90074. * Setup the ground to receive the mirror texture.
  90075. */
  90076. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  90077. if (this._groundMaterial) {
  90078. this._groundMaterial.reflectionTexture = this._groundMirror;
  90079. this._groundMaterial.reflectionFresnel = true;
  90080. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  90081. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  90082. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  90083. }
  90084. };
  90085. /**
  90086. * Setup the skybox according to the specified options.
  90087. */
  90088. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  90089. var _this = this;
  90090. if (!this._skybox) {
  90091. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  90092. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  90093. }
  90094. this._skybox.parent = this._rootMesh;
  90095. };
  90096. /**
  90097. * Setup the skybox material according to the specified options.
  90098. */
  90099. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  90100. if (!this._skybox) {
  90101. return;
  90102. }
  90103. if (!this._skyboxMaterial) {
  90104. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  90105. }
  90106. this._skyboxMaterial.useRGBColor = false;
  90107. this._skyboxMaterial.primaryLevel = 1;
  90108. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  90109. this._skyboxMaterial.secondaryLevel = 0;
  90110. this._skyboxMaterial.tertiaryLevel = 0;
  90111. this._skyboxMaterial.enableNoise = true;
  90112. this._skybox.material = this._skyboxMaterial;
  90113. };
  90114. /**
  90115. * Setup the skybox reflection texture according to the specified options.
  90116. */
  90117. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  90118. if (!this._skyboxMaterial) {
  90119. return;
  90120. }
  90121. if (this._skyboxTexture) {
  90122. return;
  90123. }
  90124. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  90125. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  90126. return;
  90127. }
  90128. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene);
  90129. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  90130. this._skyboxTexture.gammaSpace = false;
  90131. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  90132. };
  90133. /**
  90134. * Dispose all the elements created by the Helper.
  90135. */
  90136. EnvironmentHelper.prototype.dispose = function () {
  90137. if (this._groundMaterial) {
  90138. this._groundMaterial.dispose(true, true);
  90139. }
  90140. if (this._skyboxMaterial) {
  90141. this._skyboxMaterial.dispose(true, true);
  90142. }
  90143. this._rootMesh.dispose(false);
  90144. };
  90145. /**
  90146. * Default ground texture URL.
  90147. */
  90148. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  90149. /**
  90150. * Default skybox texture URL.
  90151. */
  90152. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  90153. /**
  90154. * Default environment texture URL.
  90155. */
  90156. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.dds";
  90157. return EnvironmentHelper;
  90158. }());
  90159. BABYLON.EnvironmentHelper = EnvironmentHelper;
  90160. })(BABYLON || (BABYLON = {}));
  90161. //# sourceMappingURL=babylon.environmentHelper.js.map
  90162. var BABYLON;
  90163. (function (BABYLON) {
  90164. /**
  90165. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  90166. * As a subclass of Node, this allow parenting to the camera or multiple videos with different locations in the scene.
  90167. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  90168. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  90169. */
  90170. var VideoDome = /** @class */ (function (_super) {
  90171. __extends(VideoDome, _super);
  90172. /**
  90173. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  90174. * @param name Element's name, child elements will append suffixes for their own names.
  90175. * @param urlsOrVideo
  90176. * @param options An object containing optional or exposed sub element properties:
  90177. * @param options **resolution=12** Integer, lower resolutions have more artifacts at extreme fovs
  90178. * @param options **clickToPlay=false** Add a click to play listener to the video, does not prevent autoplay.
  90179. * @param options **autoPlay=true** Automatically attempt to being playing the video.
  90180. * @param options **loop=true** Automatically loop video on end.
  90181. * @param options **size=1000** Physical radius to create the dome at, defaults to approximately half the far clip plane.
  90182. */
  90183. function VideoDome(name, urlsOrVideo, options, scene) {
  90184. var _this = _super.call(this, name, scene) || this;
  90185. // set defaults and manage values
  90186. name = name || "videoDome";
  90187. options.resolution = (Math.abs(options.resolution) | 0) || 12;
  90188. options.clickToPlay = Boolean(options.clickToPlay);
  90189. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  90190. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  90191. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  90192. // create
  90193. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true };
  90194. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  90195. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  90196. _this._mesh = BABYLON.MeshBuilder.CreateIcoSphere(name + "_mesh", {
  90197. flat: false,
  90198. radius: options.size,
  90199. subdivisions: options.resolution,
  90200. sideOrientation: BABYLON.Mesh.BACKSIDE // needs to be inside out
  90201. }, scene);
  90202. // configure material
  90203. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  90204. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE; // always clamp the up/down
  90205. material.reflectionTexture = _this._videoTexture;
  90206. material.useEquirectangularFOV = true;
  90207. material.fovMultiplier = 1.0;
  90208. // configure mesh
  90209. _this._mesh.material = material;
  90210. _this._mesh.parent = _this;
  90211. // optional configuration
  90212. if (options.clickToPlay) {
  90213. scene.onPointerUp = function () {
  90214. _this._videoTexture.video.play();
  90215. };
  90216. }
  90217. return _this;
  90218. }
  90219. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  90220. /**
  90221. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  90222. * Also see the options.resolution property.
  90223. */
  90224. get: function () {
  90225. return this._material.fovMultiplier;
  90226. },
  90227. set: function (value) {
  90228. this._material.fovMultiplier = value;
  90229. },
  90230. enumerable: true,
  90231. configurable: true
  90232. });
  90233. /**
  90234. * Releases all associated resources
  90235. */
  90236. VideoDome.prototype.dispose = function () {
  90237. _super.prototype.dispose.call(this);
  90238. this._videoTexture.dispose();
  90239. this._mesh.dispose();
  90240. this._material.dispose();
  90241. };
  90242. return VideoDome;
  90243. }(BABYLON.Node));
  90244. BABYLON.VideoDome = VideoDome;
  90245. })(BABYLON || (BABYLON = {}));
  90246. //# sourceMappingURL=babylon.videoDome.js.map
  90247. BABYLON.Effect.ShadersStore={"defaultVertexShader":"#include<__decl__defaultVertex>\n\n#define CUSTOM_VERTEX_BEGIN\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nvarying vec2 vSpecularUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec3 positionUpdated=position;\n#ifdef NORMAL \nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#define CUSTOM_VERTEX_UPDATE_POSITION\n#define CUSTOM_VERTEX_UPDATE_NORMAL\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif\n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<bumpVertex>\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n#define CUSTOM_VERTEX_MAIN_END\n}\n","defaultPixelShader":"#include<__decl__defaultFragment>\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#define CUSTOM_FRAGMENT_BEGIN\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\n#if SPECULARDIRECTUV == 1\n#define vSpecularUV vMainUV1\n#elif SPECULARDIRECTUV == 2\n#define vSpecularUV vMainUV2\n#else\nvarying vec2 vSpecularUV;\n#endif\nuniform sampler2D specularSampler;\n#endif\n\n#include<fresnelFunction>\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#include<imageProcessingDeclaration>\n#include<imageProcessingFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW)));\n#endif\n#include<bumpFragment>\n#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_ALPHA\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_DIFFUSE\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_LIGHTS\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0)\n{\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb*vRefractionInfos.x;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb*vRefractionInfos.x;\n#endif\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb*vReflectionInfos.x;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb*vReflectionInfos.x;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb*vReflectionInfos.x;\n#endif\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FOG\n#include<logDepthFragment>\n#include<fogFragment>\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ncolor.rgb=toLinearSpace(color.rgb);\n#else\n#ifdef IMAGEPROCESSING\ncolor.rgb=toLinearSpace(color.rgb);\ncolor=applyImageProcessing(color);\n#endif\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR\ngl_FragColor=color;\n}\n","pbrVertexShader":"precision highp float;\n#include<__decl__pbrVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif \n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#if defined(ALBEDO) && ALBEDODIRECTUV == 0\nvarying vec2 vAlbedoUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0\nvarying vec2 vReflectivityUV;\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#include<harmonicsFunctions>\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\nvEnvironmentIrradiance=environmentIrradianceJones(reflectionVector);\n#endif\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif \n#if defined(ALBEDO) && ALBEDODIRECTUV == 0 \nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0 \nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0 \nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0 \nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0 \nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0 \nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0 \nif (vMicroSurfaceSamplerInfos.x == 0.)\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0 \nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<bumpVertex>\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","pbrPixelShader":"#if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\n#include<__decl__pbrFragment>\nuniform vec4 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vCameraInfos;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2;\n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\n#if ALBEDODIRECTUV == 1\n#define vAlbedoUV vMainUV1\n#elif ALBEDODIRECTUV == 2\n#define vAlbedoUV vMainUV2\n#else\nvarying vec2 vAlbedoUV;\n#endif\nuniform sampler2D albedoSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY\n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFLECTIVITY\n#if REFLECTIVITYDIRECTUV == 1\n#define vReflectivityUV vMainUV1\n#elif REFLECTIVITYDIRECTUV == 2\n#define vReflectivityUV vMainUV2\n#else\nvarying vec2 vReflectivityUV;\n#endif\nuniform sampler2D reflectivitySampler;\n#endif\n#ifdef MICROSURFACEMAP\n#if MICROSURFACEMAPDIRECTUV == 1\n#define vMicroSurfaceSamplerUV vMainUV1\n#elif MICROSURFACEMAPDIRECTUV == 2\n#define vMicroSurfaceSamplerUV vMainUV2\n#else\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\nuniform sampler2D microSurfaceSampler;\n#endif\n\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\n#define sampleRefraction(s,c) textureCube(s,c)\nuniform samplerCube refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#else\n#define sampleRefraction(s,c) texture2D(s,c)\nuniform sampler2D refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#endif\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef ENVIRONMENTBRDF\nuniform sampler2D environmentBrdfSampler;\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\n\n#include<shadowsFragmentFunctions>\n#include<pbrFunctions>\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\n\n\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#endif\n#include<bumpFragment>\n#if defined(FORCENORMALFORWARD) && defined(NORMAL)\nvec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#if defined(TWOSIDEDLIGHTING)\nfaceNormal=gl_FrontFacing ? faceNormal : -faceNormal;\n#endif\nnormalW*=sign(dot(normalW,faceNormal));\n#endif\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n\n\nvec3 surfaceAlbedo=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nvec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);\n#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST)\nalpha*=albedoTexture.a;\n#endif\nsurfaceAlbedo*=toLinearSpace(albedoTexture.rgb);\nsurfaceAlbedo*=vAlbedoInfos.y;\n#endif\n\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nalpha=getLuminance(opacityMap.rgb);\n#else\nalpha*=opacityMap.a;\n#endif\nalpha*=vOpacityInfos.y;\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#if !defined(LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL)\n#ifdef ALPHATEST\nif (alpha<=ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nsurfaceAlbedo*=vColor.rgb;\n#endif\n\nvec3 ambientOcclusionColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nvec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#ifdef AMBIENTINGRAYSCALE\nambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r);\n#endif\nambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z);\n#endif\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef METALLICWORKFLOW\nvec2 metallicRoughness=surfaceReflectivityColor.rg;\n#ifdef REFLECTIVITY\nvec4 surfaceMetallicColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\n#ifdef AOSTOREINMETALMAPRED\nvec3 aoStoreInMetalMap=vec3(surfaceMetallicColorMap.r,surfaceMetallicColorMap.r,surfaceMetallicColorMap.r);\nambientOcclusionColor=mix(ambientOcclusionColor,aoStoreInMetalMap,vReflectivityInfos.z);\n#endif\n#ifdef METALLNESSSTOREINMETALMAPBLUE\nmetallicRoughness.r*=surfaceMetallicColorMap.b;\n#else\nmetallicRoughness.r*=surfaceMetallicColorMap.r;\n#endif\n#ifdef ROUGHNESSSTOREINMETALMAPALPHA\nmetallicRoughness.g*=surfaceMetallicColorMap.a;\n#else\n#ifdef ROUGHNESSSTOREINMETALMAPGREEN\nmetallicRoughness.g*=surfaceMetallicColorMap.g;\n#endif\n#endif\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmetallicRoughness.g*=microSurfaceTexel.r;\n#endif\n\nmicroSurface=1.0-metallicRoughness.g;\n\nvec3 baseColor=surfaceAlbedo;\n\n\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\n\nsurfaceAlbedo=mix(baseColor.rgb*(1.0-DefaultSpecularReflectanceDielectric.r),vec3(0.,0.,0.),metallicRoughness.r);\n\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallicRoughness.r);\n#else\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\nsurfaceReflectivityColor*=toLinearSpace(surfaceReflectivityColorMap.rgb);\nsurfaceReflectivityColor*=vReflectivityInfos.y;\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface*=surfaceReflectivityColorMap.a;\nmicroSurface*=vReflectivityInfos.z;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmicroSurface*=microSurfaceTexel.r;\n#endif\n#endif\n#endif\n#endif\n\nmicroSurface=clamp(microSurface,0.,1.);\n\nfloat roughness=1.-microSurface;\n\n#ifdef ALPHAFRESNEL\n#if defined(ALPHATEST) || defined(ALPHABLEND)\n\n\n\nfloat opacityPerceptual=alpha;\n#ifdef LINEARALPHAFRESNEL\nfloat opacity0=opacityPerceptual;\n#else\nfloat opacity0=opacityPerceptual*opacityPerceptual;\n#endif\nfloat opacity90=fresnelGrazingReflectance(opacity0);\nvec3 normalForward=faceforward(normalW,-viewDirectionW,normalW);\n\nalpha=fresnelSchlickEnvironmentGGX(clamp(dot(viewDirectionW,normalForward),0.0,1.0),vec3(opacity0),vec3(opacity90),sqrt(microSurface)).x;\n#ifdef ALPHATEST\nif (alpha<=ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#endif\n\n\nfloat NdotVUnclamped=dot(normalW,viewDirectionW);\nfloat NdotV=clamp(NdotVUnclamped,0.,1.)+0.00001;\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n\n#ifdef REFRACTION\nvec3 environmentRefraction=vec3(0.,0.,0.);\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef REFRACTIONMAP_OPPOSITEZ\nrefractionVector.z*=-1.0;\n#endif\n\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nvec3 refractionCoords=refractionVector;\nrefractionCoords=vec3(refractionMatrix*vec4(refractionCoords,0));\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\n#endif\n#ifdef LODINREFRACTIONALPHA\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,1.0);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nrefractionLOD=refractionLOD*vRefractionMicrosurfaceInfos.y+vRefractionMicrosurfaceInfos.z;\n#ifdef LODINREFRACTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticRefractionLOD=UNPACK_LOD(sampleRefraction(refractionSampler,refractionCoords).a);\nfloat requestedRefractionLOD=max(automaticRefractionLOD,refractionLOD);\n#else\nfloat requestedRefractionLOD=refractionLOD;\n#endif\nenvironmentRefraction=sampleRefractionLod(refractionSampler,refractionCoords,requestedRefractionLOD).rgb;\n#else\nfloat lodRefractionNormalized=clamp(refractionLOD/log2(vRefractionMicrosurfaceInfos.x),0.,1.);\nfloat lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;\nvec3 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords).rgb;\nif(lodRefractionNormalizedDoubled<1.0){\nenvironmentRefraction=mix(\nsampleRefraction(refractionSamplerHigh,refractionCoords).rgb,\nenvironmentRefractionMid,\nlodRefractionNormalizedDoubled\n);\n}else{\nenvironmentRefraction=mix(\nenvironmentRefractionMid,\nsampleRefraction(refractionSamplerLow,refractionCoords).rgb,\nlodRefractionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFRACTION\nenvironmentRefraction=toLinearSpace(environmentRefraction.rgb);\n#endif\n\nenvironmentRefraction*=vRefractionInfos.x;\n#endif\n\n#ifdef REFLECTION\nvec3 environmentRadiance=vec3(0.,0.,0.);\nvec3 environmentIrradiance=vec3(0.,0.,0.);\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,1.);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nreflectionLOD=reflectionLOD*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\n#ifdef LODINREFLECTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticReflectionLOD=UNPACK_LOD(sampleReflection(reflectionSampler,reflectionCoords).a);\nfloat requestedReflectionLOD=max(automaticReflectionLOD,reflectionLOD);\n#else\nfloat requestedReflectionLOD=reflectionLOD;\n#endif\nenvironmentRadiance=sampleReflectionLod(reflectionSampler,reflectionCoords,requestedReflectionLOD).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x),0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 environmentSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nenvironmentRadiance=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nenvironmentSpecularMid,\nlodReflectionNormalizedDoubled\n);\n}else{\nenvironmentRadiance=mix(\nenvironmentSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\n#endif\n\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if defined(NORMAL) && defined(USESPHERICALINVERTEX)\nenvironmentIrradiance=vEnvironmentIrradiance;\n#else\nvec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nirradianceVector.z*=-1.0;\n#endif\nenvironmentIrradiance=environmentIrradianceJones(irradianceVector);\n#endif\n#endif\n\nenvironmentRadiance*=vReflectionInfos.x;\nenvironmentRadiance*=vReflectionColor.rgb;\nenvironmentIrradiance*=vReflectionColor.rgb;\n#endif\n\n\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\nfloat reflectance90=fresnelGrazingReflectance(reflectance);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n\nvec3 diffuseBase=vec3(0.,0.,0.);\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=toLinearSpace(texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb)*vLightmapInfos.y;\n#endif\nlightingInfo info;\nfloat shadow=1.; \nfloat NdotL=-1.;\n#include<lightFragment>[0..maxSimultaneousLights]\n\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\n\nvec2 brdfSamplerUV=vec2(NdotV,roughness);\n\nvec4 environmentBrdf=texture2D(environmentBrdfSampler,brdfSamplerUV);\nvec3 specularEnvironmentReflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y;\n#ifdef RADIANCEOCCLUSION\n#ifdef AMBIENTINGRAYSCALE\nfloat ambientMonochrome=ambientOcclusionColor.r;\n#else\nfloat ambientMonochrome=getLuminance(ambientOcclusionColor);\n#endif\nfloat seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped);\nspecularEnvironmentReflectance*=seo;\n#endif\n#ifdef HORIZONOCCLUSION\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nfloat eho=environmentHorizonOcclusion(reflectionCoords,normalW);\nspecularEnvironmentReflectance*=eho;\n#endif\n#endif\n#endif\n#else\n\nvec3 specularEnvironmentReflectance=fresnelSchlickEnvironmentGGX(NdotV,specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n#endif\n\n#ifdef REFRACTION\nvec3 refractance=vec3(0.0,0.0,0.0);\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedo;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedo*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nenvironmentRefraction*=tint;\n\nalpha=1.0;\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\n\ntransmission*=1.0-specularEnvironmentReflectance;\n\nrefractance=transmission;\n#endif\n\n\n\n\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\n\nvec3 finalDiffuse=diffuseBase;\nfinalDiffuse.rgb+=vAmbientColor;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\n\n#ifdef REFLECTION\nvec3 finalIrradiance=environmentIrradiance;\nfinalIrradiance*=surfaceAlbedo.rgb;\n#endif\n\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase;\nfinalSpecular=max(finalSpecular,0.0);\n\nvec3 finalSpecularScaled=finalSpecular*vLightingIntensity.x*vLightingIntensity.w;\n#endif\n\n#ifdef REFLECTION\nvec3 finalRadiance=environmentRadiance;\nfinalRadiance*=specularEnvironmentReflectance;\n\nvec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z;\n#endif\n\n#ifdef REFRACTION\nvec3 finalRefraction=environmentRefraction;\nfinalRefraction*=refractance;\n#endif\n\nvec3 finalEmissive=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\nfinalEmissive*=toLinearSpace(emissiveColorTex.rgb);\nfinalEmissive*=vEmissiveInfos.y;\n#endif\n\n#ifdef ALPHABLEND\nfloat luminanceOverAlpha=0.0;\n#if defined(REFLECTION) && defined(RADIANCEOVERALPHA)\nluminanceOverAlpha+=getLuminance(finalRadianceScaled);\n#endif\n#if defined(SPECULARTERM) && defined(SPECULAROVERALPHA)\nluminanceOverAlpha+=getLuminance(finalSpecularScaled);\n#endif\n#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA)\nalpha=clamp(alpha+luminanceOverAlpha*luminanceOverAlpha,0.,1.);\n#endif\n#endif\n\n\n\nvec4 finalColor=vec4(finalDiffuse*ambientOcclusionColor*vLightingIntensity.x +\n#ifdef REFLECTION\nfinalIrradiance*ambientOcclusionColor*vLightingIntensity.z +\n#endif\n#ifdef SPECULARTERM\n\n\nfinalSpecularScaled +\n#endif\n#ifdef REFLECTION\n\n\nfinalRadianceScaled +\n#endif\n#ifdef REFRACTION\nfinalRefraction*vLightingIntensity.z +\n#endif\nfinalEmissive*vLightingIntensity.y,\nalpha);\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n\nfinalColor=max(finalColor,0.0);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\nfinalColor.rgb=clamp(finalColor.rgb,0.,30.0);\n#else\n\nfinalColor=applyImageProcessing(finalColor);\n#endif\n#ifdef PREMULTIPLYALPHA\n\nfinalColor.rgb*=finalColor.a;\n#endif\ngl_FragColor=finalColor;\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n}","spritesVertexShader":"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nvFogDistance=viewPos;\n#endif\n}","spritesPixelShader":"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n}","particlesVertexShader":"\nattribute vec3 position;\nattribute vec4 color;\nattribute vec4 options;\nattribute float cellIndex;\n\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec3 particlesInfos; \n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\nvoid main(void) { \nvec3 viewPos=(view*vec4(position,1.0)).xyz; \nvec3 cornerPos;\nfloat size=options.y;\nfloat angle=options.x;\nvec2 offset=options.zw;\ncornerPos=vec3(offset.x-0.5,offset.y-0.5,0.)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \nvColor=color;\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/particlesInfos.z);\nfloat columnOffset=cellIndex-rowOffset*particlesInfos.z;\nvec2 uvScale=particlesInfos.xy;\nvec2 uvOffset=vec2(offset.x ,1.0-offset.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else\nvUV=offset;\n#endif\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*vec4(viewPos,1.0);\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n}","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\nvoid main(void) {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif\nvec4 baseColor=texture2D(diffuseSampler,vUV);\ngl_FragColor=(baseColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n}","gpuRenderParticlesVertexShader":"#version 300 es\nuniform vec4 colorDead;\nuniform mat4 view;\nuniform mat4 projection;\n\nin vec3 position;\nin float age;\nin float life;\nin float size;\nin vec4 color;\nin vec2 offset;\nin vec2 uv;\nout vec2 vUV;\nout vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nout float fClipDistance;\n#endif\nvoid main() {\nvUV=uv;\nfloat ratio=age/life;\nvColor=color*vec4(1.0-ratio)+colorDead*vec4(ratio);\n\nvec4 viewPosition=view*vec4(position,1.0);\ngl_Position=projection*(viewPosition+vec4(offset*size,0,1.0));\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*viewPosition;\nfClipDistance=dot(worldPos,vClipPlane);\n#endif \n}","gpuRenderParticlesPixelShader":"#version 300 es\nuniform sampler2D textureSampler;\nin vec2 vUV;\nin vec4 vColor;\nout vec4 outFragColor;\n#ifdef CLIPPLANE\nin float fClipDistance;\n#endif\nvoid main() {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif \noutFragColor=texture(textureSampler,vUV)*vColor;\n}\n","gpuUpdateParticlesVertexShader":"#version 300 es\n#define PI 3.14159\nuniform float currentCount;\nuniform float timeDelta;\nuniform vec3 generalRandoms;\nuniform mat4 emitterWM;\nuniform vec2 lifeTime;\nuniform vec2 emitPower;\nuniform vec2 sizeRange;\nuniform vec4 color1;\nuniform vec4 color2;\nuniform vec3 gravity;\nuniform sampler2D randomSampler;\n#ifdef BOXEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\nuniform vec3 minEmitBox;\nuniform vec3 maxEmitBox;\n#endif\n#ifdef SPHEREEMITTER\nuniform float radius;\n#ifdef DIRECTEDSPHEREEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#else\nuniform float directionRandomizer;\n#endif\n#endif\n#ifdef CONEEMITTER\nuniform float radius;\nuniform float angle;\nuniform float height;\nuniform float directionRandomizer;\n#endif\n\nin vec3 position;\nin float age;\nin float life;\nin float seed;\nin float size;\nin vec4 color;\nin vec3 direction;\n\nout vec3 outPosition;\nout float outAge;\nout float outLife;\nout float outSeed;\nout float outSize;\nout vec4 outColor;\nout vec3 outDirection;\nvec3 getRandomVec3(float offset) {\nreturn texture(randomSampler,vec2(float(gl_VertexID)*offset/currentCount,0)).rgb;\n}\nvec4 getRandomVec4(float offset) {\nreturn texture(randomSampler,vec2(float(gl_VertexID)*offset/currentCount,0));\n}\nvoid main() {\nif (age>=life) {\nvec3 position;\nvec3 direction;\n\nvec4 randoms=getRandomVec4(generalRandoms.x);\n\noutAge=0.0;\noutLife=lifeTime.x+(lifeTime.y-lifeTime.x)*randoms.r;\n\noutSeed=seed;\n\noutSize=sizeRange.x+(sizeRange.y-sizeRange.x)*randoms.g;\n\noutColor=color1+(color2-color1)*randoms.b;\n\n#ifdef BOXEMITTER\nvec3 randoms2=getRandomVec3(generalRandoms.y);\nvec3 randoms3=getRandomVec3(generalRandoms.z);\nposition=minEmitBox+(maxEmitBox-minEmitBox)*randoms2;\ndirection=direction1+(direction2-direction1)*randoms3;\n#elif defined(SPHEREEMITTER)\nvec3 randoms2=getRandomVec3(generalRandoms.y);\nvec3 randoms3=getRandomVec3(generalRandoms.z);\n\nfloat phi=2.0*PI*randoms2.x;\nfloat theta=PI*randoms2.y;\nfloat randX=cos(phi)*sin(theta);\nfloat randY=cos(theta);\nfloat randZ=sin(phi)*sin(theta);\nposition=(radius*randoms2.z)*vec3(randX,randY,randZ);\n#ifdef DIRECTEDSPHEREEMITTER\ndirection=direction1+(direction2-direction1)*randoms3;\n#else\n\ndirection=position+directionRandomizer*randoms3;\n#endif\n#elif defined(CONEEMITTER)\nvec3 randoms2=getRandomVec3(generalRandoms.y);\nfloat s=2.0*PI*randoms2.x;\nfloat h=randoms2.y;\n\nh=1.-h*h;\nfloat lRadius=radius*randoms2.z;\nlRadius=lRadius*h/height;\nfloat randX=lRadius*sin(s);\nfloat randZ=lRadius*cos(s);\nfloat randY=h*height;\nposition=vec3(randX,randY,randZ); \n\nif (angle == 0.) {\ndirection=vec3(0.,1.0,0.);\n} else {\nvec3 randoms3=getRandomVec3(generalRandoms.z);\ndirection=position+directionRandomizer*randoms3;\n}\n#else \n\nposition=vec3(0.,0.,0.);\n\ndirection=2.0*(getRandomVec3(seed)-vec3(0.5,0.5,0.5));\n#endif\nfloat power=emitPower.x+(emitPower.y-emitPower.x)*randoms.a;\noutPosition=(emitterWM*vec4(position,1.)).xyz;\noutDirection=(emitterWM*vec4(direction*power,0.)).xyz;\n} else { \noutPosition=position+(direction+gravity)*timeDelta;\noutAge=age+timeDelta;\noutLife=life;\noutSeed=seed;\noutColor=color;\noutSize=size;\noutDirection=direction;\n}\n}","gpuUpdateParticlesPixelShader":"#version 300 es\nvoid main() {\ndiscard;\n}\n","colorVertexShader":"\nattribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform mat4 viewProjection;\nuniform mat4 world;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n}","colorPixelShader":"#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#else\nuniform vec4 color;\n#endif\nvoid main(void) {\n#ifdef VERTEXCOLOR\ngl_FragColor=vColor;\n#else\ngl_FragColor=color;\n#endif\n}","postprocessVertexShader":"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 biasAndScale;\nuniform vec2 depthValues;\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 worldPos=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*worldPos;\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y))+biasAndScale.x;\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","shadowMapPixelShader":"#ifndef FLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform vec2 biasAndScale;\nuniform vec2 depthValues;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=vDepthMetric;\n#ifdef ESM\ndepth=clamp(exp(-min(87.,biasAndScale.y*depth)),0.,1.);\n#endif\n#ifdef FLOAT\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#else\ngl_FragColor=pack(depth);\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 depthValues;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(vDepthMetric,vDepthMetric*vDepthMetric,0.0,1.0);\n}","ssaoPixelShader":"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n#endif\n","ssao2PixelShader":"\nprecision highp float;\nuniform sampler2D textureSampler;\nuniform float near;\nuniform float far;\nuniform float radius;\nvarying vec2 vUV;\nfloat perspectiveDepthToViewZ( const in float invClipZ,const in float near,const in float far ) {\nreturn ( near*far )/( ( far-near )*invClipZ-far );\n}\nfloat viewZToPerspectiveDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( near*far/viewZ+far)/( far-near );\n}\nfloat viewZToOrthographicDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( viewZ+near )/( near-far );\n}\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform sampler2D normalSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float base;\nuniform float xViewport;\nuniform float yViewport;\nuniform float maxZ;\nuniform float minZAspect;\nuniform vec2 texelSize;\nuniform mat4 projection;\nvoid main()\n{\nvec3 random=texture2D(randomSampler,vUV*randTextureTiles).rgb;\nfloat depth=texture2D(textureSampler,vUV).r;\nfloat depthSign=depth/abs(depth);\ndepth=depth*depthSign;\nvec3 normal=texture2D(normalSampler,vUV).rgb; \nfloat occlusion=0.0;\nfloat correctedRadius=min(radius,minZAspect*depth/near);\nvec3 vViewRay=vec3((vUV.x*2.0-1.0)*xViewport,(vUV.y*2.0-1.0)*yViewport,depthSign);\nvec3 origin=vViewRay*depth;\nvec3 rvec=random*2.0-1.0;\nrvec.z=0.0;\nvec3 tangent=normalize(rvec-normal*dot(rvec,normal));\nvec3 bitangent=cross(normal,tangent);\nmat3 tbn=mat3(tangent,bitangent,normal);\nfloat difference;\nif (depth>maxZ) {\ngl_FragColor=vec4(1.0,1.0,1.0,1.0);\nreturn;\n}\nfor (int i=0; i<SAMPLES; ++i) {\n\nvec3 samplePosition=tbn*sampleSphere[i];\nsamplePosition=samplePosition*correctedRadius+origin;\n\nvec4 offset=vec4(samplePosition,1.0);\noffset=projection*offset;\noffset.xyz/=offset.w;\noffset.xy=offset.xy*0.5+0.5;\nif (offset.x<0.0 || offset.y<0.0 || offset.x>1.0 || offset.y>1.0) {\ncontinue;\n}\n\nfloat sampleDepth=abs(texture2D(textureSampler,offset.xy).r);\n\nfloat rangeCheck=abs(depth-sampleDepth)<correctedRadius ? 1.0 : 0.0;\ndifference=depthSign*samplePosition.z-sampleDepth;\n\nocclusion+=(difference>=1e-5 ? 1.0 : 0.0)*rangeCheck;\n}\n\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor=vec4(vec3(result),1.0);\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvec4 blur9(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.3846153846)*direction;\nvec2 off2=vec2(3.2307692308)*direction;\ncolor+=texture2D(image,uv)*0.2270270270;\ncolor+=texture2D(image,uv+(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv-(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv+(off2/resolution))*0.0702702703;\ncolor+=texture2D(image,uv-(off2/resolution))*0.0702702703;\nreturn color;\n}\nvec4 blur13(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\ncolor+=texture2D(image,uv)*0.1964825501511404;\ncolor+=texture2D(image,uv+(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv-(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv+(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv-(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv+(off3/resolution))*0.010381362401148057;\ncolor+=texture2D(image,uv-(off3/resolution))*0.010381362401148057;\nreturn color;\n}\nvec4 blur13Bilateral(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\nfloat compareDepth=abs(texture2D(depthSampler,uv).r);\nfloat sampleDepth;\nfloat weight;\nfloat weightSum=30.0;\ncolor+=texture2D(image,uv)*30.0;\nsampleDepth=abs(texture2D(depthSampler,uv+(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off3/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off3/resolution))*weight;\nreturn color/weightSum;\n}\nvoid main()\n{\n#if EXPENSIVE\nfloat compareDepth=abs(texture2D(depthSampler,vUV).r);\nfloat texelsize=1.0/outSize;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 direction=vec2(0.0,1.0);\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=abs(texture2D(depthSampler,samplePos).r);\nfloat weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30000.0);\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n#else\nvec4 color;\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#else\nvec2 direction=vec2(0.0,1.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#endif\ngl_FragColor.rgb=vec3(color.r);\ngl_FragColor.a=1.0;\n#endif\n}\n#endif\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,vUV);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\nif (chromatic_aberration>0.0) {\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*radius*17.0/screen_width;\nfloat ref_shiftY=chromatic_aberration*radius*17.0/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\n}\ngl_FragColor=original;\n}","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","standardPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\nvec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\ngl_FragColor=finalColor;\n}\n#endif\n#if defined(VLS)\n#define PI 3.1415926535897932384626433832795\nuniform mat4 shadowViewProjection;\nuniform mat4 lightWorld;\nuniform vec3 cameraPosition;\nuniform vec3 sunDirection;\nuniform vec3 sunColor;\nuniform vec2 depthValues;\nuniform float scatteringCoefficient;\nuniform float scatteringPower;\nuniform sampler2D shadowMapSampler;\nuniform sampler2D positionSampler;\nfloat computeScattering(float lightDotView)\n{\nfloat result=1.0-scatteringCoefficient*scatteringCoefficient;\nresult/=(4.0*PI*pow(1.0+scatteringCoefficient*scatteringCoefficient-(2.0*scatteringCoefficient)*lightDotView,1.5));\nreturn result;\n}\nvoid main(void)\n{\n\nvec3 worldPos=texture2D(positionSampler,vUV).rgb;\nvec3 startPosition=cameraPosition;\nvec3 rayVector=worldPos-startPosition;\nfloat rayLength=length(rayVector);\nvec3 rayDirection=rayVector/rayLength;\nfloat stepLength=rayLength/NB_STEPS;\nvec3 stepL=rayDirection*stepLength;\nvec3 currentPosition=startPosition;\nvec3 accumFog=vec3(0.0);\nfor (int i=0; i<int(NB_STEPS); i++)\n{\nvec4 worldInShadowCameraSpace=shadowViewProjection*vec4(currentPosition,1.0);\nfloat depthMetric=(worldInShadowCameraSpace.z+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depthMetric,0.0,1.0);\nworldInShadowCameraSpace.xyz/=worldInShadowCameraSpace.w;\nworldInShadowCameraSpace.xyz=0.5*worldInShadowCameraSpace.xyz+vec3(0.5);\nfloat shadowMapValue=texture2D(shadowMapSampler,worldInShadowCameraSpace.xy).r;\nif (shadowMapValue>shadowPixelDepth)\naccumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));\ncurrentPosition+=stepL;\n}\naccumFog/=NB_STEPS;\nvec3 color=accumFog*scatteringPower;\ngl_FragColor=vec4(color*exp(color) ,1.0);\n}\n#endif\n#if defined(VLSMERGE)\nuniform sampler2D originalSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);\n}\n#endif\n#if defined(LUMINANCE)\nuniform vec2 lumOffsets[4];\nvoid main()\n{\nfloat average=0.0;\nvec4 color=vec4(0.0);\nfloat maximum=-1e20;\nvec3 weight=vec3(0.299,0.587,0.114);\nfor (int i=0; i<4; i++)\n{\ncolor=texture2D(textureSampler,vUV+ lumOffsets[i]);\n\nfloat GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\n\n#ifdef WEIGHTED_AVERAGE\nfloat GreyValue=dot(color.rgb,weight);\n#endif\n#ifdef BRIGHTNESS\nfloat GreyValue=max(color.r,max(color.g,color.b));\n#endif\n#ifdef HSL_COMPONENT\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\n#endif\n#ifdef MAGNITUDE\nfloat GreyValue=length(color.rgb);\n#endif\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(LUMINANCE_DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLER\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main()\n{\nvec4 color=vec4(0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++)\n{\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifdef FINAL_DOWN_SAMPLER\ngl_FragColor=pack(average);\n#else\ngl_FragColor=vec4(average,average,0.0,1.0);\n#endif\n}\n#endif\n#if defined(HDR)\nuniform sampler2D textureAdderSampler;\nuniform float averageLuminance;\nvoid main()\n{\nvec4 color=texture2D(textureAdderSampler,vUV);\nvec4 adjustedColor=color/averageLuminance;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i<GHOSTS; ++i)\n{\nvec2 offset=fract(uv+ghostDir*ghostIndice);\nfloat weight=length(vec2(0.5)-offset)/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;\nghostIndice+=1.0;\n}\nvec2 haloVec=normalize(ghostDir)*haloWidth;\nfloat weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;\nresult*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));\ngl_FragColor=result;\n}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;\nuniform sampler2D lensDirtSampler;\nuniform sampler2D lensStarSampler;\nuniform mat4 lensStarMatrix;\nvoid main(void)\n{\nvec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;\nvec4 lensMod=texture2D(lensDirtSampler,vUV);\nlensMod+=texture2D(lensStarSampler,vUV);\nvec4 result=texture2D(textureSampler,vUV)*lensMod;\ngl_FragColor=texture2D(otherSampler,vUV)+result;\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\n#if defined(MOTION_BLUR)\nuniform mat4 inverseViewProjection;\nuniform mat4 prevViewProjection;\nuniform vec2 screenSize;\nuniform float motionScale;\nuniform float motionStrength;\nuniform sampler2D depthSampler;\nvoid main(void)\n{\nvec2 texelSize=1.0/screenSize;\nfloat depth=texture2D(depthSampler,vUV).r;\nvec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);\ncpos=cpos*inverseViewProjection;\nvec4 ppos=cpos*prevViewProjection;\nppos.xyz/=ppos.w;\nppos.xy=ppos.xy*0.5+0.5;\nvec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;\nfloat speed=length(velocity/texelSize);\nint nSamples=int(clamp(speed,1.0,MAX_MOTION_SAMPLES));\nvec4 result=texture2D(textureSampler,vUV);\nfor (int i=1; i<int(MAX_MOTION_SAMPLES); ++i) {\nif (i>=nSamples)\nbreak;\nvec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\nresult+=texture2D(textureSampler,offset1);\n}\ngl_FragColor=result/float(nSamples);\n}\n#endif\n","fxaaVertexShader":"\nattribute vec2 position;\nuniform vec2 texelSize;\n\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd);\nsampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;\nsampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;\nsampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;\nsampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;\nsampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;\nsampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;\nsampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;\nsampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;\ngl_Position=vec4(position,0.0,1.0);\n}","fxaaPixelShader":"uniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst float fxaaQualitySubpix=1.0;\nconst float fxaaQualityEdgeThreshold=0.166;\nconst float fxaaQualityEdgeThresholdMin=0.0833;\nconst vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){\nvec2 posM;\nposM.x=vUV.x;\nposM.y=vUV.y;\nvec4 rgbyM=texture2D(textureSampler,vUV,0.0);\nfloat lumaM=FxaaLuma(rgbyM);\nfloat lumaS=FxaaLuma(texture2D(textureSampler,sampleCoordS,0.0));\nfloat lumaE=FxaaLuma(texture2D(textureSampler,sampleCoordE,0.0));\nfloat lumaN=FxaaLuma(texture2D(textureSampler,sampleCoordN,0.0));\nfloat lumaW=FxaaLuma(texture2D(textureSampler,sampleCoordW,0.0));\nfloat maxSM=max(lumaS,lumaM);\nfloat minSM=min(lumaS,lumaM);\nfloat maxESM=max(lumaE,maxSM);\nfloat minESM=min(lumaE,minSM);\nfloat maxWN=max(lumaN,lumaW);\nfloat minWN=min(lumaN,lumaW);\nfloat rangeMax=max(maxWN,maxESM);\nfloat rangeMin=min(minWN,minESM);\nfloat rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;\nfloat range=rangeMax-rangeMin;\nfloat rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\nreturn;\n}\nfloat lumaNW=FxaaLuma(texture2D(textureSampler,sampleCoordNW,0.0));\nfloat lumaSE=FxaaLuma(texture2D(textureSampler,sampleCoordSE,0.0));\nfloat lumaNE=FxaaLuma(texture2D(textureSampler,sampleCoordNE,0.0));\nfloat lumaSW=FxaaLuma(texture2D(textureSampler,sampleCoordSW,0.0));\nfloat lumaNS=lumaN+lumaS;\nfloat lumaWE=lumaW+lumaE;\nfloat subpixRcpRange=1.0/range;\nfloat subpixNSWE=lumaNS+lumaWE;\nfloat edgeHorz1=(-2.0*lumaM)+lumaNS;\nfloat edgeVert1=(-2.0*lumaM)+lumaWE;\nfloat lumaNESE=lumaNE+lumaSE;\nfloat lumaNWNE=lumaNW+lumaNE;\nfloat edgeHorz2=(-2.0*lumaE)+lumaNESE;\nfloat edgeVert2=(-2.0*lumaN)+lumaNWNE;\nfloat lumaNWSW=lumaNW+lumaSW;\nfloat lumaSWSE=lumaSW+lumaSE;\nfloat edgeHorz4=(abs(edgeHorz1)*2.0)+abs(edgeHorz2);\nfloat edgeVert4=(abs(edgeVert1)*2.0)+abs(edgeVert2);\nfloat edgeHorz3=(-2.0*lumaW)+lumaNWSW;\nfloat edgeVert3=(-2.0*lumaS)+lumaSWSE;\nfloat edgeHorz=abs(edgeHorz3)+edgeHorz4;\nfloat edgeVert=abs(edgeVert3)+edgeVert4;\nfloat subpixNWSWNESE=lumaNWSW+lumaNESE;\nfloat lengthSign=texelSize.x;\nbool horzSpan=edgeHorz>=edgeVert;\nfloat subpixA=subpixNSWE*2.0+subpixNWSWNESE;\nif (!horzSpan)\n{\nlumaN=lumaW;\n}\nif (!horzSpan) \n{\nlumaS=lumaE;\n}\nif (horzSpan) \n{\nlengthSign=texelSize.y;\n}\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;\nfloat gradientN=lumaN-lumaM;\nfloat gradientS=lumaS-lumaM;\nfloat lumaNN=lumaN+lumaM;\nfloat lumaSS=lumaS+lumaM;\nbool pairN=abs(gradientN)>=abs(gradientS);\nfloat gradient=max(abs(gradientN),abs(gradientS));\nif (pairN)\n{\nlengthSign=-lengthSign;\n}\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);\nvec2 posB;\nposB.x=posM.x;\nposB.y=posM.y;\nvec2 offNP;\noffNP.x=(!horzSpan) ? 0.0 : texelSize.x;\noffNP.y=(horzSpan) ? 0.0 : texelSize.y;\nif (!horzSpan) \n{\nposB.x+=lengthSign*0.5;\n}\nif (horzSpan)\n{\nposB.y+=lengthSign*0.5;\n}\nvec2 posN;\nposN.x=posB.x-offNP.x*1.5;\nposN.y=posB.y-offNP.y*1.5;\nvec2 posP;\nposP.x=posB.x+offNP.x*1.5;\nposP.y=posB.y+offNP.y*1.5;\nfloat subpixD=((-2.0)*subpixC)+3.0;\nfloat lumaEndN=FxaaLuma(texture2D(textureSampler,posN,0.0));\nfloat subpixE=subpixC*subpixC;\nfloat lumaEndP=FxaaLuma(texture2D(textureSampler,posP,0.0));\nif (!pairN) \n{\nlumaNN=lumaSS;\n}\nfloat gradientScaled=gradient*1.0/4.0;\nfloat lumaMM=lumaM-lumaNN*0.5;\nfloat subpixF=subpixD*subpixE;\nbool lumaMLTZero=lumaMM<0.0;\nlumaEndN-=lumaNN*0.5;\nlumaEndP-=lumaNN*0.5;\nbool doneN=abs(lumaEndN)>=gradientScaled;\nbool doneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) \n{\nposN.x-=offNP.x*3.0;\n}\nif (!doneN) \n{\nposN.y-=offNP.y*3.0;\n}\nbool doneNP=(!doneN) || (!doneP);\nif (!doneP) \n{\nposP.x+=offNP.x*3.0;\n}\nif (!doneP)\n{\nposP.y+=offNP.y*3.0;\n}\nif (doneNP)\n{\nif (!doneN) lumaEndN=FxaaLuma(texture2D(textureSampler,posN.xy,0.0));\nif (!doneP) lumaEndP=FxaaLuma(texture2D(textureSampler,posP.xy,0.0));\nif (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;\nif (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;\ndoneN=abs(lumaEndN)>=gradientScaled;\ndoneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) posN.x-=offNP.x*12.0;\nif (!doneN) posN.y-=offNP.y*12.0;\ndoneNP=(!doneN) || (!doneP);\nif (!doneP) posP.x+=offNP.x*12.0;\nif (!doneP) posP.y+=offNP.y*12.0;\n}\nfloat dstN=posM.x-posN.x;\nfloat dstP=posP.x-posM.x;\nif (!horzSpan)\n{\ndstN=posM.y-posN.y;\n}\nif (!horzSpan) \n{\ndstP=posP.y-posM.y;\n}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;\nfloat spanLength=(dstP+dstN);\nbool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;\nfloat spanLengthRcp=1.0/spanLength;\nbool directionN=dstN<dstP;\nfloat dst=min(dstN,dstP);\nbool goodSpan=directionN ? goodSpanN : goodSpanP;\nfloat subpixG=subpixF*subpixF;\nfloat pixelOffset=(dst*(-spanLengthRcp))+0.5;\nfloat subpixH=subpixG*fxaaQualitySubpix;\nfloat pixelOffsetGood=goodSpan ? pixelOffset : 0.0;\nfloat pixelOffsetSubpix=max(pixelOffsetGood,subpixH);\nif (!horzSpan)\n{\nposM.x+=pixelOffsetSubpix*lengthSign;\n}\nif (horzSpan)\n{\nposM.y+=pixelOffsetSubpix*lengthSign;\n}\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n}","circleOfConfusionPixelShader":"\nuniform sampler2D depthSampler;\n\nvarying vec2 vUV;\n\nuniform vec2 cameraMinMaxZ;\n\nuniform float focusDistance;\nuniform float cocPrecalculation;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(depthSampler,offset).r; \nreturn (cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth)*1000.0; \n}\nvoid main(void)\n{\nfloat pixelDistance=sampleDistance(vUV);\nfloat coc=abs(cocPrecalculation* ((focusDistance-pixelDistance)/pixelDistance));\ncoc=clamp(coc,0.0,1.0);\ngl_FragColor=vec4(coc,texture2D(depthSampler,vUV).r,coc,1.0);\n}\n","depthOfFieldMergePixelShader":"\nuniform sampler2D textureSampler;\nuniform sampler2D originalSampler;\nuniform sampler2D circleOfConfusionSampler;\n#if BLUR_LEVEL>0\nuniform sampler2D blurStep1;\n#endif\n#if BLUR_LEVEL>1\nuniform sampler2D blurStep2;\n#endif\n\nvarying vec2 vUV;\nvoid main(void)\n{\nfloat coc=texture2D(circleOfConfusionSampler,vUV).r;\nvec4 original=texture2D(originalSampler,vUV);\n#if BLUR_LEVEL == 0\nvec4 blurred1=texture2D(textureSampler,vUV);\ngl_FragColor=mix(original,blurred1,coc);\n#endif\n#if BLUR_LEVEL == 1\nvec4 blurred1=texture2D(blurStep1,vUV);\nvec4 blurred2=texture2D(textureSampler,vUV); \nif(coc<0.5){\ngl_FragColor=mix(original,blurred1,coc/0.5);\n}else{\ngl_FragColor=mix(blurred1,blurred2,(coc-0.5)/0.5);\n}\n#endif\n#if BLUR_LEVEL == 2\nvec4 blurred1=texture2D(blurStep1,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\nvec4 blurred3=texture2D(textureSampler,vUV);\nif(coc<0.33){\ngl_FragColor=mix(original,blurred1,coc/0.33);\n}else if(coc<0.66){\ngl_FragColor=mix(blurred1,blurred2,(coc-0.33)/0.33);\n}else{\ngl_FragColor=mix(blurred2,blurred3,(coc-0.66)/0.34);\n}\n#endif\n}\n","geometryVertexShader":"precision highp float;\nprecision highp int;\n#include<bonesDeclaration>\n#include<instancesDeclaration>\nattribute vec3 position;\nattribute vec3 normal;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nvarying vec2 uv;\n#endif\n#ifdef UV2\nvarying vec2 uv2;\n#endif\n#endif\n\nuniform mat4 viewProjection;\nuniform mat4 view;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 pos=vec4(finalWorld*vec4(position,1.0));\nvNormalV=normalize(vec3((view*finalWorld)*vec4(normal,0.0)));\nvViewPos=view*pos;\n#ifdef POSITION\nvPosition=pos.xyz/pos.w;\n#endif\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","geometryPixelShader":"#extension GL_EXT_draw_buffers : require\nprecision highp float;\nprecision highp int;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef POSITION\n#include<mrtFragmentDeclaration>[3]\n#else\n#include<mrtFragmentDeclaration>[2]\n#endif\nvoid main() {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\n\ngl_FragData[1]=vec4(normalize(vNormalV),1.0);\n\n#ifdef POSITION\ngl_FragData[2]=vec4(vPosition,1.0);\n#endif\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float degree;\nvoid main(void) \n{\nvec3 color=texture2D(textureSampler,vUV).rgb;\nfloat luminance=dot(color,vec3(0.3,0.59,0.11)); \nvec3 blackAndWhite=vec3(luminance,luminance,luminance);\ngl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 dataSample=texture2D(lightScatteringSampler,tc)*0.4;\ndataSample*=illuminationDecay*weight;\ncolor+=dataSample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D textureSampler,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(textureSampler,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(textureSampler,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","highlightsPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nconst vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvoid main(void) \n{\nvec4 tex=texture2D(textureSampler,vUV);\nvec3 c=tex.rgb;\nfloat luma=dot(c.rgb,RGBLuminanceCoefficients);\n\n\ngl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); \n}","imageProcessingPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main(void)\n{\nvec4 result=texture2D(textureSampler,vUV);\n#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\n\nresult.rgb=toLinearSpace(result.rgb);\n#endif\nresult=applyImageProcessing(result);\n#else\n\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;\n}","kernelBlurVertexShader":"\nattribute vec2 position;\n\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nsampleCenter=(position*madd+madd);\n#include<kernelBlurVertex>[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n}","kernelBlurPixelShader":"\nuniform sampler2D textureSampler;\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#ifdef DOF\nuniform sampler2D circleOfConfusionSampler;\nuniform vec2 cameraMinMaxZ;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(circleOfConfusionSampler,offset).g; \nreturn cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth; \n}\n#endif\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\n#ifdef PACKEDFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nvoid main(void)\n{\n#ifdef DOF\nfloat sumOfWeights=0.0; \nfloat sampleDepth=0.0;\nfloat factor=0.0;\nfloat centerSampleDepth=sampleDistance(sampleCenter);\n#endif\nfloat computedWeight=0.0;\n#ifdef PACKEDFLOAT \nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#include<kernelBlurFragment>[0..varyingCount]\n#include<kernelBlurFragment2>[0..depCount]\n#ifdef PACKEDFLOAT\ngl_FragColor=pack(blend);\n#else\ngl_FragColor=blend;\n#endif\n#ifdef DOF\n\nif(sumOfWeights == 0.0){\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor/=sumOfWeights;\n#endif\n}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,0.0);\nelse{\ngl_FragColor=texture2D(textureSampler,tc);\n}\n}","glowBlurPostProcessPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nfloat getLuminance(vec3 color)\n{\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\n}\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\n\nvec4 texel=texture2D(textureSampler,start+texelOffset);\nbaseColor.a+=texel.a*weights[i];\n\nfloat luminance=getLuminance(baseColor.rgb);\nfloat luminanceTexel=getLuminance(texel.rgb);\nfloat choice=step(luminanceTexel,luminance);\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","glowMapGenerationPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\nuniform vec4 color;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUVDiffuse).a<0.4)\ndiscard;\n#endif\n#ifdef EMISSIVE\ngl_FragColor=texture2D(emissiveSampler,vUVEmissive)*color;\n#else\ngl_FragColor=color;\n#endif\n}","glowMapGenerationVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform mat4 emissiveMatrix;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(position,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","glowMapMergePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#ifdef EMISSIVE\nuniform sampler2D textureSampler2;\n#endif\n\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef EMISSIVE\nbaseColor+=texture2D(textureSampler2,vUV);\nbaseColor*=offset;\n#else\nbaseColor.a=abs(offset-baseColor.a);\n#ifdef STROKE\nfloat alpha=smoothstep(.0,.1,baseColor.a);\nbaseColor.a=alpha;\nbaseColor.rgb=baseColor.rgb*alpha;\n#endif\n#endif\ngl_FragColor=baseColor;\n}","glowMapMergeVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include<logDepthDeclaration>\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include<logDepthVertex>\n}\n","outlinePixelShader":"#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#include<logDepthFragment>\ngl_FragColor=color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}","backgroundVertexShader":"precision highp float;\n#include<__decl__backgroundVertex>\n#include<helperFunctions>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normal);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#ifdef EQUIRECTANGULAR_RELFECTION_FOV\nmat3 screenToWorld=inverseMat3(mat3(finalWorld*viewProjection));\nvec3 segment=mix(vDirectionW,screenToWorld*vec3(0.0,0.0,1.0),abs(fFovMultiplier-1.0));\nif (fFovMultiplier<=1.0) {\nvDirectionW=normalize(segment);\n} else {\nvDirectionW=normalize(vDirectionW+(vDirectionW-segment));\n}\n#endif\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0 \nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}\n","backgroundPixelShader":"#ifdef TEXTURELODSUPPORT\n#extension GL_EXT_shader_texture_lod : enable\n#endif\nprecision highp float;\n#include<__decl__backgroundFragment>\n#define RECIPROCAL_PI2 0.15915494\n\nuniform vec3 vEyePosition;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2; \n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n\n#ifndef SHADOWONLY\n#define SHADOWONLY;\n#endif\n#include<imageProcessingDeclaration>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<helperFunctions>\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n#include<imageProcessingFunctions>\n#include<clipPlaneFragmentDeclaration>\n\n#include<fogFragmentDeclaration>\n#ifdef REFLECTIONFRESNEL\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n#endif\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(0.0,1.0,0.0);\n#endif\n\nfloat shadow=1.;\nfloat globalShadow=0.;\nfloat shadowLightCount=0.;\n#include<lightFragment>[0..maxSimultaneousLights]\n#ifdef SHADOWINUSE\nglobalShadow/=shadowLightCount;\n#else\nglobalShadow=1.0;\n#endif\n\nvec3 reflectionColor=vec3(1.,1.,1.);\n#ifdef REFLECTION\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#ifdef REFLECTIONBLUR\nfloat reflectionLOD=vReflectionInfos.y;\n#ifdef TEXTURELODSUPPORT\n\nreflectionLOD=reflectionLOD*log2(vReflectionMicrosurfaceInfos.x)*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\nreflectionColor=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD,0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nreflectionColor=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nreflectionSpecularMid,\nlodReflectionNormalizedDoubled\n);\n} else {\nreflectionColor=mix(\nreflectionSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#else\nvec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);\nreflectionColor=reflectionSample.rgb;\n#endif\n#ifdef GAMMAREFLECTION\nreflectionColor=toLinearSpace(reflectionColor.rgb);\n#endif\n#ifdef REFLECTIONBGR\nreflectionColor=reflectionColor.bgr;\n#endif\n\nreflectionColor*=vReflectionInfos.x;\n#endif\n\nvec3 diffuseColor=vec3(1.,1.,1.);\nfloat finalAlpha=alpha;\n#ifdef DIFFUSE\nvec4 diffuseMap=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef GAMMADIFFUSE\ndiffuseMap.rgb=toLinearSpace(diffuseMap.rgb);\n#endif\n\ndiffuseMap.rgb*=vDiffuseInfos.y;\n#ifdef DIFFUSEHASALPHA\nfinalAlpha*=diffuseMap.a;\n#endif\ndiffuseColor=diffuseMap.rgb;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 colorBase=diffuseColor;\n#else\nvec3 colorBase=reflectionColor*diffuseColor;\n#endif\ncolorBase=max(colorBase,0.0);\n\n#ifdef USERGBCOLOR\nvec3 finalColor=colorBase;\n#else\nvec3 finalColor=colorBase.r*vPrimaryColor.rgb*vPrimaryColor.a;\nfinalColor+=colorBase.g*vSecondaryColor.rgb*vSecondaryColor.a;\nfinalColor+=colorBase.b*vTertiaryColor.rgb*vTertiaryColor.a;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 reflectionAmount=vReflectionControl.xxx;\nvec3 reflectionReflectance0=vReflectionControl.yyy;\nvec3 reflectionReflectance90=vReflectionControl.zzz;\nfloat VdotN=dot(normalize(vEyePosition),normalW);\nvec3 planarReflectionFresnel=fresnelSchlickEnvironmentGGX(clamp(VdotN,0.0,1.0),reflectionReflectance0,reflectionReflectance90,1.0);\nreflectionAmount*=planarReflectionFresnel;\n#ifdef REFLECTIONFALLOFF\nfloat reflectionDistanceFalloff=1.0-clamp(length(vPositionW.xyz-vBackgroundCenter)*vReflectionControl.w,0.0,1.0);\nreflectionDistanceFalloff*=reflectionDistanceFalloff;\nreflectionAmount*=reflectionDistanceFalloff;\n#endif\nfinalColor=mix(finalColor,reflectionColor,clamp(reflectionAmount,0.,1.));\n#endif\n#ifdef OPACITYFRESNEL\nfloat viewAngleToFloor=dot(normalW,normalize(vEyePosition-vBackgroundCenter));\n\nconst float startAngle=0.1;\nfloat fadeFactor=clamp(viewAngleToFloor/startAngle,0.0,1.0);\nfinalAlpha*=fadeFactor*fadeFactor;\n#endif\n\n#ifdef SHADOWINUSE\nfinalColor=mix(finalColor*shadowLevel,finalColor,globalShadow);\n#endif\n\nvec4 color=vec4(finalColor,finalAlpha);\n#include<fogFragment>\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\ncolor.rgb=clamp(color.rgb,0.,30.0);\n#else\n\ncolor=applyImageProcessing(color);\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#ifdef NOISE\ncolor.rgb=dither(vPositionW.xy,color.rgb);\n#endif\ngl_FragColor=color;\n}\n"};
  90248. BABYLON.Effect.IncludesShadersStore={"depthPrePass":"#ifdef DEPTHPREPASS\ngl_FragColor=vec4(0.,0.,0.,1.0);\nreturn;\n#endif","bonesDeclaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;\nattribute vec4 matricesWeightsExtra;\n#endif\n#endif","instancesDeclaration":"#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif","pointCloudVertexDeclaration":"#ifdef POINTSIZE\nuniform float pointSize;\n#endif","bumpVertexDeclaration":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#endif\n","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying vec3 vFogDistance;\n#endif","morphTargetsVertexGlobalDeclaration":"#ifdef MORPHTARGETS\nuniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS];\n#endif","morphTargetsVertexDeclaration":"#ifdef MORPHTARGETS\nattribute vec3 position{X};\n#ifdef MORPHTARGETS_NORMAL\nattribute vec3 normal{X};\n#endif\n#ifdef MORPHTARGETS_TANGENT\nattribute vec3 tangent{X};\n#endif\n#endif","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif","morphTargetsVertex":"#ifdef MORPHTARGETS\npositionUpdated+=(position{X}-position)*morphTargetInfluences[{X}];\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}];\n#endif\n#endif","instancesVertex":"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif","bonesVertex":"#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif \nfinalWorld=finalWorld*influence;\n#endif","bumpVertex":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL)\nvec3 tbnNormal=normalize(normalUpdated);\nvec3 tbnTangent=normalize(tangentUpdated.xyz);\nvec3 tbnBitangent=cross(tbnNormal,tbnTangent)*tangentUpdated.w;\nvTBN=mat3(finalWorld)*mat3(tbnTangent,tbnBitangent,tbnNormal);\n#endif\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif","fogVertex":"#ifdef FOG\nvFogDistance=(view*worldPos).xyz;\n#endif","shadowsVertex":"#ifdef SHADOWS\n#if defined(SHADOW{X}) && !defined(SHADOWCUBE{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\nvDepthMetric{X}=((vPositionFromLight{X}.z+light{X}.depthValues.x)/(light{X}.depthValues.y));\n#endif\n#endif","pointCloudVertex":"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif","helperFunctions":"const float PI=3.1415926535897932384626433832795;\nconst float LinearEncodePowerApprox=2.2;\nconst float GammaEncodePowerApprox=1.0/LinearEncodePowerApprox;\nconst vec3 LuminanceEncodeApprox=vec3(0.2126,0.7152,0.0722);\nmat3 transposeMat3(mat3 inMatrix) {\nvec3 i0=inMatrix[0];\nvec3 i1=inMatrix[1];\nvec3 i2=inMatrix[2];\nmat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);\nreturn outMatrix;\n}\n\nmat3 inverseMat3(mat3 inMatrix) {\nfloat a00=inMatrix[0][0],a01=inMatrix[0][1],a02=inMatrix[0][2];\nfloat a10=inMatrix[1][0],a11=inMatrix[1][1],a12=inMatrix[1][2];\nfloat a20=inMatrix[2][0],a21=inMatrix[2][1],a22=inMatrix[2][2];\nfloat b01=a22*a11-a12*a21;\nfloat b11=-a22*a10+a12*a20;\nfloat b21=a21*a10-a11*a20;\nfloat det=a00*b01+a01*b11+a02*b21;\nreturn mat3(b01,(-a22*a01+a02*a21),(a12*a01-a02*a11),\nb11,(a22*a00-a02*a20),(-a12*a00+a02*a10),\nb21,(-a21*a00+a01*a20),(a11*a00-a01*a10))/det;\n}\nfloat computeFallOff(float value,vec2 clipSpace,float frustumEdgeFalloff)\n{\nfloat mask=smoothstep(1.0-frustumEdgeFalloff,1.0,clamp(dot(clipSpace,clipSpace),0.,1.));\nreturn mix(value,1.0,mask);\n}\nvec3 applyEaseInOut(vec3 x){\nreturn x*x*(3.0-2.0*x);\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn pow(color,vec3(LinearEncodePowerApprox));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn pow(color,vec3(GammaEncodePowerApprox));\n}\nfloat square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,LuminanceEncodeApprox),0.,1.);\n}\n\nfloat getRand(vec2 seed) {\nreturn fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);\n}\nvec3 dither(vec2 seed,vec3 color) {\nfloat rand=getRand(seed);\ncolor+=mix(-0.5/255.0,0.5/255.0,rand);\ncolor=max(color,0.0);\nreturn color;\n}","lightFragmentDeclaration":"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#else\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\nuniform sampler2D shadowSampler{X};\nuniform mat4 lightMatrix{X};\n#endif\nuniform vec4 shadowsInfo{X};\nuniform vec2 depthValues{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\n#endif\n#ifdef HEMILIGHT{X}\nuniform vec3 vLightGround{X};\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#endif","lightsFragmentFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n#ifdef NDOTL\nfloat ndl;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 lightVectorW;\nfloat attenuation=1.0;\nif (lightData.w == 0.)\n{\nvec3 direction=lightData.xyz-vPositionW;\nattenuation=max(0.,1.0-length(direction)/range);\nlightVectorW=normalize(direction);\n}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);\n}\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 direction=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(direction);\nfloat attenuation=max(0.,1.0-length(direction)/range);\n\nfloat cosAngle=max(0.,dot(lightDirection.xyz,-lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\nattenuation*=cosAngle;\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\n#ifdef NDOTL\nresult.ndl=0.;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\nlightingInfo result;\n\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor;\n#endif\nreturn result;\n}\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){\nvec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);\nstrq/=strq.w;\nvec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;\n#ifdef PBR\ntextureColor=toLinearSpace(textureColor);\n#endif\nreturn textureColor;\n}","lightUboDeclaration":"#ifdef LIGHT{X}\nuniform Light{X}\n{\nvec4 vLightData;\nvec4 vLightDiffuse;\nvec3 vLightSpecular;\n#ifdef SPOTLIGHT{X}\nvec4 vLightDirection;\n#endif\n#ifdef HEMILIGHT{X}\nvec3 vLightGround;\n#endif\nvec4 shadowsInfo;\nvec2 depthValues;\n} light{X};\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\nuniform sampler2D shadowSampler{X};\nuniform mat4 lightMatrix{X};\n#endif\n#endif\n#endif","defaultVertexDeclaration":"\nuniform mat4 viewProjection;\nuniform mat4 view;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n","defaultFragmentDeclaration":"uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifndef REFRACTIONMAP_3D\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\n#endif\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_SKYBOX\n#else\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif","defaultUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nvec4 diffuseLeftColor;\nvec4 diffuseRightColor;\nvec4 opacityParts;\nvec4 reflectionLeftColor;\nvec4 reflectionRightColor;\nvec4 refractionLeftColor;\nvec4 refractionRightColor;\nvec4 emissiveLeftColor; \nvec4 emissiveRightColor;\nvec2 vDiffuseInfos;\nvec2 vAmbientInfos;\nvec2 vOpacityInfos;\nvec2 vReflectionInfos;\nvec3 vReflectionPosition;\nvec3 vReflectionSize;\nvec2 vEmissiveInfos;\nvec2 vLightmapInfos;\nvec2 vSpecularInfos;\nvec3 vBumpInfos;\nmat4 diffuseMatrix;\nmat4 ambientMatrix;\nmat4 opacityMatrix;\nmat4 reflectionMatrix;\nmat4 emissiveMatrix;\nmat4 lightmapMatrix;\nmat4 specularMatrix;\nmat4 bumpMatrix; \nvec4 vTangentSpaceParams;\nmat4 refractionMatrix;\nvec4 vRefractionInfos;\nvec4 vSpecularColor;\nvec3 vEmissiveColor;\nvec4 vDiffuseColor;\nfloat pointSize; \n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","shadowsFragmentFunctions":"#ifdef SHADOWS\n#ifndef SHADOWFLOAT\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x;\n#endif\nif (depth>shadow)\n{\nreturn darkness;\n}\nreturn 1.0;\n}\nfloat computeShadowWithPCFCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\n#ifndef SHADOWFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<depth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<depth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\nfloat computeShadowWithESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness); \nreturn esm;\n}\nfloat computeShadowWithCloseESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn esm;\n}\nfloat computeShadow(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadow=texture2D(shadowSampler,uv).x;\n#endif\nif (shadowPixelDepth>shadow)\n{\nreturn computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff);\n}\nreturn 1.;\n}\nfloat computeShadowWithPCF(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float mapSize,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\n#ifndef SHADOWFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<shadowPixelDepth) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<shadowPixelDepth) visibility-=0.25;\n#endif\nreturn computeFallOff(min(1.0,visibility+darkness),clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithCloseESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0); \n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\n#endif\n","fresnelFunction":"#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{\nfloat fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);\nreturn clamp(fresnelTerm,0.,1.);\n}\n#endif","reflectionFunction":"#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\nvec3 parallaxCorrectNormal( vec3 vertexPos,vec3 origVec,vec3 cubeSize,vec3 cubePos ) {\n\nvec3 invOrigVec=vec3(1.0,1.0,1.0)/origVec;\nvec3 halfSize=cubeSize*0.5;\nvec3 intersecAtMaxPlane=(cubePos+halfSize-vertexPos)*invOrigVec;\nvec3 intersecAtMinPlane=(cubePos-halfSize-vertexPos)*invOrigVec;\n\nvec3 largestIntersec=max(intersecAtMaxPlane,intersecAtMinPlane);\n\nfloat distance=min(min(largestIntersec.x,largestIntersec.y),largestIntersec.z);\n\nvec3 intersectPositionWS=vertexPos+origVec*distance;\n\nreturn intersectPositionWS-cubePos;\n}\n#endif\nvec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvec3 direction=vDirectionW;\nfloat t=clamp(direction.y*-0.5+0.5,0.,1.0);\nfloat s=atan(direction.z,direction.x)*RECIPROCAL_PI2+0.5;\n#ifdef REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED\nreturn vec3(1.0-s,t,0);\n#else\nreturn vec3(s,t,0);\n#endif\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nvec3 cameraToVertex=normalize(worldPos.xyz-vEyePosition.xyz);\nvec3 r=reflect(cameraToVertex,worldNormal);\nfloat t=clamp(r.y*-0.5+0.5,0.,1.0);\nfloat s=atan(r.z,r.x)*RECIPROCAL_PI2+0.5;\nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 viewDir=normalize(vec3(view*worldPos));\nvec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));\nvec3 r=reflect(viewDir,viewNormal);\nr.z=r.z-1.0;\nfloat m=2.0*length(r);\nreturn vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition.xyz;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=normalize(worldPos.xyz-vEyePosition.xyz);\n\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\ncoords=parallaxCorrectNormal(worldPos.xyz,coords,vReflectionSize,vReflectionPosition);\n#endif\ncoords=vec3(reflectionMatrix*vec4(coords,0));\n#ifdef INVERTCUBICMAP\ncoords.y*=-1.0;\n#endif\nreturn coords;\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}","imageProcessingDeclaration":"#ifdef EXPOSURE\nuniform float exposureLinear;\n#endif\n#ifdef CONTRAST\nuniform float contrast;\n#endif\n#ifdef VIGNETTE\nuniform vec2 vInverseScreenSize;\nuniform vec4 vignetteSettings1;\nuniform vec4 vignetteSettings2;\n#endif\n#ifdef COLORCURVES\nuniform vec4 vCameraColorCurveNegative;\nuniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\n#endif\n#ifdef COLORGRADING\n#ifdef COLORGRADING3D\nuniform highp sampler3D txColorTransform;\n#else\nuniform sampler2D txColorTransform;\n#endif\nuniform vec4 colorTransformSettings;\n#endif","imageProcessingFunctions":"#if defined(COLORGRADING) && !defined(COLORGRADING3D)\n\nvec3 sampleTexture3D(sampler2D colorTransform,vec3 color,vec2 sampler3dSetting)\n{\nfloat sliceSize=2.0*sampler3dSetting.x; \n#ifdef SAMPLER3DGREENDEPTH\nfloat sliceContinuous=(color.g-sampler3dSetting.x)*sampler3dSetting.y;\n#else\nfloat sliceContinuous=(color.b-sampler3dSetting.x)*sampler3dSetting.y;\n#endif\nfloat sliceInteger=floor(sliceContinuous);\n\n\nfloat sliceFraction=sliceContinuous-sliceInteger;\n#ifdef SAMPLER3DGREENDEPTH\nvec2 sliceUV=color.rb;\n#else\nvec2 sliceUV=color.rg;\n#endif\nsliceUV.x*=sliceSize;\nsliceUV.x+=sliceInteger*sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice0Color=texture2D(colorTransform,sliceUV);\nsliceUV.x+=sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice1Color=texture2D(colorTransform,sliceUV);\nvec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\n#ifdef SAMPLER3DBGRMAP\ncolor.rgb=result.rgb;\n#else\ncolor.rgb=result.bgr;\n#endif\nreturn color;\n}\n#endif\nvec4 applyImageProcessing(vec4 result) {\n#ifdef EXPOSURE\nresult.rgb*=exposureLinear;\n#endif\n#ifdef VIGNETTE\n\nvec2 viewportXY=gl_FragCoord.xy*vInverseScreenSize;\nviewportXY=viewportXY*2.0-1.0;\nvec3 vignetteXY1=vec3(viewportXY*vignetteSettings1.xy+vignetteSettings1.zw,1.0);\nfloat vignetteTerm=dot(vignetteXY1,vignetteXY1);\nfloat vignette=pow(vignetteTerm,vignetteSettings2.w);\n\nvec3 vignetteColor=vignetteSettings2.rgb;\n#ifdef VIGNETTEBLENDMODEMULTIPLY\nvec3 vignetteColorMultiplier=mix(vignetteColor,vec3(1,1,1),vignette);\nresult.rgb*=vignetteColorMultiplier;\n#endif\n#ifdef VIGNETTEBLENDMODEOPAQUE\nresult.rgb=mix(vignetteColor,result.rgb,vignette);\n#endif\n#endif\n#ifdef TONEMAPPING\nconst float tonemappingCalibration=1.590579;\nresult.rgb=1.0-exp2(-tonemappingCalibration*result.rgb);\n#endif\n\nresult.rgb=toGammaSpace(result.rgb);\nresult.rgb=clamp(result.rgb,0.0,1.0);\n#ifdef CONTRAST\n\nvec3 resultHighContrast=applyEaseInOut(result.rgb);\nif (contrast<1.0) {\n\nresult.rgb=mix(vec3(0.5,0.5,0.5),result.rgb,contrast);\n} else {\n\nresult.rgb=mix(result.rgb,resultHighContrast,contrast-1.0);\n}\n#endif\n\n#ifdef COLORGRADING\nvec3 colorTransformInput=result.rgb*colorTransformSettings.xxx+colorTransformSettings.yyy;\n#ifdef COLORGRADING3D\nvec3 colorTransformOutput=texture(txColorTransform,colorTransformInput).rgb;\n#else\nvec3 colorTransformOutput=sampleTexture3D(txColorTransform,colorTransformInput,colorTransformSettings.yz).rgb;\n#endif\nresult.rgb=mix(result.rgb,colorTransformOutput,colorTransformSettings.www);\n#endif\n#ifdef COLORCURVES\n\nfloat luma=getLuminance(result.rgb);\nvec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0),vec2(1.0));\nvec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;\nresult.rgb*=colorCurve.rgb;\nresult.rgb=mix(vec3(luma),result.rgb,colorCurve.a);\n#endif\nreturn result;\n}","bumpFragmentFunctions":"#ifdef BUMP\n#if BUMPDIRECTUV == 1\n#define vBumpUV vMainUV1\n#elif BUMPDIRECTUV == 2\n#define vBumpUV vMainUV2\n#else\nvarying vec2 vBumpUV;\n#endif\nuniform sampler2D bumpSampler;\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#ifdef OBJECTSPACE_NORMALMAP\nuniform mat4 normalMatrix;\n#endif\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\n\nuv=gl_FrontFacing ? uv : -uv;\n\nvec3 dp1=dFdx(p);\nvec3 dp2=dFdy(p);\nvec2 duv1=dFdx(uv);\nvec2 duv2=dFdy(uv);\n\nvec3 dp2perp=cross(dp2,normal);\nvec3 dp1perp=cross(normal,dp1);\nvec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;\nvec3 bitangent=dp2perp*duv1.y+dp1perp*duv2.y;\n\ntangent*=vTangentSpaceParams.x;\nbitangent*=vTangentSpaceParams.y;\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(bitangent,bitangent)));\nreturn mat3(tangent*invmax,bitangent*invmax,normal);\n}\nvec3 perturbNormal(mat3 cotangentFrame,vec2 uv)\n{\nvec3 map=texture2D(bumpSampler,uv).xyz;\nmap=map*2.0-1.0;\n#ifdef NORMALXYSCALE\nmap=normalize(map*vec3(vBumpInfos.y,vBumpInfos.y,1.0));\n#endif\nreturn normalize(cotangentFrame*map);\n}\n#ifdef PARALLAX\nconst float minSamples=4.;\nconst float maxSamples=15.;\nconst int iMaxSamples=15;\n\nvec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {\nfloat parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;\nparallaxLimit*=parallaxScale;\nvec2 vOffsetDir=normalize(vViewDirCoT.xy);\nvec2 vMaxOffset=vOffsetDir*parallaxLimit;\nfloat numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));\nfloat stepSize=1.0/numSamples;\n\nfloat currRayHeight=1.0;\nvec2 vCurrOffset=vec2(0,0);\nvec2 vLastOffset=vec2(0,0);\nfloat lastSampledHeight=1.0;\nfloat currSampledHeight=1.0;\nfor (int i=0; i<iMaxSamples; i++)\n{\ncurrSampledHeight=texture2D(bumpSampler,vBumpUV+vCurrOffset).w;\n\nif (currSampledHeight>currRayHeight)\n{\nfloat delta1=currSampledHeight-currRayHeight;\nfloat delta2=(currRayHeight+stepSize)-lastSampledHeight;\nfloat ratio=delta1/(delta1+delta2);\nvCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;\n\nbreak;\n}\nelse\n{\ncurrRayHeight-=stepSize;\nvLastOffset=vCurrOffset;\nvCurrOffset+=stepSize*vMaxOffset;\nlastSampledHeight=currSampledHeight;\n}\n}\nreturn vCurrOffset;\n}\nvec2 parallaxOffset(vec3 viewDir,float heightScale)\n{\n\nfloat height=texture2D(bumpSampler,vBumpUV).w;\nvec2 texCoordOffset=heightScale*viewDir.xy*height;\nreturn -texCoordOffset;\n}\n#endif\n#endif","clipPlaneFragmentDeclaration":"#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif","fogFragmentDeclaration":"#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying vec3 vFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nfloat fogDistance=length(vFogDistance);\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif","clipPlaneFragment":"#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif","bumpFragment":"vec2 uvOffset=vec2(0.0,0.0);\n#if defined(BUMP) || defined(PARALLAX)\n#ifdef NORMALXYSCALE\nfloat normalScale=1.0;\n#else \nfloat normalScale=vBumpInfos.y;\n#endif\n#if defined(TANGENT) && defined(NORMAL)\nmat3 TBN=vTBN;\n#else\nmat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,vBumpUV);\n#endif\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nuvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z);\n#else\nuvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\n#endif\n#ifdef BUMP\n#ifdef OBJECTSPACE_NORMALMAP\nnormalW=normalize(texture2D(bumpSampler,vBumpUV).xyz*2.0-1.0);\nnormalW=normalize(mat3(normalMatrix)*normalW); \n#else\nnormalW=perturbNormal(TBN,vBumpUV+uvOffset);\n#endif\n#endif","lightFragment":"#ifdef LIGHT{X}\n#if defined(SHADOWONLY) || (defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X}))\n\n#else\n#ifdef PBR\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#else\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,glossiness);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\ninfo.diffuse*=computeProjectionTextureDiffuseLighting(projectionLightSampler{X},textureProjectionMatrix{X});\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCLOSEESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithCloseESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithCloseESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#else\n#ifdef SHADOWESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#else \n#ifdef SHADOWPCF{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithPCFCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadowWithPCF(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#else\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadow(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#endif\n#endif\n#endif\n#ifdef SHADOWONLY\n#ifndef SHADOWINUSE\n#define SHADOWINUSE\n#endif\nglobalShadow+=shadow;\nshadowLightCount+=1.0;\n#endif\n#else\nshadow=1.;\n#endif\n#ifndef SHADOWONLY\n#ifdef CUSTOMUSERLIGHTING\ndiffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow);\n#ifdef SPECULARTERM\nspecularBase+=computeCustomSpecularLighting(info,specularBase,shadow);\n#endif\n#elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\ndiffuseBase+=lightmapColor*shadow;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nspecularBase+=info.specular*shadow*lightmapColor;\n#endif\n#endif\n#else\ndiffuseBase+=info.diffuse*shadow;\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#endif\n#endif\n#endif","logDepthFragment":"#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif","fogFragment":"#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\n#endif","pbrVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#ifdef REFLECTIVITY \nuniform vec3 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform mat4 microSurfaceSamplerMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n","pbrFragmentDeclaration":"uniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\n#ifdef ALBEDO\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef REFLECTIVITY\nuniform vec3 vReflectivityInfos;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\n#endif\n\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif","pbrUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec2 vAlbedoInfos;\nuniform vec3 vAmbientInfos;\nuniform vec2 vOpacityInfos;\nuniform vec2 vEmissiveInfos;\nuniform vec2 vLightmapInfos;\nuniform vec3 vReflectivityInfos;\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform vec4 vRefractionInfos;\nuniform vec2 vReflectionInfos;\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \nuniform vec3 vBumpInfos;\nuniform mat4 albedoMatrix;\nuniform mat4 ambientMatrix;\nuniform mat4 opacityMatrix;\nuniform mat4 emissiveMatrix;\nuniform mat4 lightmapMatrix;\nuniform mat4 reflectivityMatrix;\nuniform mat4 microSurfaceSamplerMatrix;\nuniform mat4 bumpMatrix;\nuniform vec2 vTangentSpaceParams;\nuniform mat4 refractionMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\nuniform vec4 vLightingIntensity;\nuniform vec3 vRefractionMicrosurfaceInfos;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\nuniform float pointSize;\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","pbrFunctions":"\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n\nconst float kRougnhessToAlphaScale=0.1;\nconst float kRougnhessToAlphaOffset=0.29248125;\nfloat convertRoughnessToAverageSlope(float roughness)\n{\n\nconst float kMinimumVariance=0.0005;\nfloat alphaG=square(roughness)+kMinimumVariance;\nreturn alphaG;\n}\n\nfloat smithVisibilityG1_TrowbridgeReitzGGX(float dot,float alphaG)\n{\nfloat tanSquared=(1.0-dot*dot)/(dot*dot);\nreturn 2.0/(1.0+sqrt(1.0+alphaG*alphaG*tanSquared));\n}\nfloat smithVisibilityG_TrowbridgeReitzGGX_Walter(float NdotL,float NdotV,float alphaG)\n{\nreturn smithVisibilityG1_TrowbridgeReitzGGX(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGX(NdotV,alphaG);\n}\n\n\nfloat normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)\n{\n\n\n\nfloat a2=square(alphaG);\nfloat d=NdotH*NdotH*(a2-1.0)+1.0;\nreturn a2/(PI*d*d);\n}\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow(clamp(1.0-VdotH,0.,1.),5.0);\n}\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n\nvec3 computeSpecularTerm(float NdotH,float NdotL,float NdotV,float VdotH,float roughness,vec3 reflectance0,vec3 reflectance90)\n{\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\nfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);\nfloat visibility=smithVisibilityG_TrowbridgeReitzGGX_Walter(NdotL,NdotV,alphaG);\nvisibility/=(4.0*NdotL*NdotV); \nfloat specTerm=max(0.,visibility*distribution)*NdotL;\nvec3 fresnel=fresnelSchlickGGX(VdotH,reflectance0,reflectance90);\nreturn fresnel*specTerm;\n}\nfloat computeDiffuseTerm(float NdotL,float NdotV,float VdotH,float roughness)\n{\n\n\nfloat diffuseFresnelNV=pow(clamp(1.0-NdotL,0.000001,1.),5.0);\nfloat diffuseFresnelNL=pow(clamp(1.0-NdotV,0.000001,1.),5.0);\nfloat diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;\nfloat fresnel =\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);\nreturn fresnel*NdotL/PI;\n}\nfloat adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\n\nfloat lightRoughness=lightRadius/lightDistance;\n\nfloat totalRoughness=clamp(lightRoughness+roughness,0.,1.);\nreturn totalRoughness;\n#else\nreturn roughness;\n#endif\n}\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{\nconst float kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\nfloat reflectivityLuminance=getLuminance(reflectivityColor);\nfloat reflectivityLuma=sqrt(reflectivityLuminance);\nmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\nreturn microSurface;\n}\n\n\nfloat fresnelGrazingReflectance(float reflectance0) {\nfloat reflectance90=clamp(reflectance0*25.0,0.0,1.0);\nreturn reflectance90;\n}\n\n\n#define UNPACK_LOD(x) (1.0-x)*255.0\nfloat getLodFromAlphaG(float cubeMapDimensionPixels,float alphaG,float NdotV) {\nfloat microsurfaceAverageSlope=alphaG;\n\n\n\n\n\n\nmicrosurfaceAverageSlope*=sqrt(abs(NdotV));\nfloat microsurfaceAverageSlopeTexels=microsurfaceAverageSlope*cubeMapDimensionPixels;\nfloat lod=log2(microsurfaceAverageSlopeTexels);\nreturn lod;\n}\nfloat environmentRadianceOcclusion(float ambientOcclusion,float NdotVUnclamped) {\n\n\nfloat temp=NdotVUnclamped+ambientOcclusion;\nreturn clamp(square(temp)-1.0+ambientOcclusion,0.0,1.0);\n}\nfloat environmentHorizonOcclusion(vec3 reflection,vec3 normal) {\n\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflection.z*=-1.0;\n#endif\nfloat temp=clamp( 1.0+1.1*dot(reflection,normal),0.0,1.0);\nreturn square(temp);\n}","harmonicsFunctions":"#ifdef USESPHERICALFROMREFLECTIONMAP\nuniform vec3 vSphericalX;\nuniform vec3 vSphericalY;\nuniform vec3 vSphericalZ;\nuniform vec3 vSphericalXX_ZZ;\nuniform vec3 vSphericalYY_ZZ;\nuniform vec3 vSphericalZZ;\nuniform vec3 vSphericalXY;\nuniform vec3 vSphericalYZ;\nuniform vec3 vSphericalZX;\nvec3 quaternionVectorRotation_ScaledSqrtTwo(vec4 Q,vec3 V){\nvec3 T=cross(Q.xyz,V);\nT+=Q.www*V;\nreturn cross(Q.xyz,T)+V;\n}\nvec3 environmentIrradianceJones(vec3 normal)\n{\n\n\n\n\n\n\n\n\n\nfloat Nx=normal.x;\nfloat Ny=normal.y;\nfloat Nz=normal.z;\nvec3 C1=vSphericalZZ.rgb;\nvec3 Cx=vSphericalX.rgb;\nvec3 Cy=vSphericalY.rgb;\nvec3 Cz=vSphericalZ.rgb;\nvec3 Cxx_zz=vSphericalXX_ZZ.rgb;\nvec3 Cyy_zz=vSphericalYY_ZZ.rgb;\nvec3 Cxy=vSphericalXY.rgb;\nvec3 Cyz=vSphericalYZ.rgb;\nvec3 Czx=vSphericalZX.rgb;\nvec3 a1=Cyy_zz*Ny+Cy;\nvec3 a2=Cyz*Nz+a1;\nvec3 b1=Czx*Nz+Cx;\nvec3 b2=Cxy*Ny+b1;\nvec3 b3=Cxx_zz*Nx+b2;\nvec3 t1=Cz*Nz+C1;\nvec3 t2=a2*Ny+t1;\nvec3 t3=b3*Nx+t2;\nreturn t3;\n}\n#endif","pbrLightFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range)\n{ \n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat lightDistanceFalloff=1.0/((lightDistanceSquared+0.001));\n#else\nfloat lightDistanceFalloff=max(0.,1.0-length(lightOffset)/range);\n#endif\nreturn lightDistanceFalloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent)\n{\nfloat falloff=0.0;\n#ifdef USEPHYSICALLIGHTFALLOFF\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \n\n\n\n\n\nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\n\n\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\nfalloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\n#else\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection,directionToLightCenterW));\nif (cosAngle>=cosHalfAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\n#endif\nreturn falloff;\n}\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightDirection;\nfloat attenuation=1.0;\nfloat lightDistance;\n\nif (lightData.w == 0.)\n{\nvec3 lightOffset=lightData.xyz-vPositionW;\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nattenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\nlightDistance=sqrt(lightDistanceSquared);\nlightDirection=normalize(lightOffset);\n}\n\nelse\n{\nlightDistance=length(-lightData.xyz);\nlightDirection=normalize(-lightData.xyz);\n}\n\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+lightDirection);\nNdotL=clamp(dot(vNormal,lightDirection),0.00000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightOffset=lightData.xyz-vPositionW;\nvec3 directionToLightCenterW=normalize(lightOffset);\n\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nfloat attenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\n\nfloat directionalAttenuation=computeDirectionalLightFalloff(lightDirection.xyz,directionToLightCenterW,lightDirection.w,lightData.w);\nattenuation*=directionalAttenuation;\n\nfloat lightDistance=sqrt(lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+directionToLightCenterW);\nNdotL=clamp(dot(vNormal,directionToLightCenterW),0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\n\n\n\nNdotL=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,NdotL);\n#ifdef SPECULARTERM\n\nvec3 lightVectorW=normalize(lightData.xyz);\nvec3 H=normalize(viewDirectionW+lightVectorW);\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nNdotL=clamp(NdotL,0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor;\n#endif\nreturn result;\n}","mrtFragmentDeclaration":"#if __VERSION__>=200\nlayout(location=0) out vec4 glFragData[{X}];\n#endif\n","bones300Declaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nin vec4 matricesIndices;\nin vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nin vec4 matricesIndicesExtra;\nin vec4 matricesWeightsExtra;\n#endif\n#endif","instances300Declaration":"#ifdef INSTANCES\nin vec4 world0;\nin vec4 world1;\nin vec4 world2;\nin vec4 world3;\n#else\nuniform mat4 world;\n#endif","kernelBlurFragment":"#ifdef DOF\nsampleDepth=sampleDistance(sampleCoord{X});\nfactor=clamp(1.0-((centerSampleDepth-sampleDepth)/centerSampleDepth),0.0,1.0);\ncomputedWeight=KERNEL_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCoord{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCoord{X})*computedWeight;\n#endif","kernelBlurFragment2":"#ifdef DOF\nsampleDepth=sampleDistance(sampleCoord{X});\nfactor=clamp(1.0-((centerSampleDepth-sampleDepth)/centerSampleDepth),0.0,1.0);\ncomputedWeight=KERNEL_DEP_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_DEP_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*computedWeight;\n#endif","kernelBlurVaryingDeclaration":"varying vec2 sampleCoord{X};","kernelBlurVertex":"sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};","backgroundVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\nuniform float shadowLevel;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif","backgroundFragmentDeclaration":" uniform vec4 vPrimaryColor;\nuniform vec4 vSecondaryColor;\nuniform vec4 vTertiaryColor;\nuniform float shadowLevel;\nuniform float alpha;\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif","backgroundUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec4 vPrimaryColor;\nuniform vec4 vSecondaryColor;\nuniform vec4 vTertiaryColor;\nuniform vec2 vDiffuseInfos;\nuniform vec2 vReflectionInfos;\nuniform mat4 diffuseMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\nuniform float pointSize;\nuniform float shadowLevel;\nuniform float alpha;\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};"};
  90249. (function universalModuleDefinition(root, factory) {
  90250. var f = factory();
  90251. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  90252. globalObject["BABYLON"] = f;
  90253. if(true)
  90254. module.exports = f;
  90255. else if(typeof define === 'function' && define.amd)
  90256. define("BABYLON", factory);
  90257. else if(typeof exports === 'object')
  90258. exports["BABYLON"] = f;
  90259. else {
  90260. root["BABYLON"] = f;
  90261. }
  90262. })(this, function() {
  90263. return BABYLON;
  90264. });
  90265. /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(2)))
  90266. /***/ }),
  90267. /* 1 */
  90268. /***/ (function(module, exports, __webpack_require__) {
  90269. "use strict";
  90270. Object.defineProperty(exports, "__esModule", { value: true });
  90271. var babylonjs_1 = __webpack_require__(0);
  90272. var helper_1 = __webpack_require__(3);
  90273. var HTMLMapper = (function () {
  90274. function HTMLMapper() {
  90275. }
  90276. HTMLMapper.prototype.map = function (element) {
  90277. var config = {};
  90278. var _loop_1 = function (attrIdx) {
  90279. var attr = element.attributes.item(attrIdx);
  90280. var split = attr.nodeName.split('.');
  90281. split.reduce(function (currentConfig, key, idx) {
  90282. var camelKey = helper_1.kebabToCamel(key);
  90283. if (idx === split.length - 1) {
  90284. var val = attr.nodeValue;
  90285. if (val === "true") {
  90286. val = true;
  90287. }
  90288. else if (val === "false") {
  90289. val = false;
  90290. }
  90291. else {
  90292. var number = parseFloat(val);
  90293. if (!isNaN(number)) {
  90294. val = number;
  90295. }
  90296. }
  90297. currentConfig[camelKey] = val;
  90298. }
  90299. else {
  90300. currentConfig[camelKey] = currentConfig[camelKey] || {};
  90301. }
  90302. return currentConfig[camelKey];
  90303. }, config);
  90304. };
  90305. for (var attrIdx = 0; attrIdx < element.attributes.length; ++attrIdx) {
  90306. _loop_1(attrIdx);
  90307. }
  90308. return config;
  90309. };
  90310. return HTMLMapper;
  90311. }());
  90312. var JSONMapper = (function () {
  90313. function JSONMapper() {
  90314. }
  90315. JSONMapper.prototype.map = function (rawSource) {
  90316. return JSON.parse(rawSource);
  90317. };
  90318. return JSONMapper;
  90319. }());
  90320. var DOMMapper = (function () {
  90321. function DOMMapper() {
  90322. }
  90323. DOMMapper.prototype.map = function (baseElement) {
  90324. var htmlMapper = new HTMLMapper();
  90325. var config = htmlMapper.map(baseElement);
  90326. var traverseChildren = function (element, partConfig) {
  90327. var children = element.children;
  90328. if (children.length) {
  90329. for (var i = 0; i < children.length; ++i) {
  90330. var item = children.item(i);
  90331. var configMapped = htmlMapper.map(item);
  90332. var key = helper_1.kebabToCamel(item.nodeName.toLowerCase());
  90333. if (item.attributes.getNamedItem('array') && item.attributes.getNamedItem('array').nodeValue === 'true') {
  90334. partConfig[key] = [];
  90335. }
  90336. else {
  90337. if (element.attributes.getNamedItem('array') && element.attributes.getNamedItem('array').nodeValue === 'true') {
  90338. partConfig.push(configMapped);
  90339. }
  90340. else if (partConfig[key]) {
  90341. element.setAttribute('array', 'true');
  90342. var oldItem = partConfig[key];
  90343. partConfig = [oldItem, configMapped];
  90344. }
  90345. else {
  90346. partConfig[key] = configMapped;
  90347. }
  90348. }
  90349. traverseChildren(item, partConfig[key] || configMapped);
  90350. }
  90351. }
  90352. return partConfig;
  90353. };
  90354. traverseChildren(baseElement, config);
  90355. return config;
  90356. };
  90357. return DOMMapper;
  90358. }());
  90359. var MapperManager = (function () {
  90360. function MapperManager() {
  90361. this.mappers = {
  90362. "html": new HTMLMapper(),
  90363. "json": new JSONMapper(),
  90364. "dom": new DOMMapper()
  90365. };
  90366. }
  90367. MapperManager.prototype.getMapper = function (type) {
  90368. if (!this.mappers[type]) {
  90369. babylonjs_1.Tools.Error("No mapper defined for " + type);
  90370. }
  90371. return this.mappers[type] || this.mappers[MapperManager.DefaultMapper];
  90372. };
  90373. MapperManager.prototype.registerMapper = function (type, mapper) {
  90374. this.mappers[type] = mapper;
  90375. };
  90376. MapperManager.DefaultMapper = 'json';
  90377. return MapperManager;
  90378. }());
  90379. exports.MapperManager = MapperManager;
  90380. exports.mapperManager = new MapperManager();
  90381. /***/ }),
  90382. /* 2 */
  90383. /***/ (function(module, exports) {
  90384. var g;
  90385. // This works in non-strict mode
  90386. g = (function() {
  90387. return this;
  90388. })();
  90389. try {
  90390. // This works if eval is allowed (see CSP)
  90391. g = g || Function("return this")() || (1,eval)("this");
  90392. } catch(e) {
  90393. // This works if the window reference is available
  90394. if(typeof window === "object")
  90395. g = window;
  90396. }
  90397. // g can still be undefined, but nothing to do about it...
  90398. // We return undefined, instead of nothing here, so it's
  90399. // easier to handle this case. if(!global) { ...}
  90400. module.exports = g;
  90401. /***/ }),
  90402. /* 3 */
  90403. /***/ (function(module, exports, __webpack_require__) {
  90404. "use strict";
  90405. Object.defineProperty(exports, "__esModule", { value: true });
  90406. function isUrl(urlToCheck) {
  90407. if (urlToCheck.indexOf('http') === 0 || urlToCheck.indexOf('/') === 0 || urlToCheck.indexOf('./') === 0 || urlToCheck.indexOf('../') === 0) {
  90408. return true;
  90409. }
  90410. return false;
  90411. }
  90412. exports.isUrl = isUrl;
  90413. function kebabToCamel(s) {
  90414. return s.replace(/(\-\w)/g, function (m) { return m[1].toUpperCase(); });
  90415. }
  90416. exports.kebabToCamel = kebabToCamel;
  90417. function camelToKebab(str) {
  90418. return !str ? null : str.replace(/([A-Z])/g, function (g) { return '-' + g[0].toLowerCase(); });
  90419. }
  90420. exports.camelToKebab = camelToKebab;
  90421. /***/ }),
  90422. /* 4 */
  90423. /***/ (function(module, exports, __webpack_require__) {
  90424. "use strict";
  90425. Object.defineProperty(exports, "__esModule", { value: true });
  90426. var babylonjs_1 = __webpack_require__(0);
  90427. var ViewerManager = (function () {
  90428. function ViewerManager() {
  90429. this.viewers = {};
  90430. this.onViewerAddedObservable = new babylonjs_1.Observable();
  90431. }
  90432. ViewerManager.prototype.addViewer = function (viewer) {
  90433. this.viewers[viewer.getBaseId()] = viewer;
  90434. this._onViewerAdded(viewer);
  90435. };
  90436. ViewerManager.prototype.getViewerById = function (id) {
  90437. return this.viewers[id];
  90438. };
  90439. ViewerManager.prototype.getViewerByHTMLElement = function (element) {
  90440. for (var id in this.viewers) {
  90441. if (this.viewers[id].containerElement === element) {
  90442. return this.getViewerById(id);
  90443. }
  90444. }
  90445. };
  90446. ViewerManager.prototype.getViewerPromiseById = function (id) {
  90447. var _this = this;
  90448. return new Promise(function (resolve, reject) {
  90449. var localViewer = _this.getViewerById(id);
  90450. if (localViewer) {
  90451. return resolve(localViewer);
  90452. }
  90453. var viewerFunction = function (viewer) {
  90454. if (viewer.getBaseId() === id) {
  90455. resolve(viewer);
  90456. _this.onViewerAddedObservable.removeCallback(viewerFunction);
  90457. }
  90458. };
  90459. _this.onViewerAddedObservable.add(viewerFunction);
  90460. });
  90461. };
  90462. ViewerManager.prototype._onViewerAdded = function (viewer) {
  90463. this.onViewerAdded && this.onViewerAdded(viewer);
  90464. this.onViewerAddedObservable.notifyObservers(viewer);
  90465. };
  90466. return ViewerManager;
  90467. }());
  90468. exports.ViewerManager = ViewerManager;
  90469. exports.viewerManager = new ViewerManager();
  90470. /***/ }),
  90471. /* 5 */
  90472. /***/ (function(module, exports, __webpack_require__) {
  90473. "use strict";
  90474. var __extends = (this && this.__extends) || (function () {
  90475. var extendStatics = Object.setPrototypeOf ||
  90476. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  90477. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  90478. return function (d, b) {
  90479. extendStatics(d, b);
  90480. function __() { this.constructor = d; }
  90481. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  90482. };
  90483. })();
  90484. Object.defineProperty(exports, "__esModule", { value: true });
  90485. var viewer_1 = __webpack_require__(6);
  90486. var babylonjs_1 = __webpack_require__(0);
  90487. var DefaultViewer = (function (_super) {
  90488. __extends(DefaultViewer, _super);
  90489. function DefaultViewer(containerElement, initialConfiguration) {
  90490. if (initialConfiguration === void 0) { initialConfiguration = { extends: 'default' }; }
  90491. var _this = _super.call(this, containerElement, initialConfiguration) || this;
  90492. _this.containerElement = containerElement;
  90493. _this.onModelLoaded = function (meshes) {
  90494. var hideLoadingDelay = 500;
  90495. if (_this.configuration.lab && _this.configuration.lab.hideLoadingDelay !== undefined) {
  90496. hideLoadingDelay = _this.configuration.lab.hideLoadingDelay;
  90497. }
  90498. setTimeout(function () {
  90499. _this.hideLoadingScreen();
  90500. }, hideLoadingDelay);
  90501. meshes[0].rotation.y += Math.PI;
  90502. return;
  90503. };
  90504. _this.onModelLoadedObservable.add(_this.onModelLoaded);
  90505. return _this;
  90506. }
  90507. DefaultViewer.prototype.initScene = function () {
  90508. var _this = this;
  90509. return _super.prototype.initScene.call(this).then(function () {
  90510. _this.extendClassWithConfig(_this.scene, _this.configuration.scene);
  90511. return _this.scene;
  90512. });
  90513. };
  90514. DefaultViewer.prototype.onTemplatesLoaded = function () {
  90515. var _this = this;
  90516. this.showLoadingScreen();
  90517. this.initNavbar();
  90518. var closeButton = document.getElementById('close-button');
  90519. if (closeButton) {
  90520. closeButton.addEventListener('pointerdown', function () {
  90521. _this.hideOverlayScreen();
  90522. });
  90523. }
  90524. return _super.prototype.onTemplatesLoaded.call(this);
  90525. };
  90526. DefaultViewer.prototype.initNavbar = function () {
  90527. var navbar = this.templateManager.getTemplate('navBar');
  90528. if (navbar) {
  90529. var navbarHeight_1 = navbar.parent.clientHeight + 'px';
  90530. var navbarShown_1 = true;
  90531. var timeoutCancel_1;
  90532. var triggerNavbar = function (show, evt) {
  90533. if (show === void 0) { show = false; }
  90534. if (!navbar || evt.button > 0)
  90535. return;
  90536. timeoutCancel_1 && clearTimeout(timeoutCancel_1);
  90537. if (show === navbarShown_1)
  90538. return;
  90539. if (show) {
  90540. navbar.parent.style.bottom = show ? '0px' : '-' + navbarHeight_1;
  90541. navbarShown_1 = show;
  90542. }
  90543. else {
  90544. var visibilityTimeout = 2000;
  90545. if (navbar.configuration.params && navbar.configuration.params.visibilityTimeout !== undefined) {
  90546. visibilityTimeout = navbar.configuration.params.visibilityTimeout;
  90547. }
  90548. timeoutCancel_1 = setTimeout(function () {
  90549. if (navbar) {
  90550. navbar.parent.style.bottom = '-' + navbarHeight_1;
  90551. }
  90552. navbarShown_1 = show;
  90553. }, visibilityTimeout);
  90554. }
  90555. };
  90556. this.templateManager.eventManager.registerCallback('viewer', triggerNavbar.bind(this, false), 'pointerout');
  90557. this.templateManager.eventManager.registerCallback('viewer', triggerNavbar.bind(this, true), 'pointerdown');
  90558. this.templateManager.eventManager.registerCallback('viewer', triggerNavbar.bind(this, false), 'pointerup');
  90559. this.templateManager.eventManager.registerCallback('navBar', triggerNavbar.bind(this, true), 'pointerover');
  90560. var viewerTemplate = this.templateManager.getTemplate('viewer');
  90561. var viewerElement_1 = viewerTemplate && viewerTemplate.parent;
  90562. var triggerFullscren = function (eventData) {
  90563. if (viewerElement_1) {
  90564. var fullscreenElement = document.fullscreenElement || document.webkitFullscreenElement || document.mozFullScreenElement || document.msFullscreenElement;
  90565. if (!fullscreenElement) {
  90566. var requestFullScreen = viewerElement_1.requestFullscreen || viewerElement_1.webkitRequestFullscreen || viewerElement_1.msRequestFullscreen || viewerElement_1.mozRequestFullScreen;
  90567. requestFullScreen.call(viewerElement_1);
  90568. }
  90569. else {
  90570. var exitFullscreen = document.exitFullscreen || document.webkitExitFullscreen || document.msExitFullscreen || document.mozCancelFullScreen;
  90571. exitFullscreen.call(document);
  90572. }
  90573. }
  90574. };
  90575. this.templateManager.eventManager.registerCallback('navBar', triggerFullscren, 'pointerdown', '#fullscreen-button');
  90576. }
  90577. };
  90578. DefaultViewer.prototype.prepareContainerElement = function () {
  90579. this.containerElement.style.position = 'relative';
  90580. this.containerElement.style.display = 'flex';
  90581. };
  90582. DefaultViewer.prototype.configureModel = function (modelConfiguration, focusMeshes) {
  90583. if (focusMeshes === void 0) { focusMeshes = this.scene.meshes; }
  90584. _super.prototype.configureModel.call(this, modelConfiguration, focusMeshes);
  90585. var navbar = this.templateManager.getTemplate('navBar');
  90586. if (!navbar)
  90587. return;
  90588. var metadataContainer = navbar.parent.querySelector('#model-metadata');
  90589. if (metadataContainer) {
  90590. if (modelConfiguration.title !== undefined) {
  90591. var element = metadataContainer.querySelector('span.model-title');
  90592. if (element) {
  90593. element.innerHTML = modelConfiguration.title;
  90594. }
  90595. }
  90596. if (modelConfiguration.subtitle !== undefined) {
  90597. var element = metadataContainer.querySelector('span.model-subtitle');
  90598. if (element) {
  90599. element.innerHTML = modelConfiguration.subtitle;
  90600. }
  90601. }
  90602. if (modelConfiguration.thumbnail !== undefined) {
  90603. metadataContainer.querySelector('.thumbnail').style.backgroundImage = "url('" + modelConfiguration.thumbnail + "')";
  90604. }
  90605. }
  90606. };
  90607. DefaultViewer.prototype.loadModel = function (model) {
  90608. var _this = this;
  90609. if (model === void 0) { model = this.configuration.model; }
  90610. this.showLoadingScreen();
  90611. return _super.prototype.loadModel.call(this, model, true).catch(function (error) {
  90612. console.log(error);
  90613. _this.hideLoadingScreen();
  90614. _this.showOverlayScreen('error');
  90615. return _this.scene;
  90616. });
  90617. };
  90618. DefaultViewer.prototype.showOverlayScreen = function (subScreen) {
  90619. var _this = this;
  90620. var template = this.templateManager.getTemplate('overlay');
  90621. if (!template)
  90622. return Promise.resolve('Overlay template not found');
  90623. return template.show((function (template) {
  90624. var canvasRect = _this.containerElement.getBoundingClientRect();
  90625. var canvasPositioning = window.getComputedStyle(_this.containerElement).position;
  90626. template.parent.style.display = 'flex';
  90627. template.parent.style.width = canvasRect.width + "px";
  90628. template.parent.style.height = canvasRect.height + "px";
  90629. template.parent.style.opacity = "1";
  90630. var subTemplate = _this.templateManager.getTemplate(subScreen);
  90631. if (!subTemplate) {
  90632. return Promise.reject(subScreen + ' template not found');
  90633. }
  90634. return subTemplate.show((function (template) {
  90635. template.parent.style.display = 'flex';
  90636. return Promise.resolve(template);
  90637. }));
  90638. }));
  90639. };
  90640. DefaultViewer.prototype.hideOverlayScreen = function () {
  90641. var template = this.templateManager.getTemplate('overlay');
  90642. if (!template)
  90643. return Promise.resolve('Overlay template not found');
  90644. return template.hide((function (template) {
  90645. template.parent.style.opacity = "0";
  90646. var onTransitionEnd = function () {
  90647. template.parent.removeEventListener("transitionend", onTransitionEnd);
  90648. template.parent.style.display = 'none';
  90649. };
  90650. template.parent.addEventListener("transitionend", onTransitionEnd);
  90651. var overlays = template.parent.querySelectorAll('.overlay');
  90652. if (overlays) {
  90653. for (var i = 0; i < overlays.length; ++i) {
  90654. var htmlElement = overlays.item(i);
  90655. htmlElement.style.display = 'none';
  90656. }
  90657. }
  90658. return Promise.resolve(template);
  90659. }));
  90660. };
  90661. DefaultViewer.prototype.showLoadingScreen = function () {
  90662. var _this = this;
  90663. var template = this.templateManager.getTemplate('loadingScreen');
  90664. if (!template)
  90665. return Promise.resolve('Loading Screen template not found');
  90666. return template.show((function (template) {
  90667. var canvasRect = _this.containerElement.getBoundingClientRect();
  90668. var canvasPositioning = window.getComputedStyle(_this.containerElement).position;
  90669. template.parent.style.display = 'flex';
  90670. template.parent.style.width = canvasRect.width + "px";
  90671. template.parent.style.height = canvasRect.height + "px";
  90672. template.parent.style.opacity = "1";
  90673. template.parent.style.backgroundColor = "black";
  90674. return Promise.resolve(template);
  90675. }));
  90676. };
  90677. DefaultViewer.prototype.hideLoadingScreen = function () {
  90678. var template = this.templateManager.getTemplate('loadingScreen');
  90679. if (!template)
  90680. return Promise.resolve('Loading Screen template not found');
  90681. return template.hide((function (template) {
  90682. template.parent.style.opacity = "0";
  90683. var onTransitionEnd = function () {
  90684. template.parent.removeEventListener("transitionend", onTransitionEnd);
  90685. template.parent.style.display = 'none';
  90686. };
  90687. template.parent.addEventListener("transitionend", onTransitionEnd);
  90688. return Promise.resolve(template);
  90689. }));
  90690. };
  90691. DefaultViewer.prototype.configureLights = function (lightsConfiguration, focusMeshes) {
  90692. var _this = this;
  90693. if (lightsConfiguration === void 0) { lightsConfiguration = {}; }
  90694. if (focusMeshes === void 0) { focusMeshes = this.scene.meshes; }
  90695. _super.prototype.configureLights.call(this, lightsConfiguration, focusMeshes);
  90696. if (this.configuration.lab && this.configuration.lab.flashlight) {
  90697. var pointerPosition = BABYLON.Vector3.Zero();
  90698. var lightTarget_1;
  90699. var angle = 0.5;
  90700. var exponent = Math.PI / 2;
  90701. if (typeof this.configuration.lab.flashlight === "object") {
  90702. exponent = this.configuration.lab.flashlight.exponent || exponent;
  90703. angle = this.configuration.lab.flashlight.angle || angle;
  90704. }
  90705. var flashlight = new babylonjs_1.SpotLight("flashlight", babylonjs_1.Vector3.Zero(), babylonjs_1.Vector3.Zero(), exponent, angle, this.scene);
  90706. if (typeof this.configuration.lab.flashlight === "object") {
  90707. flashlight.intensity = this.configuration.lab.flashlight.intensity || flashlight.intensity;
  90708. if (this.configuration.lab.flashlight.diffuse) {
  90709. flashlight.diffuse.r = this.configuration.lab.flashlight.diffuse.r;
  90710. flashlight.diffuse.g = this.configuration.lab.flashlight.diffuse.g;
  90711. flashlight.diffuse.b = this.configuration.lab.flashlight.diffuse.b;
  90712. }
  90713. if (this.configuration.lab.flashlight.specular) {
  90714. flashlight.specular.r = this.configuration.lab.flashlight.specular.r;
  90715. flashlight.specular.g = this.configuration.lab.flashlight.specular.g;
  90716. flashlight.specular.b = this.configuration.lab.flashlight.specular.b;
  90717. }
  90718. }
  90719. this.scene.constantlyUpdateMeshUnderPointer = true;
  90720. this.scene.onPointerObservable.add(function (eventData, eventState) {
  90721. if (eventData.type === 4 && eventData.pickInfo) {
  90722. lightTarget_1 = (eventData.pickInfo.pickedPoint);
  90723. }
  90724. else {
  90725. lightTarget_1 = undefined;
  90726. }
  90727. });
  90728. var updateFlashlightFunction = function () {
  90729. if (_this.camera && flashlight) {
  90730. flashlight.position.copyFrom(_this.camera.position);
  90731. if (lightTarget_1) {
  90732. lightTarget_1.subtractToRef(flashlight.position, flashlight.direction);
  90733. }
  90734. }
  90735. };
  90736. this.scene.registerBeforeRender(updateFlashlightFunction);
  90737. this.registeredOnBeforerenderFunctions.push(updateFlashlightFunction);
  90738. }
  90739. };
  90740. return DefaultViewer;
  90741. }(viewer_1.AbstractViewer));
  90742. exports.DefaultViewer = DefaultViewer;
  90743. /***/ }),
  90744. /* 6 */
  90745. /***/ (function(module, exports, __webpack_require__) {
  90746. "use strict";
  90747. Object.defineProperty(exports, "__esModule", { value: true });
  90748. var viewerManager_1 = __webpack_require__(4);
  90749. var templateManager_1 = __webpack_require__(19);
  90750. var loader_1 = __webpack_require__(22);
  90751. var babylonjs_1 = __webpack_require__(0);
  90752. var deepmerge = __webpack_require__(14);
  90753. var AbstractViewer = (function () {
  90754. function AbstractViewer(containerElement, initialConfiguration) {
  90755. if (initialConfiguration === void 0) { initialConfiguration = {}; }
  90756. var _this = this;
  90757. this.containerElement = containerElement;
  90758. this.resize = function () {
  90759. if (!_this.isCanvasInDOM()) {
  90760. return;
  90761. }
  90762. if (_this.canvas.clientWidth <= 0 || _this.canvas.clientHeight <= 0) {
  90763. return;
  90764. }
  90765. _this.engine.resize();
  90766. };
  90767. this.render = function () {
  90768. _this.scene && _this.scene.activeCamera && _this.scene.render();
  90769. };
  90770. if (containerElement.id) {
  90771. this.baseId = containerElement.id;
  90772. }
  90773. else {
  90774. this.baseId = containerElement.id = 'bjs' + Math.random().toString(32).substr(2, 8);
  90775. }
  90776. this.onSceneInitObservable = new babylonjs_1.Observable();
  90777. this.onEngineInitObservable = new babylonjs_1.Observable();
  90778. this.onModelLoadedObservable = new babylonjs_1.Observable();
  90779. this.onModelLoadProgressObservable = new babylonjs_1.Observable();
  90780. this.onModelLoadErrorObservable = new babylonjs_1.Observable();
  90781. this.onInitDoneObservable = new babylonjs_1.Observable();
  90782. this.onLoaderInitObservable = new babylonjs_1.Observable();
  90783. this.registeredOnBeforerenderFunctions = [];
  90784. viewerManager_1.viewerManager.addViewer(this);
  90785. this.templateManager = new templateManager_1.TemplateManager(containerElement);
  90786. this.prepareContainerElement();
  90787. loader_1.default.loadConfiguration(initialConfiguration, function (configuration) {
  90788. _this.configuration = deepmerge(_this.configuration || {}, configuration);
  90789. if (_this.configuration.observers) {
  90790. _this.configureObservers(_this.configuration.observers);
  90791. }
  90792. var templateConfiguration = _this.configuration.templates || {};
  90793. _this.templateManager.initTemplate(templateConfiguration);
  90794. _this.templateManager.onAllLoaded.add(function () {
  90795. var canvas = _this.templateManager.getCanvas();
  90796. if (canvas) {
  90797. _this.canvas = canvas;
  90798. }
  90799. _this._onTemplateLoaded();
  90800. });
  90801. });
  90802. }
  90803. Object.defineProperty(AbstractViewer.prototype, "isHdrSupported", {
  90804. get: function () {
  90805. return this._hdrSupport;
  90806. },
  90807. enumerable: true,
  90808. configurable: true
  90809. });
  90810. AbstractViewer.prototype.getBaseId = function () {
  90811. return this.baseId;
  90812. };
  90813. AbstractViewer.prototype.isCanvasInDOM = function () {
  90814. return !!this.canvas && !!this.canvas.parentElement;
  90815. };
  90816. AbstractViewer.prototype.updateConfiguration = function (newConfiguration) {
  90817. if (newConfiguration === void 0) { newConfiguration = this.configuration; }
  90818. this.configuration = deepmerge(this.configuration || {}, newConfiguration);
  90819. if (newConfiguration.scene) {
  90820. this.configureScene(newConfiguration.scene);
  90821. }
  90822. if (newConfiguration.optimizer) {
  90823. this.configureOptimizer(newConfiguration.optimizer);
  90824. }
  90825. if (newConfiguration.observers) {
  90826. this.configureObservers(newConfiguration.observers);
  90827. }
  90828. if (newConfiguration.model && typeof newConfiguration.model === 'object') {
  90829. this.configureModel(newConfiguration.model);
  90830. }
  90831. if (newConfiguration.lights) {
  90832. this.configureLights(newConfiguration.lights);
  90833. }
  90834. if (newConfiguration.skybox !== undefined || newConfiguration.ground !== undefined) {
  90835. this.configureEnvironment(newConfiguration.skybox, newConfiguration.ground);
  90836. }
  90837. if (newConfiguration.camera) {
  90838. this.configureCamera(newConfiguration.camera);
  90839. }
  90840. };
  90841. AbstractViewer.prototype.configureEnvironment = function (skyboxConifguration, groundConfiguration) {
  90842. if (!skyboxConifguration && !groundConfiguration) {
  90843. if (this.environmentHelper) {
  90844. this.environmentHelper.dispose();
  90845. delete this.environmentHelper;
  90846. }
  90847. ;
  90848. return Promise.resolve(this.scene);
  90849. }
  90850. var options = {
  90851. createGround: !!groundConfiguration,
  90852. createSkybox: !!skyboxConifguration,
  90853. setupImageProcessing: false
  90854. };
  90855. if (groundConfiguration) {
  90856. var groundConfig = (typeof groundConfiguration === 'boolean') ? {} : groundConfiguration;
  90857. var groundSize = groundConfig.size || (typeof skyboxConifguration === 'object' && skyboxConifguration.scale);
  90858. if (groundSize) {
  90859. options.groundSize = groundSize;
  90860. }
  90861. options.enableGroundShadow = groundConfig === true || groundConfig.receiveShadows;
  90862. if (groundConfig.shadowLevel !== undefined) {
  90863. options.groundShadowLevel = groundConfig.shadowLevel;
  90864. }
  90865. options.enableGroundMirror = !!groundConfig.mirror;
  90866. if (groundConfig.texture) {
  90867. options.groundTexture = groundConfig.texture;
  90868. }
  90869. if (groundConfig.color) {
  90870. options.groundColor = new babylonjs_1.Color3(groundConfig.color.r, groundConfig.color.g, groundConfig.color.b);
  90871. }
  90872. if (groundConfig.opacity !== undefined) {
  90873. options.groundOpacity = groundConfig.opacity;
  90874. }
  90875. if (groundConfig.mirror) {
  90876. options.enableGroundMirror = true;
  90877. if (typeof groundConfig.mirror === "object") {
  90878. if (groundConfig.mirror.amount !== undefined)
  90879. options.groundMirrorAmount = groundConfig.mirror.amount;
  90880. if (groundConfig.mirror.sizeRatio !== undefined)
  90881. options.groundMirrorSizeRatio = groundConfig.mirror.sizeRatio;
  90882. if (groundConfig.mirror.blurKernel !== undefined)
  90883. options.groundMirrorBlurKernel = groundConfig.mirror.blurKernel;
  90884. if (groundConfig.mirror.fresnelWeight !== undefined)
  90885. options.groundMirrorFresnelWeight = groundConfig.mirror.fresnelWeight;
  90886. if (groundConfig.mirror.fallOffDistance !== undefined)
  90887. options.groundMirrorFallOffDistance = groundConfig.mirror.fallOffDistance;
  90888. if (this.defaultPipelineTextureType !== undefined)
  90889. options.groundMirrorTextureType = this.defaultPipelineTextureType;
  90890. }
  90891. }
  90892. }
  90893. var postInitSkyboxMaterial = false;
  90894. if (skyboxConifguration) {
  90895. var conf = skyboxConifguration === true ? {} : skyboxConifguration;
  90896. if (conf.material && conf.material.imageProcessingConfiguration) {
  90897. options.setupImageProcessing = false;
  90898. }
  90899. var skyboxSize = conf.scale;
  90900. if (skyboxSize) {
  90901. options.skyboxSize = skyboxSize;
  90902. }
  90903. options.sizeAuto = !options.skyboxSize;
  90904. if (conf.color) {
  90905. options.skyboxColor = new babylonjs_1.Color3(conf.color.r, conf.color.g, conf.color.b);
  90906. }
  90907. if (conf.cubeTexture && conf.cubeTexture.url) {
  90908. if (typeof conf.cubeTexture.url === "string") {
  90909. options.skyboxTexture = conf.cubeTexture.url;
  90910. }
  90911. else {
  90912. postInitSkyboxMaterial = true;
  90913. }
  90914. }
  90915. if (conf.material && conf.material.imageProcessingConfiguration) {
  90916. postInitSkyboxMaterial = true;
  90917. }
  90918. }
  90919. options.setupImageProcessing = false;
  90920. if (!this.environmentHelper) {
  90921. this.environmentHelper = this.scene.createDefaultEnvironment(options);
  90922. }
  90923. else {
  90924. var scene = this.environmentHelper.rootMesh.getScene();
  90925. if (scene !== this.scene) {
  90926. this.environmentHelper.dispose();
  90927. this.environmentHelper = this.scene.createDefaultEnvironment(options);
  90928. }
  90929. else {
  90930. this.environmentHelper.updateOptions(options);
  90931. }
  90932. }
  90933. if (postInitSkyboxMaterial) {
  90934. var skyboxMaterial = this.environmentHelper.skyboxMaterial;
  90935. if (skyboxMaterial) {
  90936. if (typeof skyboxConifguration === 'object' && skyboxConifguration.material && skyboxConifguration.material.imageProcessingConfiguration) {
  90937. this.extendClassWithConfig(skyboxMaterial.imageProcessingConfiguration, skyboxConifguration.material.imageProcessingConfiguration);
  90938. }
  90939. }
  90940. }
  90941. };
  90942. AbstractViewer.prototype.configureScene = function (sceneConfig, optimizerConfig) {
  90943. if (!this.scene) {
  90944. return;
  90945. }
  90946. if (sceneConfig.debug) {
  90947. this.scene.debugLayer.show();
  90948. }
  90949. else {
  90950. if (this.scene.debugLayer.isVisible()) {
  90951. this.scene.debugLayer.hide();
  90952. }
  90953. }
  90954. if (sceneConfig.clearColor) {
  90955. var cc = sceneConfig.clearColor;
  90956. var oldcc = this.scene.clearColor;
  90957. if (cc.r !== undefined) {
  90958. oldcc.r = cc.r;
  90959. }
  90960. if (cc.g !== undefined) {
  90961. oldcc.g = cc.g;
  90962. }
  90963. if (cc.b !== undefined) {
  90964. oldcc.b = cc.b;
  90965. }
  90966. if (cc.a !== undefined) {
  90967. oldcc.a = cc.a;
  90968. }
  90969. }
  90970. if (sceneConfig.imageProcessingConfiguration) {
  90971. this.extendClassWithConfig(this.scene.imageProcessingConfiguration, sceneConfig.imageProcessingConfiguration);
  90972. }
  90973. if (sceneConfig.environmentTexture) {
  90974. if (this.scene.environmentTexture) {
  90975. this.scene.environmentTexture.dispose();
  90976. }
  90977. var environmentTexture = babylonjs_1.CubeTexture.CreateFromPrefilteredData(sceneConfig.environmentTexture, this.scene);
  90978. this.scene.environmentTexture = environmentTexture;
  90979. }
  90980. if (sceneConfig.autoRotate) {
  90981. this.camera.useAutoRotationBehavior = true;
  90982. }
  90983. };
  90984. AbstractViewer.prototype.configureOptimizer = function (optimizerConfig) {
  90985. if (typeof optimizerConfig === 'boolean') {
  90986. if (this.sceneOptimizer) {
  90987. this.sceneOptimizer.stop();
  90988. this.sceneOptimizer.dispose();
  90989. delete this.sceneOptimizer;
  90990. }
  90991. if (optimizerConfig) {
  90992. this.sceneOptimizer = new babylonjs_1.SceneOptimizer(this.scene);
  90993. this.sceneOptimizer.start();
  90994. }
  90995. }
  90996. else {
  90997. var optimizerOptions = new babylonjs_1.SceneOptimizerOptions(optimizerConfig.targetFrameRate, optimizerConfig.trackerDuration);
  90998. if (optimizerConfig.degradation) {
  90999. switch (optimizerConfig.degradation) {
  91000. case "low":
  91001. optimizerOptions = babylonjs_1.SceneOptimizerOptions.LowDegradationAllowed(optimizerConfig.targetFrameRate);
  91002. break;
  91003. case "moderate":
  91004. optimizerOptions = babylonjs_1.SceneOptimizerOptions.ModerateDegradationAllowed(optimizerConfig.targetFrameRate);
  91005. break;
  91006. case "hight":
  91007. optimizerOptions = babylonjs_1.SceneOptimizerOptions.HighDegradationAllowed(optimizerConfig.targetFrameRate);
  91008. break;
  91009. }
  91010. }
  91011. if (this.sceneOptimizer) {
  91012. this.sceneOptimizer.stop();
  91013. this.sceneOptimizer.dispose();
  91014. }
  91015. this.sceneOptimizer = new babylonjs_1.SceneOptimizer(this.scene, optimizerOptions, optimizerConfig.autoGeneratePriorities, optimizerConfig.improvementMode);
  91016. this.sceneOptimizer.start();
  91017. }
  91018. };
  91019. AbstractViewer.prototype.configureObservers = function (observersConfiguration) {
  91020. if (observersConfiguration.onEngineInit) {
  91021. this.onEngineInitObservable.add(window[observersConfiguration.onEngineInit]);
  91022. }
  91023. else {
  91024. if (observersConfiguration.onEngineInit === '' && this.configuration.observers && this.configuration.observers.onEngineInit) {
  91025. this.onEngineInitObservable.removeCallback(window[this.configuration.observers.onEngineInit]);
  91026. }
  91027. }
  91028. if (observersConfiguration.onSceneInit) {
  91029. this.onSceneInitObservable.add(window[observersConfiguration.onSceneInit]);
  91030. }
  91031. else {
  91032. if (observersConfiguration.onSceneInit === '' && this.configuration.observers && this.configuration.observers.onSceneInit) {
  91033. this.onSceneInitObservable.removeCallback(window[this.configuration.observers.onSceneInit]);
  91034. }
  91035. }
  91036. if (observersConfiguration.onModelLoaded) {
  91037. this.onModelLoadedObservable.add(window[observersConfiguration.onModelLoaded]);
  91038. }
  91039. else {
  91040. if (observersConfiguration.onModelLoaded === '' && this.configuration.observers && this.configuration.observers.onModelLoaded) {
  91041. this.onModelLoadedObservable.removeCallback(window[this.configuration.observers.onModelLoaded]);
  91042. }
  91043. }
  91044. };
  91045. AbstractViewer.prototype.configureCamera = function (cameraConfig, focusMeshes) {
  91046. var _this = this;
  91047. if (focusMeshes === void 0) { focusMeshes = this.scene.meshes; }
  91048. if (!this.scene.activeCamera) {
  91049. this.scene.createDefaultCamera(true, true, true);
  91050. this.camera = this.scene.activeCamera;
  91051. }
  91052. if (cameraConfig.position) {
  91053. this.camera.position.copyFromFloats(cameraConfig.position.x || 0, cameraConfig.position.y || 0, cameraConfig.position.z || 0);
  91054. }
  91055. if (cameraConfig.rotation) {
  91056. this.camera.rotationQuaternion = new babylonjs_1.Quaternion(cameraConfig.rotation.x || 0, cameraConfig.rotation.y || 0, cameraConfig.rotation.z || 0, cameraConfig.rotation.w || 0);
  91057. }
  91058. this.extendClassWithConfig(this.camera, cameraConfig);
  91059. this.camera.minZ = cameraConfig.minZ || this.camera.minZ;
  91060. this.camera.maxZ = cameraConfig.maxZ || this.camera.maxZ;
  91061. if (cameraConfig.behaviors) {
  91062. for (var name_1 in cameraConfig.behaviors) {
  91063. this.setCameraBehavior(cameraConfig.behaviors[name_1], focusMeshes);
  91064. }
  91065. }
  91066. ;
  91067. var sceneExtends = this.scene.getWorldExtends(function (mesh) {
  91068. return !_this.environmentHelper || (mesh !== _this.environmentHelper.ground && mesh !== _this.environmentHelper.rootMesh && mesh !== _this.environmentHelper.skybox);
  91069. });
  91070. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  91071. var sceneDiagonalLenght = sceneDiagonal.length();
  91072. if (isFinite(sceneDiagonalLenght))
  91073. this.camera.upperRadiusLimit = sceneDiagonalLenght * 3;
  91074. };
  91075. AbstractViewer.prototype.configureLights = function (lightsConfiguration, focusMeshes) {
  91076. var _this = this;
  91077. if (lightsConfiguration === void 0) { lightsConfiguration = {}; }
  91078. if (focusMeshes === void 0) { focusMeshes = this.scene.meshes; }
  91079. if (!Object.keys(lightsConfiguration).length)
  91080. return;
  91081. var lightsAvailable = this.scene.lights.map(function (light) { return light.name; });
  91082. var lightsToConfigure = Object.keys(this.configuration.lights || []);
  91083. if (Object.keys(lightsToConfigure).length !== lightsAvailable.length) {
  91084. lightsAvailable.forEach(function (lName) {
  91085. if (lightsToConfigure.indexOf(lName) === -1) {
  91086. _this.scene.getLightByName(lName).dispose();
  91087. }
  91088. });
  91089. }
  91090. Object.keys(lightsConfiguration).forEach(function (name, idx) {
  91091. var lightConfig = { type: 0 };
  91092. if (typeof lightsConfiguration[name] === 'object') {
  91093. lightConfig = lightsConfiguration[name];
  91094. }
  91095. lightConfig.name = name;
  91096. var light;
  91097. if (lightsAvailable.indexOf(name) === -1) {
  91098. var constructor = babylonjs_1.Light.GetConstructorFromName(lightConfig.type, lightConfig.name, _this.scene);
  91099. if (!constructor)
  91100. return;
  91101. light = constructor();
  91102. }
  91103. else {
  91104. light = _this.scene.getLightByName(name);
  91105. lightsAvailable = lightsAvailable.filter(function (ln) { return ln !== name; });
  91106. if (lightConfig.type !== undefined && light.getTypeID() !== lightConfig.type) {
  91107. light.dispose();
  91108. var constructor = babylonjs_1.Light.GetConstructorFromName(lightConfig.type, lightConfig.name, _this.scene);
  91109. if (!constructor)
  91110. return;
  91111. light = constructor();
  91112. }
  91113. }
  91114. if (lightsConfiguration[name] === false) {
  91115. light.dispose();
  91116. return;
  91117. }
  91118. var enabled = lightConfig.enabled !== undefined ? lightConfig.enabled : !lightConfig.disabled;
  91119. light.setEnabled(enabled);
  91120. _this.extendClassWithConfig(light, lightConfig);
  91121. if (light instanceof babylonjs_1.ShadowLight) {
  91122. if (lightConfig.target) {
  91123. if (light.setDirectionToTarget) {
  91124. var target = babylonjs_1.Vector3.Zero().copyFrom(lightConfig.target);
  91125. light.setDirectionToTarget(target);
  91126. }
  91127. }
  91128. else if (lightConfig.direction) {
  91129. var direction = babylonjs_1.Vector3.Zero().copyFrom(lightConfig.direction);
  91130. light.direction = direction;
  91131. }
  91132. var shadowGenerator = light.getShadowGenerator();
  91133. if (lightConfig.shadowEnabled && _this.maxShadows) {
  91134. if (!shadowGenerator) {
  91135. shadowGenerator = new babylonjs_1.ShadowGenerator(512, light);
  91136. }
  91137. _this.extendClassWithConfig(shadowGenerator, lightConfig.shadowConfig || {});
  91138. var shadownMap = shadowGenerator.getShadowMap();
  91139. if (!shadownMap)
  91140. return;
  91141. var renderList = shadownMap.renderList;
  91142. for (var index = 0; index < focusMeshes.length; index++) {
  91143. if (babylonjs_1.Tags.MatchesQuery(focusMeshes[index], 'castShadow')) {
  91144. renderList && renderList.push(focusMeshes[index]);
  91145. }
  91146. }
  91147. }
  91148. else if (shadowGenerator) {
  91149. shadowGenerator.dispose();
  91150. }
  91151. }
  91152. });
  91153. };
  91154. AbstractViewer.prototype.configureModel = function (modelConfiguration, focusMeshes) {
  91155. if (focusMeshes === void 0) { focusMeshes = this.scene.meshes; }
  91156. var meshesWithNoParent = focusMeshes.filter(function (m) { return !m.parent; });
  91157. var updateMeshesWithNoParent = function (variable, value, param) {
  91158. meshesWithNoParent.forEach(function (mesh) {
  91159. if (param) {
  91160. mesh[variable][param] = value;
  91161. }
  91162. else {
  91163. mesh[variable] = value;
  91164. }
  91165. });
  91166. };
  91167. var updateXYZ = function (variable, configValues) {
  91168. if (configValues.x !== undefined) {
  91169. updateMeshesWithNoParent(variable, configValues.x, 'x');
  91170. }
  91171. if (configValues.y !== undefined) {
  91172. updateMeshesWithNoParent(variable, configValues.y, 'y');
  91173. }
  91174. if (configValues.z !== undefined) {
  91175. updateMeshesWithNoParent(variable, configValues.z, 'z');
  91176. }
  91177. if (configValues.w !== undefined) {
  91178. updateMeshesWithNoParent(variable, configValues.w, 'w');
  91179. }
  91180. };
  91181. if (modelConfiguration.position) {
  91182. updateXYZ('position', modelConfiguration.position);
  91183. }
  91184. if (modelConfiguration.rotation) {
  91185. if (modelConfiguration.rotation.w) {
  91186. meshesWithNoParent.forEach(function (mesh) {
  91187. if (!mesh.rotationQuaternion) {
  91188. mesh.rotationQuaternion = new babylonjs_1.Quaternion();
  91189. }
  91190. });
  91191. updateXYZ('rotationQuaternion', modelConfiguration.rotation);
  91192. }
  91193. else {
  91194. updateXYZ('rotation', modelConfiguration.rotation);
  91195. }
  91196. }
  91197. if (modelConfiguration.scaling) {
  91198. updateXYZ('scaling', modelConfiguration.scaling);
  91199. }
  91200. if (modelConfiguration.castShadow) {
  91201. focusMeshes.forEach(function (mesh) {
  91202. babylonjs_1.Tags.AddTagsTo(mesh, 'castShadow');
  91203. });
  91204. }
  91205. if (modelConfiguration.normalize) {
  91206. var center = false;
  91207. var unitSize = false;
  91208. var parentIndex = void 0;
  91209. if (modelConfiguration.normalize === true) {
  91210. center = true;
  91211. unitSize = true;
  91212. parentIndex = 0;
  91213. }
  91214. else {
  91215. center = !!modelConfiguration.normalize.center;
  91216. unitSize = !!modelConfiguration.normalize.unitSize;
  91217. parentIndex = modelConfiguration.normalize.parentIndex;
  91218. }
  91219. var meshesToNormalize = [];
  91220. if (parentIndex !== undefined) {
  91221. meshesToNormalize.push(focusMeshes[parentIndex]);
  91222. }
  91223. else {
  91224. meshesToNormalize = meshesWithNoParent;
  91225. }
  91226. if (unitSize) {
  91227. meshesToNormalize.forEach(function (mesh) {
  91228. mesh.normalizeToUnitCube(true);
  91229. mesh.computeWorldMatrix(true);
  91230. });
  91231. }
  91232. if (center) {
  91233. meshesToNormalize.forEach(function (mesh) {
  91234. var boundingInfo = mesh.getHierarchyBoundingVectors(true);
  91235. var sizeVec = boundingInfo.max.subtract(boundingInfo.min);
  91236. var halfSizeVec = sizeVec.scale(0.5);
  91237. var center = boundingInfo.min.add(halfSizeVec);
  91238. mesh.position = center.scale(-1);
  91239. mesh.position.y += halfSizeVec.y;
  91240. mesh.computeWorldMatrix(true);
  91241. });
  91242. }
  91243. }
  91244. };
  91245. AbstractViewer.prototype.dispose = function () {
  91246. window.removeEventListener('resize', this.resize);
  91247. if (this.sceneOptimizer) {
  91248. this.sceneOptimizer.stop();
  91249. this.sceneOptimizer.dispose();
  91250. }
  91251. if (this.scene.activeCamera) {
  91252. this.scene.activeCamera.detachControl(this.canvas);
  91253. }
  91254. this.scene.dispose();
  91255. this.engine.dispose();
  91256. this.templateManager.dispose();
  91257. };
  91258. AbstractViewer.prototype.onTemplatesLoaded = function () {
  91259. return Promise.resolve(this);
  91260. };
  91261. AbstractViewer.prototype._onTemplateLoaded = function () {
  91262. var _this = this;
  91263. return this.onTemplatesLoaded().then(function () {
  91264. var autoLoadModel = !!_this.configuration.model;
  91265. return _this.initEngine().then(function (engine) {
  91266. return _this.onEngineInitObservable.notifyObserversWithPromise(engine);
  91267. }).then(function () {
  91268. if (autoLoadModel) {
  91269. return _this.loadModel();
  91270. }
  91271. else {
  91272. return _this.scene || _this.initScene();
  91273. }
  91274. }).then(function (scene) {
  91275. return _this.onSceneInitObservable.notifyObserversWithPromise(scene);
  91276. }).then(function () {
  91277. return _this.onInitDoneObservable.notifyObserversWithPromise(_this);
  91278. }).then(function () {
  91279. return _this;
  91280. });
  91281. });
  91282. };
  91283. AbstractViewer.prototype.initEngine = function () {
  91284. this.injectCustomShaders();
  91285. var canvasElement = this.templateManager.getCanvas();
  91286. if (!canvasElement) {
  91287. return Promise.reject('Canvas element not found!');
  91288. }
  91289. var config = this.configuration.engine || {};
  91290. this.engine = new babylonjs_1.Engine(canvasElement, !!config.antialiasing, config.engineOptions);
  91291. babylonjs_1.Database.IDBStorageEnabled = false;
  91292. if (!config.disableResize) {
  91293. window.addEventListener('resize', this.resize);
  91294. }
  91295. this.engine.runRenderLoop(this.render);
  91296. if (this.configuration.engine && this.configuration.engine.adaptiveQuality) {
  91297. var scale = Math.max(0.5, 1 / (window.devicePixelRatio || 2));
  91298. this.engine.setHardwareScalingLevel(scale);
  91299. }
  91300. this.handleHardwareLimitations();
  91301. return Promise.resolve(this.engine);
  91302. };
  91303. AbstractViewer.prototype.initScene = function () {
  91304. if (this.scene) {
  91305. this.scene.dispose();
  91306. }
  91307. this.scene = new babylonjs_1.Scene(this.engine);
  91308. this.scene.createDefaultLight(true);
  91309. if (this.configuration.scene) {
  91310. this.configureScene(this.configuration.scene);
  91311. if (this.configuration.optimizer) {
  91312. this.configureOptimizer(this.configuration.optimizer);
  91313. }
  91314. }
  91315. return Promise.resolve(this.scene);
  91316. };
  91317. AbstractViewer.prototype.loadModel = function (model, clearScene) {
  91318. var _this = this;
  91319. if (model === void 0) { model = this.configuration.model; }
  91320. if (clearScene === void 0) { clearScene = true; }
  91321. var modelUrl = (typeof model === 'string') ? model : model.url;
  91322. if (!modelUrl) {
  91323. return Promise.resolve(this.scene);
  91324. }
  91325. if (this.isLoading) {
  91326. this.nextLoading = function () {
  91327. delete _this.nextLoading;
  91328. _this.loadModel(model, clearScene);
  91329. };
  91330. return Promise.resolve(this.scene);
  91331. }
  91332. this.isLoading = true;
  91333. if ((typeof model === 'string')) {
  91334. if (this.configuration.model && typeof this.configuration.model === 'object') {
  91335. this.configuration.model.url = model;
  91336. }
  91337. }
  91338. else {
  91339. if (this.configuration.model) {
  91340. deepmerge(this.configuration.model, model);
  91341. }
  91342. else {
  91343. this.configuration.model = model;
  91344. }
  91345. }
  91346. var parts = modelUrl.split('/');
  91347. var filename = parts.pop();
  91348. var base = parts.join('/') + '/';
  91349. var plugin = (typeof model === 'string') ? undefined : model.loader;
  91350. return Promise.resolve(this.scene).then(function (scene) {
  91351. if (!scene)
  91352. return _this.initScene();
  91353. if (clearScene) {
  91354. scene.meshes.forEach(function (mesh) {
  91355. if (babylonjs_1.Tags.MatchesQuery(mesh, "viewerMesh")) {
  91356. mesh.dispose();
  91357. }
  91358. });
  91359. }
  91360. return scene;
  91361. }).then(function () {
  91362. return new Promise(function (resolve, reject) {
  91363. _this.lastUsedLoader = babylonjs_1.SceneLoader.ImportMesh(undefined, base, filename, _this.scene, function (meshes) {
  91364. meshes.forEach(function (mesh) {
  91365. babylonjs_1.Tags.AddTagsTo(mesh, "viewerMesh");
  91366. });
  91367. resolve(meshes);
  91368. }, function (progressEvent) {
  91369. _this.onModelLoadProgressObservable.notifyObserversWithPromise(progressEvent);
  91370. }, function (e, m, exception) {
  91371. _this.onModelLoadErrorObservable.notifyObserversWithPromise({ message: m, exception: exception }).then(function () {
  91372. reject(exception);
  91373. });
  91374. }, plugin);
  91375. _this.onLoaderInitObservable.notifyObserversWithPromise(_this.lastUsedLoader);
  91376. });
  91377. }).then(function (meshes) {
  91378. return _this.onModelLoadedObservable.notifyObserversWithPromise(meshes)
  91379. .then(function () {
  91380. _this.configureModel(_this.configuration.model || model, meshes);
  91381. _this.configureLights(_this.configuration.lights);
  91382. if (_this.configuration.camera) {
  91383. _this.configureCamera(_this.configuration.camera, meshes);
  91384. }
  91385. return _this.initEnvironment(meshes);
  91386. }).then(function () {
  91387. _this.isLoading = false;
  91388. if (_this.nextLoading) {
  91389. return _this.nextLoading();
  91390. }
  91391. return _this.scene;
  91392. });
  91393. });
  91394. };
  91395. AbstractViewer.prototype.initEnvironment = function (focusMeshes) {
  91396. if (focusMeshes === void 0) { focusMeshes = this.scene.meshes; }
  91397. this.configureEnvironment(this.configuration.skybox, this.configuration.ground);
  91398. return Promise.resolve(this.scene);
  91399. };
  91400. AbstractViewer.prototype.handleHardwareLimitations = function () {
  91401. var maxVaryingRows = this.engine.getCaps().maxVaryingVectors;
  91402. var maxFragmentSamplers = this.engine.getCaps().maxTexturesImageUnits;
  91403. if ((maxVaryingRows < 8) || (maxFragmentSamplers < 8)) {
  91404. this.maxShadows = 0;
  91405. }
  91406. else {
  91407. this.maxShadows = 3;
  91408. }
  91409. var caps = this.engine.getCaps();
  91410. var linearHalfFloatTargets = caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering;
  91411. var linearFloatTargets = caps.textureFloatRender && caps.textureFloatLinearFiltering;
  91412. this._hdrSupport = !!(linearFloatTargets || linearHalfFloatTargets);
  91413. if (linearHalfFloatTargets) {
  91414. this.defaultHighpTextureType = babylonjs_1.Engine.TEXTURETYPE_HALF_FLOAT;
  91415. this.shadowGeneratorBias = 0.002;
  91416. }
  91417. else if (linearFloatTargets) {
  91418. this.defaultHighpTextureType = babylonjs_1.Engine.TEXTURETYPE_FLOAT;
  91419. this.shadowGeneratorBias = 0.001;
  91420. }
  91421. else {
  91422. this.defaultHighpTextureType = babylonjs_1.Engine.TEXTURETYPE_UNSIGNED_INT;
  91423. this.shadowGeneratorBias = 0.001;
  91424. }
  91425. this.defaultPipelineTextureType = this._hdrSupport ? this.defaultHighpTextureType : babylonjs_1.Engine.TEXTURETYPE_UNSIGNED_INT;
  91426. };
  91427. AbstractViewer.prototype.injectCustomShaders = function () {
  91428. var customShaders = this.configuration.customShaders;
  91429. if (!customShaders) {
  91430. return;
  91431. }
  91432. if (customShaders.shaders) {
  91433. Object.keys(customShaders.shaders).forEach(function (key) {
  91434. babylonjs_1.Effect.ShadersStore[key] = customShaders.shaders[key];
  91435. });
  91436. }
  91437. if (customShaders.includes) {
  91438. Object.keys(customShaders.includes).forEach(function (key) {
  91439. babylonjs_1.Effect.IncludesShadersStore[key] = customShaders.includes[key];
  91440. });
  91441. }
  91442. };
  91443. AbstractViewer.prototype.extendClassWithConfig = function (object, config) {
  91444. var _this = this;
  91445. if (!config)
  91446. return;
  91447. Object.keys(config).forEach(function (key) {
  91448. if (key in object && typeof object[key] !== 'function') {
  91449. if (typeof object[key] === 'object') {
  91450. _this.extendClassWithConfig(object[key], config[key]);
  91451. }
  91452. else {
  91453. if (config[key] !== undefined) {
  91454. object[key] = config[key];
  91455. }
  91456. }
  91457. }
  91458. });
  91459. };
  91460. AbstractViewer.prototype.setCameraBehavior = function (behaviorConfig, payload) {
  91461. var behavior;
  91462. var type = (typeof behaviorConfig !== "object") ? behaviorConfig : behaviorConfig.type;
  91463. var config = (typeof behaviorConfig === "object") ? behaviorConfig : {};
  91464. switch (type) {
  91465. case 0:
  91466. this.camera.useAutoRotationBehavior = true;
  91467. behavior = this.camera.autoRotationBehavior;
  91468. break;
  91469. case 1:
  91470. this.camera.useBouncingBehavior = true;
  91471. behavior = this.camera.bouncingBehavior;
  91472. break;
  91473. case 2:
  91474. this.camera.useFramingBehavior = true;
  91475. behavior = this.camera.framingBehavior;
  91476. break;
  91477. default:
  91478. behavior = null;
  91479. break;
  91480. }
  91481. if (behavior) {
  91482. if (typeof behaviorConfig === "object") {
  91483. this.extendClassWithConfig(behavior, behaviorConfig);
  91484. }
  91485. }
  91486. switch (type) {
  91487. case 0:
  91488. break;
  91489. case 1:
  91490. break;
  91491. case 2:
  91492. if (config.zoomOnBoundingInfo) {
  91493. var meshes = payload;
  91494. var bounding = meshes[0].getHierarchyBoundingVectors();
  91495. behavior.zoomOnBoundingInfo(bounding.min, bounding.max);
  91496. }
  91497. break;
  91498. }
  91499. };
  91500. return AbstractViewer;
  91501. }());
  91502. exports.AbstractViewer = AbstractViewer;
  91503. /***/ }),
  91504. /* 7 */
  91505. /***/ (function(module, exports) {
  91506. module.exports = "<viewer></viewer> <loading-screen></loading-screen> <overlay></overlay>";
  91507. /***/ }),
  91508. /* 8 */
  91509. /***/ (function(module, exports) {
  91510. module.exports = "<style>loading-screen{position:absolute;left:0;z-index:100;opacity:1;pointer-events:none;display:flex;justify-content:center;align-items:center;-webkit-transition:opacity 2s ease;-moz-transition:opacity 2s ease;transition:opacity 2s ease}img.loading-image{-webkit-animation:spin 2s linear infinite;animation:spin 2s linear infinite}@-webkit-keyframes spin{0%{-webkit-transform:rotate(0)}100%{-webkit-transform:rotate(360deg)}}@keyframes spin{0%{transform:rotate(0)}100%{transform:rotate(360deg)}}</style> <img class=loading-image src={{loadingImage}}>";
  91511. /***/ }),
  91512. /* 9 */
  91513. /***/ (function(module, exports) {
  91514. module.exports = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAHgAAAB4CAYAAAA5ZDbSAAAStUlEQVR42uyaA7TrShiFn23btm3btm3btm3btm372LWd9+318nSRNk2mtz3trLXX5PbmZOafPT9nxmq1VmuKFggEZs1ms0uVSqUj8vn8Q/SP5nK5lRpMjFYLh8NTZTKZhSBxi2KxeDlEPgh+BQVrhKbfwDNgZf45QZ2J0mrxeHxGtHJRCDoUQm+FpLd4joKc5aKJaDbDNzxuZT3yyLg1FqPVWPip0un0PBCxMUScD+6wtTJr+dz49hdsmh14nMiAKK0WiUSmgbjFC4XCYSz2VeB9/p2wyaxJK9EY93set+dxwhYr1QU9U7B4s4CNIfMM+pvAzyBm1VFjPl+D3cDELdacyVy4kMsdLBMrX0kf4beM1QCt9Ff7hY14nGRpWiIHBgYmU+BDwLMRi3EMJN4KpJUBa5g05OlHthORc4amIJXgZ30EPtXWyiHITFtN0JBziDz6DB6nHtYEI+i04BZQtJqwIfcAOBXM0hCEdXR0TM1k5ydV2Iv+CLTyeXbqgWeeeeY4DmnMOGjxTrw/aDVpkxtirW7Bos09xkns6+ublAlNA3Gr4S+3JCe4ksk9YOeWsdH4nkcTicTMZfLVuXjvrQYmKS54/EZaRReqaQvzz7FrZUYXBocz8BV2tWcQpEDR5eR7mPjGTmP98ssvEyra5N1CnZNZBL+Dp9mUF7A2a0W7u6dlE8/E82Ve0zVlCHz3HhFtnGAmfJWPC5Nm4pfSO6YLWIdVee/bOiFTiz1A/zL9xSpJqjLmpGHJZHJW9sDlvB/yul7gHlze4sY0Wr7UQLrwierA5fJf7eISrcaE9jHuh/TXsLk3j0aj81dbepRbUkXND40Gz7Hx1/SdaIRcz9BCxjDHh/A4nlMAxvjbKa0wZGaDKmeCO5nLAQoQOzs7fa86pVKpOfj2lSDsdc60N5Reat380uD5DfuyZ5KBwGzOc0jNiWCvet1QfONH+ushcz/M6AoqIUojapgWzgauBTEfiP6QzS+ix/E0qW6CB9MFCL7/G5Pd1DGd+uyz8SHmKB0eVPC9KAvwA3iK56Py6fTasVhseoMnVuMrs6h0seWelFnI9PqgIG+DTT2dSSsFsgw3+1z1ZpUsyyzOMrz7+QgH77+CB9gAp/HTWqFQaEqZMMOp4hKMd7hN1DcgxfMzLiLfsZFlMf7mScngA9Gfqp7w3XffuSe6WCi8Y9WufUYwsUKZY0EVVA5FoB3wR3MZNquTg3mxMNvSXw0+Bn1OrgBcid+ds9IxkHc51ljWJuNDAPsb67I/j5O5EfKaGkeyaSZ5hEktdEhxZrGs3GqMfxKL9aYCPJCtYqET4BIep6zQzI9N1L20rIA02geiO5HhYKunZ5JKdtgpNThSCzGpt+2z3YN0N8rkOaoW1K7Iicy9Gfs2HeuBrM+ytWuh3WiULvQxn2d90uh2OmUIkzpp8MZ+ayj4lcFvl6ZiznRxbRKTEe0j3JdizPkYb3fGvUim1n1FzptG4XP3rjQQ03tgWeW/oFBlPv8s8h6tG6GO1tBOKYoeKkFt4HmdhbI7V+F7Rk9P2traJlKRoZTP6x7WOeAl5tFZJyXOt3Xm/eabb47nwkWuCl4YHQf8nheh4BkgQpfWGrjxwdOAlEsNvR/sh6ldsJbXShlrXDbSyfV8tmznse/SL+ZCrnGUSvJ3X/6toUAaeowIVbXNa1rQ78IcfaCc1s+bkWj+ijKvCvjoj6Sf0Mm/5jOZbXinrc4PLdJQfbdSKzeuxkjFTSdJbs43qw2QtFNtX7mrTmr+c1+5OMIYz5VLRfj/2XnvlQa4ypMBCi6nMW7hwmFdI553VDXpB1wQHKyEYL0DZrHvLJ8LXnbjK2WmdCb9iMOF88+cK2D1d8MD96Kqm5+ZAlgHKBZ5Q8rHml3i6VRJGlfJDUI7Oo/4UAG7tdx4mPhlHSpy9Ub0oA4/qvGryrsVlOmuG/37IDniiZy4HOkPC9nsTm4miXlcrZIJ4X82gaA/2zvneNmdHoz/bNu2bdu2bdu2bdu2bdu2fbz3zfe9+eOizelMs93uns7n08uz0+48nUzwJPnFyQO2QAZi/IXNwgGTdXlTgFrfMnH4P9mRS6m18GgWFio/7xFVWiJAS59aHu5Tj7MMBQyxbIktFo1d0kS86mmMtZsmNGYOlknB6wkCTA8mWS5EtPz888+cxXc6vfkPmAqYcsAMxbFUmvZX77wzlhF82SqU4Pf++++PmjeqhBg4OS1QYCldAs4NTgvzrTzDWuxY435wwPYtMweMNXdk3NjzYd8GTHRWyhyE1xboxUzaS47JLieHwhmcvb0oYIvJz35Z0nP4o14YNxcEznenGVXKCTAi5VYCC3CnrXOS//dKJiP4j7entxCk/Bzet1rJAL463D9h42K9LSdmnUhE3yuWSNFA/f6WQsROh9HoyAHbRz1glptzh/JkKdqAqFfrjZD5RFrtZ+3glcNlvX1mCIA3GvYegQ54TM85Ltg9YsNNZu0KAXmz8uzgrtMss0/W7z8v64YdvKQHwElaL1xiK4dJFv2RvPYrURe513dynfYtgXD/8Kj7YFM5BoG6xEs2kyXvx8k6IYFzWcRxEjIKt0/5eezgqSzxqYVRahFsymc06jKHIaJLCLC94zr//XcBXno3F3I/IbOxYHkMalnk2SzfMp4t68yBSmP5lTVH6HUB9VxscXljxzGwLDXA7DjJJZ7F6znVmTRsb1/+qTwA828Z+FjbWvYrGQcDShICFPLw10C9wSHDbrchbBqArR3HZtk2cL779aOmAnJ/1gnZjSbAtv16ouWDVc7WHvIzM1iaeCsDjIYduIOvyPLl9wh4wF0Tio1NEVCt5lZxYY5arzpZcovV5Zq8rAALlfZdi9pDFC3whdktyw7ekLWPnZBzNDDm+xxi12FXjkbylizKkfLnxwZgTy5R4h18fy9YvB8yn4j0DTMFkUkBzaLN4hjxyJTAr2x5ogwxPp0sws4Q/nCypzxzmQG+1yHjxNCJjBik/PDFGWT+fV6pMMpEWNPSsDUBey2lv3xoBhHKDzAb5AS7XEaQRdPz66+/Tpp5dzwnpK/u7p7HI0QMouWDyDf6scQXpn+Nj5fCmZSl38G7eWV94meIKB3YDwf9s4HsSgC+JeYLy+e+I7nK1iZbB2Ap/radEQGbP3Dt3o4uwZvmK64JFQd6pxcgmgg+Qh8BmO87vaFg7Ro41zl5CppN2dNT+96w43wA1vn6EMDTegX6SYTLaVeS61r7KQu7Um52pifAHW1tJ7cawCiIkn4ygbGDbwqcb+nsaBrnAmJ0EHblwoaLzQNg5tu6BQH+2DERoSbYLBiUfZDmK2Yi3j7/BTRF9Ip9CWAUTfn/DwLm+o30o6BkNHKG0/KP2jq6t+Kl0cmXcwT4b1HaxuoLAFPawTEODCtmhKD0TBK7RI0/PM3b1dnZvSM7OSFNggdcIfaLy73nbH2AbaqOUpjbA+Z6MCoZTQt0pXqXNCfojATTas5IdgZn+mJ9ZAefYYRLlwt8We4MhBfwOm8bIBd4rbSzuo00CUvEOAAiZZKWazWAKfriFc4kyz9XicP+jS+6Vg34rCvAYoot0GoAW1Qd6EeBO3iXGJNop0GZGAT4iwPY4Iq1AMBSI3Mhr0C/YDVvzA6eNYngJl4tRLI5cF/KGfO9IyBjtRLAOIgsogME/ZD5BJNpggHmQykP959c0+WqGGAHrTdtOYDDqTofhSTJx1CaACiVmaEPMJU3wPo2Ht/qAFvsR0zQkNojYFGXGpY8BEEIb4ApJ9jqAFtUHanDOXkIN7ynq+uaaIDxtvTyJn6QlqcrovYOLwcA+a5yr7+bGWCtoUU9MbrQLO4U6AeDs/Ls4LMy3OBjkrttdmY+gHGZQnZvNoAV1E9kjc6jQFyGemI4OZYOtIHXjQZYPnxQxrfoLbp9ebQKAGBb5JcZYC3P39PzBlWFtIDZUHVusbBEIQRxrVc1Ql8EWIn8b9IEC8J+niq6pO6EBGfylGTCVFoy8IvejPqfI4aL0X53MwDM4mrVm508a1ozp3e9svBsQ/umt5LhB98oCuD29rfKCrD65R+mRieZE57Vc2uSXgvHO6CuGEfjO5izeQCGm/tv6EJop7SZPQPhnZ0d9xcNcK3/+EELr64FqJ5FVXEmAaoIeM3E8DO37OGgvVJ63hFgRP5ZRQGsvQavFY12JepcOye+TUoNbfn9BUDNGZE6x+OBHi+eymJrl94Aaz3mD4hty6Kt4pkQp1ki0xLxYS0B1ZU473DoH9mqAJMNoHlYmDPh/ly7itDMslP3o/J8LlDt9N1V/FvftQDA+NFlvnm1iq3LoPEmJSQE1MPpy1iTUTyvOmLwlmTl+cr4yuGhO+67777R/AH2HzgxKFkhgB4TkAzn1joQgmJhre+0edW4ohG+m/fhP/3008kSCAg7lwFgCIk07+LokuvdRhRW0w42l7n1GeLNzLLznn766THFszKjgPyTt+gRE2XDRgGMKEf8yqIeX8RONepmP6/tDsb27g72cpaHkMJdU+nPL8Bb5gkw/1YkwLhdaXujlerfb9BORbt/n3omBmsj/yDCgRcnABjs1o1565oJYJwPKn5P1CZa3Q3s+X8Jz2Jo975Dazz2hACjBn1XmQHWvhLzyoIeS3y7iJ1q+LZvo8oBzTfrCqZBJTkzBBit93F22QBWX/lSBN8bulO1kRat6SS3aLzi0LSTwV8KAYa+wFqQNPMQhWr9pNL2eQCmtyANl2lxC1GtwU2z3tR48cwR+tDwHX//PXNAnDmcbSkPl9iSXTTotQ0x+EwA8W6HQed4/fXXJ470iZ+tjSl/LkT82r0GLxSrZIGYeDFVeeXIO1S1+Hvr3cp8Wbk6E2K5OxsPODH+3lgfqzg/EKse3VuKtldvr0mTENI7I9Z5XMS3xp07jIp2/ucxiWehzm91EX4bDnBxncod7dXdJHth7BgRLEfJalQBxFsVsj7u7VxpsBF4Y0Q8u//vpgXYtldPoK1cjM0NKY+MQ/oRZwgTLlOUZj0KpkXom6U1JNuaHWC1Vy+CXBdjr2rA/2BAlaun0CBDgEiZEgUiVHRQQcDol7tXWQFWe/VW+eMaFKAJPdrQRQTUrRDjkY2hvyq8NT5Bcs0+vCThv4c0amKekqTZtv377/Up93m3gabNk/Qb/O6778aNad9L02iZ4344bjnTXj50BS9gRx4u5XHvShFFU6SxHeQztw36JVLm4R6PNMBePepvsTtjzlWZY0FKAnva3dQQbQjAGN7yhu+SIloBcYyUlnej0kUzC5kMznRR9iolo2JEIbxo+iLXy0OGS3WIRo201Ayp1PIeIKa0vQO48eXBv2kQwCza/+3V7nh7dXL57E4yhw/nymZ5LjZE2YZU67lHF/LWNBebiMFZ8TYVBbDaq8/J7xvHdOZGwULRkjnuqHdzavQbuQ987JU0F7iBwwBGz7VT08jaND7my9QLYOxVje0eGGOv0otJRPeisCkwkQoIRKADHGk/a4kAZtRkiEZ5jGEbbk32QIoWfUZsa3WaZckf5yD4EXGuTq89nb50az5t94G6VV6khQs3h7zSUMnAs6q7S87xRoiiBH/2UYF+YMjra8ifR40IjeLc30vmeAlxXoAn7AV6L9r9K0oOcELVnhUD51k5w1mForNtjB8YjV4WeWOZ4yG52gryhF0K30uPraYciNZT076gXFPnSWfVanxvYK/WpElHxMs3IpXlWOgi4sQ8L1IBp4laFc0/iO/WZKR84c9EJE8WCrDaqxfI2z976FlFzhWfG4B7VSvIvj5ZpNaMTbpbbda/fLknDDv09Sz2p9JsbqPYKRptRCLd1Dhj5Pe3CgL1P7ke1V5UfL/WHXiy5HrFWAyAG763EGXwfYVmhANDbd6Ogsokfaahw6k0h7hvDNEQ58KZYcQ5r7HFbbBz/wbO+YJZkavri9o3hyzAyobZwULtmyPgMR9lhWx71d0Z8Q7FauTlnVB3azWIGxux4G4KoWYNcGiX0n1ELr7CZwssRXgpzAp1vVYjodv39cYCdspILRaGjUsf/gHJaAWdrW+QG0Rv/QrFbPHSBywngFzzDeiEkB2zovybktEch90C9wcI/zQjSelhUQ3DJTkpdrCxwD+IJroCvCdPXnMAg2PLfDU6qoF/eX6TZVl8Lclzax0dsyrVqBpO4pqAQHcDecz3EvxQwkI16kGkp9m0v2ljxoU/UGfElBUCxYCMK/HKejMj5LpRriWVx1yNIgfmhyz+83U4WzFvDsAZUa1yYwfcLAh4P3kwI+S6RMybBcrHjKg8XQshTiOZESR+bS+prONUK1niITtvezTcAGYEid2zasSpGUY1ekSztpgRcpHpsK5co1er1YRDu6DelsCMOL5d6DmVo78FBgRzcRy+pgTzFeiqVq1Ki43KZo0b/wP23paVqC/D3gAAAABJRU5ErkJggg=="
  91515. /***/ }),
  91516. /* 10 */
  91517. /***/ (function(module, exports) {
  91518. module.exports = "<style>viewer{position:relative;overflow:hidden;flex:1;z-index:1;justify-content:center;align-items:center;width:100%;height:100%}.babylonjs-canvas{flex:1;width:100%;height:100%;touch-action:none}</style> <canvas class=babylonjs-canvas id={{canvasId}}> </canvas> <nav-bar></nav-bar>";
  91519. /***/ }),
  91520. /* 11 */
  91521. /***/ (function(module, exports) {
  91522. module.exports = "<style>overlay{position:absolute;z-index:99;opacity:0;display:flex;justify-content:center;align-items:center;-webkit-transition:opacity 1s ease;-moz-transition:opacity 1s ease;transition:opacity 1s ease}.overlay-item{width:100%;height:100%;display:none;align-items:center;justify-content:center;background-color:rgba(121,121,121,.3)}error.overlay-item{background-color:rgba(121,121,121,1)}div#close-button{position:absolute;top:10px;right:10px;width:30px;height:30px;cursor:pointer}div#close-button img{width:100%}</style> <div id=close-button> <img src={{closeImage}} alt={{closeText}}> </div> <help class=overlay-item></help> <error class=overlay-item></error> <share class=overlay-item></share>";
  91523. /***/ }),
  91524. /* 12 */
  91525. /***/ (function(module, exports) {
  91526. module.exports = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAQAAAD9CzEMAAAAt0lEQVR42u2WAQbDQBBFQ9IbRtDcrrqK3LBbXrEH6OuHEPMBjPd2xHyZKtdNpcLMg11Pr7y4/YdvwIdd4jtw4BU0Rjrbz9mNzkjzgpU3wNhCvH5M3i1fKzzeK3K8V+R4r8jxTpHjlULhc0WOd8fU6e4I8y3y13tFjHel4GswwAvFSR/ZN6Zv2gjvmzbGhwqPzxUenys83is8Pld4vFac/9sy8/SVNrbgYJl8WGhsvkpoA1+pVK6ZLyLNXm2txsT5AAAAAElFTkSuQmCC"
  91527. /***/ }),
  91528. /* 13 */
  91529. /***/ (function(module, exports) {
  91530. module.exports = "Error loading the model";
  91531. /***/ }),
  91532. /* 14 */
  91533. /***/ (function(module, exports, __webpack_require__) {
  91534. (function (global, factory) {
  91535. true ? module.exports = factory() :
  91536. typeof define === 'function' && define.amd ? define(factory) :
  91537. (global.deepmerge = factory());
  91538. }(this, (function () { 'use strict';
  91539. var isMergeableObject = function isMergeableObject(value) {
  91540. return isNonNullObject(value)
  91541. && !isSpecial(value)
  91542. };
  91543. function isNonNullObject(value) {
  91544. return !!value && typeof value === 'object'
  91545. }
  91546. function isSpecial(value) {
  91547. var stringValue = Object.prototype.toString.call(value);
  91548. return stringValue === '[object RegExp]'
  91549. || stringValue === '[object Date]'
  91550. || isReactElement(value)
  91551. }
  91552. // see https://github.com/facebook/react/blob/b5ac963fb791d1298e7f396236383bc955f916c1/src/isomorphic/classic/element/ReactElement.js#L21-L25
  91553. var canUseSymbol = typeof Symbol === 'function' && Symbol.for;
  91554. var REACT_ELEMENT_TYPE = canUseSymbol ? Symbol.for('react.element') : 0xeac7;
  91555. function isReactElement(value) {
  91556. return value.$$typeof === REACT_ELEMENT_TYPE
  91557. }
  91558. function emptyTarget(val) {
  91559. return Array.isArray(val) ? [] : {}
  91560. }
  91561. function cloneUnlessOtherwiseSpecified(value, optionsArgument) {
  91562. var clone = !optionsArgument || optionsArgument.clone !== false;
  91563. return (clone && isMergeableObject(value))
  91564. ? deepmerge(emptyTarget(value), value, optionsArgument)
  91565. : value
  91566. }
  91567. function defaultArrayMerge(target, source, optionsArgument) {
  91568. return target.concat(source).map(function(element) {
  91569. return cloneUnlessOtherwiseSpecified(element, optionsArgument)
  91570. })
  91571. }
  91572. function mergeObject(target, source, optionsArgument) {
  91573. var destination = {};
  91574. if (isMergeableObject(target)) {
  91575. Object.keys(target).forEach(function(key) {
  91576. destination[key] = cloneUnlessOtherwiseSpecified(target[key], optionsArgument);
  91577. });
  91578. }
  91579. Object.keys(source).forEach(function(key) {
  91580. if (!isMergeableObject(source[key]) || !target[key]) {
  91581. destination[key] = cloneUnlessOtherwiseSpecified(source[key], optionsArgument);
  91582. } else {
  91583. destination[key] = deepmerge(target[key], source[key], optionsArgument);
  91584. }
  91585. });
  91586. return destination
  91587. }
  91588. function deepmerge(target, source, optionsArgument) {
  91589. var sourceIsArray = Array.isArray(source);
  91590. var targetIsArray = Array.isArray(target);
  91591. var options = optionsArgument || { arrayMerge: defaultArrayMerge };
  91592. var sourceAndTargetTypesMatch = sourceIsArray === targetIsArray;
  91593. if (!sourceAndTargetTypesMatch) {
  91594. return cloneUnlessOtherwiseSpecified(source, optionsArgument)
  91595. } else if (sourceIsArray) {
  91596. var arrayMerge = options.arrayMerge || defaultArrayMerge;
  91597. return arrayMerge(target, source, optionsArgument)
  91598. } else {
  91599. return mergeObject(target, source, optionsArgument)
  91600. }
  91601. }
  91602. deepmerge.all = function deepmergeAll(array, optionsArgument) {
  91603. if (!Array.isArray(array)) {
  91604. throw new Error('first argument should be an array')
  91605. }
  91606. return array.reduce(function(prev, next) {
  91607. return deepmerge(prev, next, optionsArgument)
  91608. }, {})
  91609. };
  91610. var deepmerge_1 = deepmerge;
  91611. return deepmerge_1;
  91612. })));
  91613. /***/ }),
  91614. /* 15 */
  91615. /***/ (function(module, exports, __webpack_require__) {
  91616. module.exports = __webpack_require__(16);
  91617. /***/ }),
  91618. /* 16 */
  91619. /***/ (function(module, exports, __webpack_require__) {
  91620. "use strict";
  91621. Object.defineProperty(exports, "__esModule", { value: true });
  91622. var mappers_1 = __webpack_require__(1);
  91623. exports.mapperManager = mappers_1.mapperManager;
  91624. var viewerManager_1 = __webpack_require__(4);
  91625. exports.viewerManager = viewerManager_1.viewerManager;
  91626. var defaultViewer_1 = __webpack_require__(5);
  91627. exports.DefaultViewer = defaultViewer_1.DefaultViewer;
  91628. var viewer_1 = __webpack_require__(6);
  91629. exports.AbstractViewer = viewer_1.AbstractViewer;
  91630. __webpack_require__(0);
  91631. __webpack_require__(30);
  91632. __webpack_require__(31);
  91633. var babylonjs_1 = __webpack_require__(0);
  91634. var initializer_1 = __webpack_require__(32);
  91635. exports.InitTags = initializer_1.InitTags;
  91636. babylonjs_1.PromisePolyfill.Apply();
  91637. exports.disableInit = false;
  91638. document.addEventListener("DOMContentLoaded", function (event) {
  91639. if (exports.disableInit)
  91640. return;
  91641. initializer_1.InitTags();
  91642. });
  91643. /***/ }),
  91644. /* 17 */
  91645. /***/ (function(module, exports) {
  91646. module.exports = cannon;
  91647. /***/ }),
  91648. /* 18 */
  91649. /***/ (function(module, exports, __webpack_require__) {
  91650. /**
  91651. * from OimoPhysics DEV 1.1.0a AS3
  91652. * @author Saharan / http://el-ement.com/
  91653. *
  91654. * to Oimo.js 2015 JAVASCRIPT
  91655. * @author LoTh / http://lo-th.github.io/labs/
  91656. */
  91657. var OIMO = {
  91658. REVISION: "1.2",
  91659. // Global identification of next shape.
  91660. // This will be incremented every time a shape is created.
  91661. nextID: 0,
  91662. proxyID: 0,
  91663. // BroadPhase
  91664. BR_NULL: 0,
  91665. BR_BRUTE_FORCE: 1,
  91666. BR_SWEEP_AND_PRUNE: 2,
  91667. BR_BOUNDING_VOLUME_TREE: 3,
  91668. // body type
  91669. BODY_NULL: 0,
  91670. BODY_DYNAMIC: 1,
  91671. BODY_STATIC: 2,
  91672. // shape type
  91673. SHAPE_NULL: 0,
  91674. SHAPE_SPHERE: 1,
  91675. SHAPE_BOX: 2,
  91676. SHAPE_CYLINDER: 3,
  91677. SHAPE_TETRA: 4,
  91678. // joint type
  91679. JOINT_NULL: 0,
  91680. JOINT_DISTANCE: 1,
  91681. JOINT_BALL_AND_SOCKET: 2,
  91682. JOINT_HINGE: 3,
  91683. JOINT_WHEEL: 4,
  91684. JOINT_SLIDER: 5,
  91685. JOINT_PRISMATIC: 6,
  91686. // this world scale defaut is 0.1 to 10 meters max for dynamique body
  91687. // scale all by 100 so object is between 10 to 10000 three unit.
  91688. WORLD_SCALE: 100,
  91689. INV_SCALE: 0.01,
  91690. // AABB aproximation
  91691. AABB_PROX: 0.005,
  91692. // Math function
  91693. sqrt: Math.sqrt,
  91694. abs: Math.abs,
  91695. floor: Math.floor,
  91696. cos: Math.cos,
  91697. sin: Math.sin,
  91698. acos: Math.acos,
  91699. asin: Math.asin,
  91700. atan2: Math.atan2,
  91701. round: Math.round,
  91702. pow: Math.pow,
  91703. max: Math.max,
  91704. min: Math.min,
  91705. random: Math.random,
  91706. lerp: function (a, b, percent) { return a + (b - a) * percent; },
  91707. rand: function (a, b) { return OIMO.lerp(a, b, OIMO.random()); },
  91708. randInt: function (a, b, n) { return OIMO.lerp(a, b, OIMO.random()).toFixed(n || 0) * 1; },
  91709. int: function (x) { return ~~x; },
  91710. fix: function (x, n) { return x.toFixed(n || 3, 10); },
  91711. clamp: function (value, min, max) { return OIMO.max(min, OIMO.min(max, value)); },
  91712. degtorad: 0.0174532925199432957,
  91713. radtodeg: 57.295779513082320876,
  91714. PI: 3.141592653589793,
  91715. TwoPI: 6.283185307179586,
  91716. PI90: 1.570796326794896,
  91717. PI270: 4.712388980384689,
  91718. CustomError: null,
  91719. Error: function (Class, Msg) {
  91720. if (OIMO.CustomError == null) console.error(Class, Msg);
  91721. else OIMO.CustomError.innerHTML += Class + " - " + Msg + '<br>';
  91722. }
  91723. };
  91724. var OIMO_ARRAY_TYPE;
  91725. if (!OIMO_ARRAY_TYPE) { OIMO_ARRAY_TYPE = typeof Float32Array !== 'undefined' ? Float32Array : Array; }
  91726. try {
  91727. (function (w) {
  91728. var perfNow;
  91729. var perfNowNames = ['now', 'webkitNow', 'msNow', 'mozNow'];
  91730. if (!!w['performance']) for (var i = 0; i < perfNowNames.length; ++i) {
  91731. var n = perfNowNames[i];
  91732. if (!!w['performance'][n]) {
  91733. perfNow = function () { return w['performance'][n]() };
  91734. break;
  91735. }
  91736. }
  91737. if (!perfNow) perfNow = Date.now;
  91738. //w.perfNow = perfNow;
  91739. OIMO.now = perfNow;
  91740. })(window);
  91741. } catch (e) { OIMO.now = function () { return 0; }; }
  91742. /**
  91743. * The class of physical computing world.
  91744. * You must be added to the world physical all computing objects
  91745. * @author saharan
  91746. * @author lo-th
  91747. */
  91748. OIMO.World = function (TimeStep, BroadPhaseType, Iterations, NoStat) {
  91749. // The time between each step
  91750. this.timeStep = TimeStep || 0.01666; // 1/60;
  91751. // The number of iterations for constraint solvers.
  91752. this.numIterations = Iterations || 8;
  91753. // It is a wide-area collision judgment that is used in order to reduce as much as possible a detailed collision judgment.
  91754. switch (BroadPhaseType || 2) {
  91755. case 1: this.broadPhase = new OIMO.BruteForceBroadPhase(); break;
  91756. case 2: default: this.broadPhase = new OIMO.SAPBroadPhase(); break;
  91757. case 3: this.broadPhase = new OIMO.DBVTBroadPhase(); break;
  91758. }
  91759. // This is the detailed information of the performance.
  91760. this.performance = null;
  91761. this.isNoStat = NoStat || false;
  91762. if (!this.isNoStat) this.performance = new OIMO.Performance(this);
  91763. // Whether the constraints randomizer is enabled or not.
  91764. this.enableRandomizer = true;
  91765. // The rigid body list
  91766. this.rigidBodies = null;
  91767. // number of rigid body
  91768. this.numRigidBodies = 0;
  91769. // The contact list
  91770. this.contacts = null;
  91771. this.unusedContacts = null;
  91772. // The number of contact
  91773. this.numContacts = 0;
  91774. // The number of contact points
  91775. this.numContactPoints = 0;
  91776. // The joint list
  91777. this.joints = null;
  91778. // The number of joints.
  91779. this.numJoints = 0;
  91780. // The number of simulation islands.
  91781. this.numIslands = 0;
  91782. // The gravity in the world.
  91783. this.gravity = new OIMO.Vec3(0, -9.80665, 0);
  91784. var numShapeTypes = 5;//4;//3;
  91785. this.detectors = [];
  91786. this.detectors.length = numShapeTypes;
  91787. var i = numShapeTypes;
  91788. while (i--) {
  91789. this.detectors[i] = [];
  91790. this.detectors[i].length = numShapeTypes;
  91791. }
  91792. this.detectors[OIMO.SHAPE_SPHERE][OIMO.SHAPE_SPHERE] = new OIMO.SphereSphereCollisionDetector();
  91793. this.detectors[OIMO.SHAPE_SPHERE][OIMO.SHAPE_BOX] = new OIMO.SphereBoxCollisionDetector(false);
  91794. this.detectors[OIMO.SHAPE_BOX][OIMO.SHAPE_SPHERE] = new OIMO.SphereBoxCollisionDetector(true);
  91795. this.detectors[OIMO.SHAPE_BOX][OIMO.SHAPE_BOX] = new OIMO.BoxBoxCollisionDetector();
  91796. // CYLINDER add
  91797. this.detectors[OIMO.SHAPE_CYLINDER][OIMO.SHAPE_CYLINDER] = new OIMO.CylinderCylinderCollisionDetector();
  91798. this.detectors[OIMO.SHAPE_CYLINDER][OIMO.SHAPE_BOX] = new OIMO.BoxCylinderCollisionDetector(true);
  91799. this.detectors[OIMO.SHAPE_BOX][OIMO.SHAPE_CYLINDER] = new OIMO.BoxCylinderCollisionDetector(false);
  91800. this.detectors[OIMO.SHAPE_CYLINDER][OIMO.SHAPE_SPHERE] = new OIMO.SphereCylinderCollisionDetector(true);
  91801. this.detectors[OIMO.SHAPE_SPHERE][OIMO.SHAPE_CYLINDER] = new OIMO.SphereCylinderCollisionDetector(false);
  91802. // TETRA add
  91803. this.detectors[OIMO.SHAPE_TETRA][OIMO.SHAPE_TETRA] = new OIMO.TetraTetraCollisionDetector();
  91804. this.randX = 65535;
  91805. this.randA = 98765;
  91806. this.randB = 123456789;
  91807. //this.maxIslandRigidBodies = 64;
  91808. this.islandRigidBodies = [];
  91809. //this.islandRigidBodies.length = this.maxIslandRigidBodies;
  91810. this.islandStack = [];
  91811. //this.islandStack.length = this.maxIslandRigidBodies;
  91812. //this.maxIslandConstraints = 128;
  91813. this.islandConstraints = [];
  91814. //this.islandConstraints.length = this.maxIslandConstraints;
  91815. };
  91816. OIMO.World.prototype = {
  91817. constructor: OIMO.World,
  91818. /**
  91819. * Reset the randomizer and remove all rigid bodies, shapes, joints and any object from the world.
  91820. */
  91821. clear: function () {
  91822. this.randX = 65535;
  91823. while (this.joints !== null) {
  91824. this.removeJoint(this.joints);
  91825. }
  91826. while (this.contacts !== null) {
  91827. this.removeContact(this.contacts);
  91828. }
  91829. while (this.rigidBodies !== null) {
  91830. this.removeRigidBody(this.rigidBodies);
  91831. }
  91832. OIMO.nextID = 0;
  91833. OIMO.proxyID = 0;
  91834. },
  91835. /**
  91836. * I'll add a rigid body to the world.
  91837. * Rigid body that has been added will be the operands of each step.
  91838. * @param rigidBody Rigid body that you want to add
  91839. */
  91840. addRigidBody: function (rigidBody) {
  91841. if (rigidBody.parent) {
  91842. OIMO.Error("World", "It is not possible to be added to more than one world one of the rigid body");
  91843. }
  91844. rigidBody.parent = this;
  91845. rigidBody.awake();
  91846. for (var shape = rigidBody.shapes; shape !== null; shape = shape.next) {
  91847. this.addShape(shape);
  91848. }
  91849. if (this.rigidBodies !== null) (this.rigidBodies.prev = rigidBody).next = this.rigidBodies;
  91850. this.rigidBodies = rigidBody;
  91851. this.numRigidBodies++;
  91852. },
  91853. /**
  91854. * I will remove the rigid body from the world.
  91855. * Rigid body that has been deleted is excluded from the calculation on a step-by-step basis.
  91856. * @param rigidBody Rigid body to be removed
  91857. */
  91858. removeRigidBody: function (rigidBody) {
  91859. var remove = rigidBody;
  91860. if (remove.parent !== this) return;
  91861. remove.awake();
  91862. var js = remove.jointLink;
  91863. while (js != null) {
  91864. var joint = js.joint;
  91865. js = js.next;
  91866. this.removeJoint(joint);
  91867. }
  91868. for (var shape = rigidBody.shapes; shape !== null; shape = shape.next) {
  91869. this.removeShape(shape);
  91870. }
  91871. var prev = remove.prev;
  91872. var next = remove.next;
  91873. if (prev !== null) prev.next = next;
  91874. if (next !== null) next.prev = prev;
  91875. if (this.rigidBodies == remove) this.rigidBodies = next;
  91876. remove.prev = null;
  91877. remove.next = null;
  91878. remove.parent = null;
  91879. this.numRigidBodies--;
  91880. },
  91881. getByName: function (name) {
  91882. var result = null;
  91883. var body = this.rigidBodies;
  91884. while (body !== null) {
  91885. if (body.name !== " " && body.name === name) result = body;
  91886. body = body.next;
  91887. }
  91888. var joint = this.joints;
  91889. while (joint !== null) {
  91890. if (joint.name !== "" && joint.name === name) result = joint;
  91891. joint = joint.next;
  91892. }
  91893. return result;
  91894. },
  91895. /**
  91896. * I'll add a shape to the world..
  91897. * Add to the rigid world, and if you add a shape to a rigid body that has been added to the world,
  91898. * Shape will be added to the world automatically, please do not call from outside this method.
  91899. * @param shape Shape you want to add
  91900. */
  91901. addShape: function (shape) {
  91902. if (!shape.parent || !shape.parent.parent) {
  91903. OIMO.Error("World", "It is not possible to be added alone to shape world");
  91904. }
  91905. shape.proxy = this.broadPhase.createProxy(shape);
  91906. shape.updateProxy();
  91907. this.broadPhase.addProxy(shape.proxy);
  91908. },
  91909. /**
  91910. * I will remove the shape from the world.
  91911. * Add to the rigid world, and if you add a shape to a rigid body that has been added to the world,
  91912. * Shape will be added to the world automatically, please do not call from outside this method.
  91913. * @param shape Shape you want to delete
  91914. */
  91915. removeShape: function (shape) {
  91916. this.broadPhase.removeProxy(shape.proxy);
  91917. shape.proxy = null;
  91918. },
  91919. /**
  91920. * I'll add a joint to the world.
  91921. * Joint that has been added will be the operands of each step.
  91922. * @param shape Joint to be added
  91923. */
  91924. addJoint: function (joint) {
  91925. if (joint.parent) {
  91926. OIMO.Error("World", "It is not possible to be added to more than one world one of the joint");
  91927. }
  91928. if (this.joints != null) (this.joints.prev = joint).next = this.joints;
  91929. this.joints = joint;
  91930. joint.parent = this;
  91931. this.numJoints++;
  91932. joint.awake();
  91933. joint.attach();
  91934. },
  91935. /**
  91936. * I will remove the joint from the world.
  91937. * Joint that has been added will be the operands of each step.
  91938. * @param shape Joint to be deleted
  91939. */
  91940. removeJoint: function (joint) {
  91941. var remove = joint;
  91942. var prev = remove.prev;
  91943. var next = remove.next;
  91944. if (prev !== null) prev.next = next;
  91945. if (next !== null) next.prev = prev;
  91946. if (this.joints == remove) this.joints = next;
  91947. remove.prev = null;
  91948. remove.next = null;
  91949. this.numJoints--;
  91950. remove.awake();
  91951. remove.detach();
  91952. remove.parent = null;
  91953. },
  91954. worldscale: function (scale) {
  91955. OIMO.WORLD_SCALE = scale || 100;
  91956. OIMO.INV_SCALE = 1 / OIMO.WORLD_SCALE;
  91957. },
  91958. addContact: function (s1, s2) {
  91959. var newContact;
  91960. if (this.unusedContacts !== null) {
  91961. newContact = this.unusedContacts;
  91962. this.unusedContacts = this.unusedContacts.next;
  91963. } else {
  91964. newContact = new OIMO.Contact();
  91965. }
  91966. newContact.attach(s1, s2);
  91967. newContact.detector = this.detectors[s1.type][s2.type];
  91968. if (this.contacts) (this.contacts.prev = newContact).next = this.contacts;
  91969. this.contacts = newContact;
  91970. this.numContacts++;
  91971. },
  91972. removeContact: function (contact) {
  91973. var prev = contact.prev;
  91974. var next = contact.next;
  91975. if (next) next.prev = prev;
  91976. if (prev) prev.next = next;
  91977. if (this.contacts == contact) this.contacts = next;
  91978. contact.prev = null;
  91979. contact.next = null;
  91980. contact.detach();
  91981. contact.next = this.unusedContacts;
  91982. this.unusedContacts = contact;
  91983. this.numContacts--;
  91984. },
  91985. checkContact: function (name1, name2) {
  91986. var n1, n2;
  91987. var contact = this.contacts;
  91988. while (contact !== null) {
  91989. n1 = contact.body1.name || ' ';
  91990. n2 = contact.body2.name || ' ';
  91991. if ((n1 == name1 && n2 == name2) || (n2 == name1 && n1 == name2)) { if (contact.touching) return true; else return false; }
  91992. else contact = contact.next;
  91993. }
  91994. return false;
  91995. },
  91996. callSleep: function (body) {
  91997. if (!body.allowSleep) return false;
  91998. if (body.linearVelocity.lengthSq() > 0.04) return false;
  91999. if (body.angularVelocity.lengthSq() > 0.25) return false;
  92000. return true;
  92001. },
  92002. /**
  92003. * I will proceed only time step seconds time of World.
  92004. */
  92005. step: function () {
  92006. var time0, time1, time2, time3;
  92007. var stat = !this.isNoStat ? true : false;
  92008. if (stat) time0 = OIMO.now();
  92009. var body = this.rigidBodies;
  92010. while (body !== null) {
  92011. body.addedToIsland = false;
  92012. if (body.sleeping) {
  92013. if (
  92014. body.linearVelocity.testZero() ||
  92015. body.angularVelocity.testZero() ||
  92016. body.position.testDiff(body.sleepPosition) ||
  92017. body.orientation.testDiff(body.sleepOrientation)
  92018. ) body.awake(); // awake the body
  92019. }
  92020. body = body.next;
  92021. }
  92022. //------------------------------------------------------
  92023. // UPDATE CONTACT
  92024. //------------------------------------------------------
  92025. // broad phase
  92026. if (stat) time1 = OIMO.now();
  92027. this.broadPhase.detectPairs();
  92028. var pairs = this.broadPhase.pairs;
  92029. var i = this.broadPhase.numPairs;
  92030. //do{
  92031. while (i--) {
  92032. //for(var i=0, l=numPairs; i<l; i++){
  92033. var pair = pairs[i];
  92034. var s1;
  92035. var s2;
  92036. if (pair.shape1.id < pair.shape2.id) {
  92037. s1 = pair.shape1;
  92038. s2 = pair.shape2;
  92039. } else {
  92040. s1 = pair.shape2;
  92041. s2 = pair.shape1;
  92042. }
  92043. var link;
  92044. if (s1.numContacts < s2.numContacts) link = s1.contactLink;
  92045. else link = s2.contactLink;
  92046. var exists = false;
  92047. while (link) {
  92048. var contact = link.contact;
  92049. if (contact.shape1 == s1 && contact.shape2 == s2) {
  92050. contact.persisting = true;
  92051. exists = true;// contact already exists
  92052. break;
  92053. }
  92054. link = link.next;
  92055. }
  92056. if (!exists) {
  92057. this.addContact(s1, s2);
  92058. }
  92059. }// while(i-- >0);
  92060. if (stat) {
  92061. time2 = OIMO.now();
  92062. this.performance.broadPhaseTime = time2 - time1;
  92063. }
  92064. // update & narrow phase
  92065. this.numContactPoints = 0;
  92066. contact = this.contacts;
  92067. while (contact !== null) {
  92068. if (!contact.persisting) {
  92069. if (contact.shape1.aabb.intersectTest(contact.shape2.aabb)) {
  92070. /*var aabb1=contact.shape1.aabb;
  92071. var aabb2=contact.shape2.aabb;
  92072. if(
  92073. aabb1.minX>aabb2.maxX || aabb1.maxX<aabb2.minX ||
  92074. aabb1.minY>aabb2.maxY || aabb1.maxY<aabb2.minY ||
  92075. aabb1.minZ>aabb2.maxZ || aabb1.maxZ<aabb2.minZ
  92076. ){*/
  92077. var next = contact.next;
  92078. this.removeContact(contact);
  92079. contact = next;
  92080. continue;
  92081. }
  92082. }
  92083. var b1 = contact.body1;
  92084. var b2 = contact.body2;
  92085. if (b1.isDynamic && !b1.sleeping || b2.isDynamic && !b2.sleeping) {
  92086. contact.updateManifold();
  92087. }
  92088. this.numContactPoints += contact.manifold.numPoints;
  92089. contact.persisting = false;
  92090. contact.constraint.addedToIsland = false;
  92091. contact = contact.next;
  92092. }
  92093. if (stat) {
  92094. time3 = OIMO.now();
  92095. this.performance.narrowPhaseTime = time3 - time2;
  92096. }
  92097. //------------------------------------------------------
  92098. // SOLVE ISLANDS
  92099. //------------------------------------------------------
  92100. var invTimeStep = 1 / this.timeStep;
  92101. //var body;
  92102. var joint;
  92103. var constraint;
  92104. //var num;
  92105. for (joint = this.joints; joint !== null; joint = joint.next) {
  92106. joint.addedToIsland = false;
  92107. }
  92108. // clear old island array
  92109. this.islandRigidBodies = [];
  92110. this.islandConstraints = [];
  92111. this.islandStack = [];
  92112. // expand island buffers
  92113. /*if(this.maxIslandRigidBodies<this.numRigidBodies){
  92114. this.maxIslandRigidBodies=this.numRigidBodies<<1;
  92115. //this.maxIslandRigidBodies=this.numRigidBodies*2;
  92116. this.islandRigidBodies=[];
  92117. this.islandStack=[];
  92118. this.islandRigidBodies.length = this.maxIslandRigidBodies;
  92119. this.islandStack.length = this.maxIslandRigidBodies;
  92120. }
  92121. var numConstraints=this.numJoints+this.numContacts;
  92122. if(this.maxIslandConstraints<numConstraints){
  92123. this.maxIslandConstraints=numConstraints<<1;
  92124. //this.maxIslandConstraints=numConstraints*2;
  92125. this.islandConstraints=[];
  92126. this.islandConstraints.length = this.maxIslandConstraints;
  92127. }*/
  92128. time1 = OIMO.now();
  92129. this.numIslands = 0;
  92130. // build and solve simulation islands
  92131. for (var base = this.rigidBodies; base !== null; base = base.next) {
  92132. if (base.addedToIsland || base.isStatic || base.sleeping) continue;// ignore
  92133. if (base.isLonely()) {// update single body
  92134. if (base.isDynamic) {
  92135. base.linearVelocity.addTime(this.gravity, this.timeStep);
  92136. /*base.linearVelocity.x+=this.gravity.x*this.timeStep;
  92137. base.linearVelocity.y+=this.gravity.y*this.timeStep;
  92138. base.linearVelocity.z+=this.gravity.z*this.timeStep;*/
  92139. }
  92140. if (this.callSleep(base)) {
  92141. base.sleepTime += this.timeStep;
  92142. if (base.sleepTime > 0.5) base.sleep();
  92143. else base.updatePosition(this.timeStep);
  92144. } else {
  92145. base.sleepTime = 0;
  92146. base.updatePosition(this.timeStep);
  92147. }
  92148. this.numIslands++;
  92149. continue;
  92150. }
  92151. var islandNumRigidBodies = 0;
  92152. var islandNumConstraints = 0;
  92153. var stackCount = 1;
  92154. // add rigid body to stack
  92155. this.islandStack[0] = base;
  92156. base.addedToIsland = true;
  92157. // build an island
  92158. do {
  92159. // get rigid body from stack
  92160. body = this.islandStack[--stackCount];
  92161. this.islandStack[stackCount] = null;
  92162. body.sleeping = false;
  92163. // add rigid body to the island
  92164. this.islandRigidBodies[islandNumRigidBodies++] = body;
  92165. if (body.isStatic) continue;
  92166. // search connections
  92167. for (var cs = body.contactLink; cs !== null; cs = cs.next) {
  92168. var contact = cs.contact;
  92169. constraint = contact.constraint;
  92170. if (constraint.addedToIsland || !contact.touching) continue;// ignore
  92171. // add constraint to the island
  92172. this.islandConstraints[islandNumConstraints++] = constraint;
  92173. constraint.addedToIsland = true;
  92174. var next = cs.body;
  92175. if (next.addedToIsland) continue;
  92176. // add rigid body to stack
  92177. this.islandStack[stackCount++] = next;
  92178. next.addedToIsland = true;
  92179. }
  92180. for (var js = body.jointLink; js !== null; js = js.next) {
  92181. constraint = js.joint;
  92182. if (constraint.addedToIsland) continue;// ignore
  92183. // add constraint to the island
  92184. this.islandConstraints[islandNumConstraints++] = constraint;
  92185. constraint.addedToIsland = true;
  92186. next = js.body;
  92187. if (next.addedToIsland || !next.isDynamic) continue;
  92188. // add rigid body to stack
  92189. this.islandStack[stackCount++] = next;
  92190. next.addedToIsland = true;
  92191. }
  92192. } while (stackCount != 0);
  92193. // update velocities
  92194. var gVel = new OIMO.Vec3().addTime(this.gravity, this.timeStep);
  92195. /*var gx=this.gravity.x*this.timeStep;
  92196. var gy=this.gravity.y*this.timeStep;
  92197. var gz=this.gravity.z*this.timeStep;*/
  92198. var j = islandNumRigidBodies;
  92199. while (j--) {
  92200. //or(var j=0, l=islandNumRigidBodies; j<l; j++){
  92201. body = this.islandRigidBodies[j];
  92202. if (body.isDynamic) {
  92203. body.linearVelocity.addEqual(gVel);
  92204. /*body.linearVelocity.x+=gx;
  92205. body.linearVelocity.y+=gy;
  92206. body.linearVelocity.z+=gz;*/
  92207. }
  92208. }
  92209. // randomizing order
  92210. if (this.enableRandomizer) {
  92211. //for(var j=1, l=islandNumConstraints; j<l; j++){
  92212. j = islandNumConstraints;
  92213. while (j--) {
  92214. if (j !== 0) {
  92215. var swap = (this.randX = (this.randX * this.randA + this.randB & 0x7fffffff)) / 2147483648.0 * j | 0;
  92216. constraint = this.islandConstraints[j];
  92217. this.islandConstraints[j] = this.islandConstraints[swap];
  92218. this.islandConstraints[swap] = constraint;
  92219. }
  92220. }
  92221. }
  92222. // solve contraints
  92223. j = islandNumConstraints;
  92224. while (j--) {
  92225. //for(j=0, l=islandNumConstraints; j<l; j++){
  92226. this.islandConstraints[j].preSolve(this.timeStep, invTimeStep);// pre-solve
  92227. }
  92228. var k = this.numIterations;
  92229. while (k--) {
  92230. //for(var k=0, l=this.numIterations; k<l; k++){
  92231. j = islandNumConstraints;
  92232. while (j--) {
  92233. //for(j=0, m=islandNumConstraints; j<m; j++){
  92234. this.islandConstraints[j].solve();// main-solve
  92235. }
  92236. }
  92237. j = islandNumConstraints;
  92238. while (j--) {
  92239. //for(j=0, l=islandNumConstraints; j<l; j++){
  92240. this.islandConstraints[j].postSolve();// post-solve
  92241. this.islandConstraints[j] = null;// gc
  92242. }
  92243. // sleeping check
  92244. var sleepTime = 10;
  92245. j = islandNumRigidBodies;
  92246. while (j--) {
  92247. //for(j=0, l=islandNumRigidBodies;j<l;j++){
  92248. body = this.islandRigidBodies[j];
  92249. if (this.callSleep(body)) {
  92250. body.sleepTime += this.timeStep;
  92251. if (body.sleepTime < sleepTime) sleepTime = body.sleepTime;
  92252. } else {
  92253. body.sleepTime = 0;
  92254. sleepTime = 0;
  92255. continue;
  92256. }
  92257. }
  92258. if (sleepTime > 0.5) {
  92259. // sleep the island
  92260. j = islandNumRigidBodies;
  92261. while (j--) {
  92262. //for(j=0, l=islandNumRigidBodies;j<l;j++){
  92263. this.islandRigidBodies[j].sleep();
  92264. this.islandRigidBodies[j] = null;// gc
  92265. }
  92266. } else {
  92267. // update positions
  92268. j = islandNumRigidBodies;
  92269. while (j--) {
  92270. //for(j=0, l=islandNumRigidBodies;j<l;j++){
  92271. this.islandRigidBodies[j].updatePosition(this.timeStep);
  92272. this.islandRigidBodies[j] = null;// gc
  92273. }
  92274. }
  92275. this.numIslands++;
  92276. }
  92277. if (stat) {
  92278. time2 = OIMO.now();
  92279. this.performance.solvingTime = time2 - time1;
  92280. //------------------------------------------------------
  92281. // END SIMULATION
  92282. //------------------------------------------------------
  92283. time2 = OIMO.now();
  92284. // fps update
  92285. this.performance.upfps();
  92286. this.performance.totalTime = time2 - time0;
  92287. }
  92288. }
  92289. }
  92290. /**
  92291. * The class of rigid body.
  92292. * Rigid body has the shape of a single or multiple collision processing,
  92293. * I can set the parameters individually.
  92294. * @author saharan
  92295. */
  92296. OIMO.RigidBody = function (x, y, z, rad, ax, ay, az) {
  92297. this.name = " ";
  92298. // The maximum number of shapes that can be added to a one rigid.
  92299. this.MAX_SHAPES = 64;//64;
  92300. this.prev = null;
  92301. this.next = null;
  92302. // I represent the kind of rigid body.
  92303. // Please do not change from the outside this variable.
  92304. // If you want to change the type of rigid body, always
  92305. // Please specify the type you want to set the arguments of setupMass method.
  92306. this.type = OIMO.BODY_NULL;
  92307. this.massInfo = new OIMO.MassInfo();
  92308. // It is the world coordinate of the center of gravity.
  92309. this.position = new OIMO.Vec3(x, y, z);
  92310. this.orientation = this.rotationAxisToQuad(rad || 0, ax || 0, ay || 0, az || 0);
  92311. this.newPosition = new OIMO.Vec3();
  92312. this.controlPos = false;
  92313. this.newOrientation = new OIMO.Quat();
  92314. this.newRotation = new OIMO.Vec3();
  92315. this.currentRotation = new OIMO.Vec3();
  92316. this.controlRot = false;
  92317. this.controlRotInTime = false;
  92318. // Is the translational velocity.
  92319. this.linearVelocity = new OIMO.Vec3();
  92320. // Is the angular velocity.
  92321. this.angularVelocity = new OIMO.Vec3();
  92322. // return matrix for three.js
  92323. this.matrix = new OIMO.Mat44();
  92324. //--------------------------------------------
  92325. // Please do not change from the outside this variables.
  92326. //--------------------------------------------
  92327. // It is a world that rigid body has been added.
  92328. this.parent = null;
  92329. this.contactLink = null;
  92330. this.numContacts = 0;
  92331. // An array of shapes that are included in the rigid body.
  92332. this.shapes = null;
  92333. // The number of shapes that are included in the rigid body.
  92334. this.numShapes = 0;
  92335. // It is the link array of joint that is connected to the rigid body.
  92336. this.jointLink = null;
  92337. // The number of joints that are connected to the rigid body.
  92338. this.numJoints = 0;
  92339. // It is the world coordinate of the center of gravity in the sleep just before.
  92340. this.sleepPosition = new OIMO.Vec3();
  92341. // It is a quaternion that represents the attitude of sleep just before.
  92342. this.sleepOrientation = new OIMO.Quat();
  92343. // I will show this rigid body to determine whether it is a rigid body static.
  92344. this.isStatic = false;
  92345. // I indicates that this rigid body to determine whether it is a rigid body dynamic.
  92346. this.isDynamic = false;
  92347. // It is a rotation matrix representing the orientation.
  92348. this.rotation = new OIMO.Mat33();
  92349. //--------------------------------------------
  92350. // It will be recalculated automatically from the shape, which is included.
  92351. //--------------------------------------------
  92352. // This is the weight.
  92353. this.mass = NaN;
  92354. // It is the reciprocal of the mass.
  92355. this.inverseMass = NaN;
  92356. // It is the inverse of the inertia tensor in the world system.
  92357. this.inverseInertia = new OIMO.Mat33();
  92358. // It is the inertia tensor in the initial state.
  92359. this.localInertia = new OIMO.Mat33();
  92360. // It is the inverse of the inertia tensor in the initial state.
  92361. this.inverseLocalInertia = new OIMO.Mat33();
  92362. // I indicates rigid body whether it has been added to the simulation Island.
  92363. this.addedToIsland = false;
  92364. // It shows how to sleep rigid body.
  92365. this.allowSleep = true;
  92366. // This is the time from when the rigid body at rest.
  92367. this.sleepTime = 0;
  92368. // I shows rigid body to determine whether it is a sleep state.
  92369. this.sleeping = false;
  92370. };
  92371. OIMO.RigidBody.prototype = {
  92372. constructor: OIMO.RigidBody,
  92373. /**
  92374. * I'll add a shape to rigid body.
  92375. * If you add a shape, please call the setupMass method to step up to the start of the next.
  92376. * @param shape shape to Add
  92377. */
  92378. addShape: function (shape) {
  92379. if (shape.parent) OIMO.Error("RigidBody", "It is not possible that you add to the multi-rigid body the shape of one");
  92380. if (this.shapes != null) (this.shapes.prev = shape).next = this.shapes;
  92381. this.shapes = shape;
  92382. shape.parent = this;
  92383. if (this.parent) this.parent.addShape(shape);
  92384. this.numShapes++;
  92385. },
  92386. /**
  92387. * I will delete the shape from the rigid body.
  92388. * If you delete a shape, please call the setupMass method to step up to the start of the next.
  92389. * @param shape shape to Delete
  92390. */
  92391. removeShape: function (shape) {
  92392. var remove = shape;
  92393. if (remove.parent != this) return;
  92394. var prev = remove.prev;
  92395. var next = remove.next;
  92396. if (prev != null) prev.next = next;
  92397. if (next != null) next.prev = prev;
  92398. if (this.shapes == remove) this.shapes = next;
  92399. remove.prev = null;
  92400. remove.next = null;
  92401. remove.parent = null;
  92402. if (this.parent) this.parent.removeShape(remove);
  92403. this.numShapes--;
  92404. },
  92405. remove: function () {
  92406. this.dispose();
  92407. },
  92408. dispose: function () {
  92409. this.parent.removeRigidBody(this);
  92410. },
  92411. checkContact: function (name) {
  92412. this.parent.checkContact(this.name, name);
  92413. },
  92414. /**
  92415. * Calulates mass datas(center of gravity, mass, moment inertia, etc...).
  92416. * If the parameter type is set to BODY_STATIC, the rigid body will be fixed to the space.
  92417. * If the parameter adjustPosition is set to true, the shapes' relative positions and
  92418. * the rigid body's position will be adjusted to the center of gravity.
  92419. * @param type
  92420. * @param adjustPosition
  92421. */
  92422. setupMass: function (type, AdjustPosition) {
  92423. var adjustPosition = (AdjustPosition !== undefined) ? AdjustPosition : true;
  92424. this.type = type || OIMO.BODY_DYNAMIC;
  92425. this.isDynamic = this.type == OIMO.BODY_DYNAMIC;
  92426. this.isStatic = this.type == OIMO.BODY_STATIC;
  92427. this.mass = 0;
  92428. this.localInertia.set(0, 0, 0, 0, 0, 0, 0, 0, 0);
  92429. var te = this.localInertia.elements;
  92430. //
  92431. var tmpM = new OIMO.Mat33();
  92432. var tmpV = new OIMO.Vec3();
  92433. for (var shape = this.shapes; shape != null; shape = shape.next) {
  92434. shape.calculateMassInfo(this.massInfo);
  92435. var shapeMass = this.massInfo.mass;
  92436. var relX = shape.relativePosition.x;
  92437. var relY = shape.relativePosition.y;
  92438. var relZ = shape.relativePosition.z;
  92439. /*tmpV.x+=relX*shapeMass;
  92440. tmpV.y+=relY*shapeMass;
  92441. tmpV.z+=relZ*shapeMass;*/
  92442. tmpV.addScale(shape.relativePosition, shapeMass);
  92443. this.mass += shapeMass;
  92444. this.rotateInertia(shape.relativeRotation, this.massInfo.inertia, tmpM);
  92445. this.localInertia.addEqual(tmpM);
  92446. // add offset inertia
  92447. te[0] += shapeMass * (relY * relY + relZ * relZ);
  92448. te[4] += shapeMass * (relX * relX + relZ * relZ);
  92449. te[8] += shapeMass * (relX * relX + relY * relY);
  92450. var xy = shapeMass * relX * relY;
  92451. var yz = shapeMass * relY * relZ;
  92452. var zx = shapeMass * relZ * relX;
  92453. te[1] -= xy;
  92454. te[3] -= xy;
  92455. te[2] -= yz;
  92456. te[6] -= yz;
  92457. te[5] -= zx;
  92458. te[7] -= zx;
  92459. }
  92460. this.inverseMass = 1 / this.mass;
  92461. tmpV.scaleEqual(this.inverseMass);
  92462. if (adjustPosition) {
  92463. this.position.addEqual(tmpV);
  92464. for (shape = this.shapes; shape != null; shape = shape.next) {
  92465. shape.relativePosition.subEqual(tmpV);
  92466. }
  92467. // subtract offset inertia
  92468. relX = tmpV.x;
  92469. relY = tmpV.y;
  92470. relZ = tmpV.z;
  92471. //var te = this.localInertia.elements;
  92472. te[0] -= this.mass * (relY * relY + relZ * relZ);
  92473. te[4] -= this.mass * (relX * relX + relZ * relZ);
  92474. te[8] -= this.mass * (relX * relX + relY * relY);
  92475. xy = this.mass * relX * relY;
  92476. yz = this.mass * relY * relZ;
  92477. zx = this.mass * relZ * relX;
  92478. te[1] += xy;
  92479. te[3] += xy;
  92480. te[2] += yz;
  92481. te[6] += yz;
  92482. te[5] += zx;
  92483. te[7] += zx;
  92484. }
  92485. this.inverseLocalInertia.invert(this.localInertia);
  92486. if (this.type == OIMO.BODY_STATIC) {
  92487. this.inverseMass = 0;
  92488. this.inverseLocalInertia.set(0, 0, 0, 0, 0, 0, 0, 0, 0);
  92489. }
  92490. this.syncShapes();
  92491. this.awake();
  92492. },
  92493. /**
  92494. * Awake the rigid body.
  92495. */
  92496. awake: function () {
  92497. if (!this.allowSleep || !this.sleeping) return;
  92498. this.sleeping = false;
  92499. this.sleepTime = 0;
  92500. // awake connected constraints
  92501. var cs = this.contactLink;
  92502. while (cs != null) {
  92503. cs.body.sleepTime = 0;
  92504. cs.body.sleeping = false;
  92505. cs = cs.next;
  92506. }
  92507. var js = this.jointLink;
  92508. while (js != null) {
  92509. js.body.sleepTime = 0;
  92510. js.body.sleeping = false;
  92511. js = js.next;
  92512. }
  92513. for (var shape = this.shapes; shape != null; shape = shape.next) {
  92514. shape.updateProxy();
  92515. }
  92516. },
  92517. /**
  92518. * Sleep the rigid body.
  92519. */
  92520. sleep: function () {
  92521. if (!this.allowSleep || this.sleeping) return;
  92522. this.linearVelocity.set(0, 0, 0);
  92523. this.angularVelocity.set(0, 0, 0);
  92524. this.sleepPosition.copy(this.position);
  92525. this.sleepOrientation.copy(this.orientation);
  92526. /*this.linearVelocity.x=0;
  92527. this.linearVelocity.y=0;
  92528. this.linearVelocity.z=0;
  92529. this.angularVelocity.x=0;
  92530. this.angularVelocity.y=0;
  92531. this.angularVelocity.z=0;
  92532. this.sleepPosition.x=this.position.x;
  92533. this.sleepPosition.y=this.position.y;
  92534. this.sleepPosition.z=this.position.z;*/
  92535. /*this.sleepOrientation.s=this.orientation.s;
  92536. this.sleepOrientation.x=this.orientation.x;
  92537. this.sleepOrientation.y=this.orientation.y;
  92538. this.sleepOrientation.z=this.orientation.z;*/
  92539. this.sleepTime = 0;
  92540. this.sleeping = true;
  92541. for (var shape = this.shapes; shape != null; shape = shape.next) {
  92542. shape.updateProxy();
  92543. }
  92544. },
  92545. /**
  92546. * Get whether the rigid body has not any connection with others.
  92547. * @return
  92548. */
  92549. isLonely: function () {
  92550. return this.numJoints == 0 && this.numContacts == 0;
  92551. },
  92552. /**
  92553. * The time integration of the motion of a rigid body, you can update the information such as the shape.
  92554. * This method is invoked automatically when calling the step of the World,
  92555. * There is no need to call from outside usually.
  92556. * @param timeStep time
  92557. */
  92558. updatePosition: function (timeStep) {
  92559. switch (this.type) {
  92560. case OIMO.BODY_STATIC:
  92561. this.linearVelocity.set(0, 0, 0);
  92562. this.angularVelocity.set(0, 0, 0);
  92563. // ONLY FOR TEST
  92564. if (this.controlPos) {
  92565. this.position.copy(this.newPosition);
  92566. this.controlPos = false;
  92567. }
  92568. if (this.controlRot) {
  92569. this.orientation.copy(this.newOrientation);
  92570. this.controlRot = false;
  92571. }
  92572. /*this.linearVelocity.x=0;
  92573. this.linearVelocity.y=0;
  92574. this.linearVelocity.z=0;
  92575. this.angularVelocity.x=0;
  92576. this.angularVelocity.y=0;
  92577. this.angularVelocity.z=0;*/
  92578. break;
  92579. case OIMO.BODY_DYNAMIC:
  92580. if (this.controlPos) {
  92581. this.angularVelocity.set(0, 0, 0);
  92582. this.linearVelocity.set(0, 0, 0);
  92583. this.linearVelocity.x = (this.newPosition.x - this.position.x) / timeStep;
  92584. this.linearVelocity.y = (this.newPosition.y - this.position.y) / timeStep;
  92585. this.linearVelocity.z = (this.newPosition.z - this.position.z) / timeStep;
  92586. this.controlPos = false;
  92587. }
  92588. if (this.controlRot) {
  92589. this.angularVelocity.set(0, 0, 0);
  92590. this.orientation.copy(this.newOrientation);
  92591. //var t=timeStep//*0.5;
  92592. //var q = new OIMO.Quat();
  92593. //q.sub(this.newOrientation, this.orientation);
  92594. //q.normalize(q);
  92595. /*q.s = (this.newOrientation.s - this.orientation.s)/t;
  92596. q.x = (this.newOrientation.x - this.orientation.x)/t;
  92597. q.y = (this.newOrientation.y - this.orientation.y)/t;
  92598. q.z = (this.newOrientation.z - this.orientation.z)/t;*/
  92599. //this.angularVelocity.applyQuaternion(q);
  92600. //this.angularVelocity.x = this.angularVelocity.x/t;
  92601. //this.angularVelocity.y = this.angularVelocity.y/t;
  92602. //this.angularVelocity.z = this.angularVelocity.z/t;
  92603. this.controlRot = false;
  92604. }
  92605. this.position.addTime(this.linearVelocity, timeStep);
  92606. this.orientation.addTime(this.angularVelocity, timeStep);
  92607. break;
  92608. default: OIMO.Error("RigidBody", "Invalid type.");
  92609. }
  92610. this.syncShapes();
  92611. },
  92612. rotateInertia: function (rot, inertia, out) {
  92613. var tm1 = rot.elements;
  92614. var tm2 = inertia.elements;
  92615. var a0 = tm1[0], a3 = tm1[3], a6 = tm1[6];
  92616. var a1 = tm1[1], a4 = tm1[4], a7 = tm1[7];
  92617. var a2 = tm1[2], a5 = tm1[5], a8 = tm1[8];
  92618. var b0 = tm2[0], b3 = tm2[3], b6 = tm2[6];
  92619. var b1 = tm2[1], b4 = tm2[4], b7 = tm2[7];
  92620. var b2 = tm2[2], b5 = tm2[5], b8 = tm2[8];
  92621. var e00 = a0 * b0 + a1 * b3 + a2 * b6;
  92622. var e01 = a0 * b1 + a1 * b4 + a2 * b7;
  92623. var e02 = a0 * b2 + a1 * b5 + a2 * b8;
  92624. var e10 = a3 * b0 + a4 * b3 + a5 * b6;
  92625. var e11 = a3 * b1 + a4 * b4 + a5 * b7;
  92626. var e12 = a3 * b2 + a4 * b5 + a5 * b8;
  92627. var e20 = a6 * b0 + a7 * b3 + a8 * b6;
  92628. var e21 = a6 * b1 + a7 * b4 + a8 * b7;
  92629. var e22 = a6 * b2 + a7 * b5 + a8 * b8;
  92630. var oe = out.elements;
  92631. oe[0] = e00 * a0 + e01 * a1 + e02 * a2;
  92632. oe[1] = e00 * a3 + e01 * a4 + e02 * a5;
  92633. oe[2] = e00 * a6 + e01 * a7 + e02 * a8;
  92634. oe[3] = e10 * a0 + e11 * a1 + e12 * a2;
  92635. oe[4] = e10 * a3 + e11 * a4 + e12 * a5;
  92636. oe[5] = e10 * a6 + e11 * a7 + e12 * a8;
  92637. oe[6] = e20 * a0 + e21 * a1 + e22 * a2;
  92638. oe[7] = e20 * a3 + e21 * a4 + e22 * a5;
  92639. oe[8] = e20 * a6 + e21 * a7 + e22 * a8;
  92640. },
  92641. syncShapes: function () {
  92642. var s = this.orientation.s;
  92643. var x = this.orientation.x;
  92644. var y = this.orientation.y;
  92645. var z = this.orientation.z;
  92646. var x2 = 2 * x;
  92647. var y2 = 2 * y;
  92648. var z2 = 2 * z;
  92649. var xx = x * x2;
  92650. var yy = y * y2;
  92651. var zz = z * z2;
  92652. var xy = x * y2;
  92653. var yz = y * z2;
  92654. var xz = x * z2;
  92655. var sx = s * x2;
  92656. var sy = s * y2;
  92657. var sz = s * z2;
  92658. var tr = this.rotation.elements;
  92659. tr[0] = 1 - yy - zz;
  92660. tr[1] = xy - sz;
  92661. tr[2] = xz + sy;
  92662. tr[3] = xy + sz;
  92663. tr[4] = 1 - xx - zz;
  92664. tr[5] = yz - sx;
  92665. tr[6] = xz - sy;
  92666. tr[7] = yz + sx;
  92667. tr[8] = 1 - xx - yy;
  92668. this.rotateInertia(this.rotation, this.inverseLocalInertia, this.inverseInertia);
  92669. for (var shape = this.shapes; shape != null; shape = shape.next) {
  92670. //var relPos=shape.relativePosition;
  92671. //var relRot=shape.relativeRotation;
  92672. //var rot=shape.rotation;
  92673. /*var lx=relPos.x;
  92674. var ly=relPos.y;
  92675. var lz=relPos.z;
  92676. shape.position.x=this.position.x+lx*tr[0]+ly*tr[1]+lz*tr[2];
  92677. shape.position.y=this.position.y+lx*tr[3]+ly*tr[4]+lz*tr[5];
  92678. shape.position.z=this.position.z+lx*tr[6]+ly*tr[7]+lz*tr[8];*/
  92679. shape.position.mul(this.position, shape.relativePosition, this.rotation);
  92680. //shape.rotation.mul(shape.relativeRotation,this.rotation);
  92681. // add by QuaziKb
  92682. shape.rotation.mul(this.rotation, shape.relativeRotation);
  92683. shape.updateProxy();
  92684. }
  92685. },
  92686. applyImpulse: function (position, force) {
  92687. this.linearVelocity.addScale(force, this.inverseMass);
  92688. /*this.linearVelocity.x+=force.x*this.inverseMass;
  92689. this.linearVelocity.y+=force.y*this.inverseMass;
  92690. this.linearVelocity.z+=force.z*this.inverseMass;*/
  92691. var rel = new OIMO.Vec3();
  92692. rel.sub(position, this.position).cross(rel, force).mulMat(this.inverseInertia, rel);
  92693. this.angularVelocity.addEqual(rel);
  92694. /*this.angularVelocity.x+=rel.x;
  92695. this.angularVelocity.y+=rel.y;
  92696. this.angularVelocity.z+=rel.z;*/
  92697. },
  92698. //---------------------------------------------
  92699. //
  92700. // FOR THREE JS
  92701. //
  92702. //---------------------------------------------
  92703. rotationVectToQuad: function (rot) {
  92704. var r = OIMO.EulerToAxis(rot.x * OIMO.degtorad, rot.y * OIMO.degtorad, rot.z * OIMO.degtorad);
  92705. return this.rotationAxisToQuad(r[0], r[1], r[2], r[3]);
  92706. },
  92707. rotationAxisToQuad: function (rad, ax, ay, az) { // in radian
  92708. var len = ax * ax + ay * ay + az * az;
  92709. if (len > 0) {
  92710. len = 1 / OIMO.sqrt(len);
  92711. ax *= len;
  92712. ay *= len;
  92713. az *= len;
  92714. }
  92715. var sin = OIMO.sin(rad * 0.5);
  92716. var cos = OIMO.cos(rad * 0.5);
  92717. return new OIMO.Quat(cos, sin * ax, sin * ay, sin * az);
  92718. },
  92719. //---------------------------------------------
  92720. // SET DYNAMIQUE POSITION AND ROTATION
  92721. //---------------------------------------------
  92722. setPosition: function (pos) {
  92723. this.newPosition.copy(pos).multiplyScalar(OIMO.INV_SCALE);
  92724. //this.newPosition.set(pos.x*OIMO.INV_SCALE,pos.y*OIMO.INV_SCALE,pos.z*OIMO.INV_SCALE);
  92725. this.controlPos = true;
  92726. },
  92727. setQuaternion: function (q) {
  92728. //if(this.type == this.BODY_STATIC)this.orientation.init(q.w,q.x,q.y,q.z);
  92729. this.newOrientation.set(q.x, q.y, q.z, q.w);
  92730. this.controlRot = true;
  92731. },
  92732. setRotation: function (rot) {
  92733. this.newOrientation = this.rotationVectToQuad(rot);
  92734. this.controlRot = true;
  92735. },
  92736. //---------------------------------------------
  92737. // RESET DYNAMIQUE POSITION AND ROTATION
  92738. //---------------------------------------------
  92739. resetPosition: function (x, y, z) {
  92740. this.linearVelocity.set(0, 0, 0);
  92741. this.angularVelocity.set(0, 0, 0);
  92742. this.position.set(x, y, z).multiplyScalar(OIMO.INV_SCALE);
  92743. //this.position.set( x*OIMO.INV_SCALE, y*OIMO.INV_SCALE, z*OIMO.INV_SCALE );
  92744. this.awake();
  92745. },
  92746. resetQuaternion: function (q) {
  92747. this.angularVelocity.set(0, 0, 0);
  92748. this.orientation = new OIMO.Quat(q.w, q.x, q.y, q.z);
  92749. this.awake();
  92750. },
  92751. resetRotation: function (x, y, z) {
  92752. this.angularVelocity.set(0, 0, 0);
  92753. this.orientation = this.rotationVectToQuad(new OIMO.Vec3(x, y, z));
  92754. this.awake();
  92755. },
  92756. //---------------------------------------------
  92757. // GET POSITION AND ROTATION
  92758. //---------------------------------------------
  92759. getPosition: function () {
  92760. return new OIMO.Vec3().scale(this.position, OIMO.WORLD_SCALE);
  92761. },
  92762. getRotation: function () {
  92763. return new OIMO.Euler().setFromRotationMatrix(this.rotation);
  92764. },
  92765. getQuaternion: function () {
  92766. return new OIMO.Quaternion().setFromRotationMatrix(this.rotation);
  92767. },
  92768. getMatrix: function () {
  92769. var m = this.matrix.elements;
  92770. var r, p;
  92771. if (!this.sleeping) {
  92772. // rotation matrix
  92773. r = this.rotation.elements;
  92774. m[0] = r[0]; m[1] = r[3]; m[2] = r[6]; m[3] = 0;
  92775. m[4] = r[1]; m[5] = r[4]; m[6] = r[7]; m[7] = 0;
  92776. m[8] = r[2]; m[9] = r[5]; m[10] = r[8]; m[11] = 0;
  92777. // position matrix
  92778. p = this.position;
  92779. m[12] = p.x * OIMO.WORLD_SCALE;
  92780. m[13] = p.y * OIMO.WORLD_SCALE;
  92781. m[14] = p.z * OIMO.WORLD_SCALE;
  92782. // sleep or not ?
  92783. m[15] = 0;
  92784. } else {
  92785. m[15] = 1;
  92786. }
  92787. return m;
  92788. }
  92789. };
  92790. /**
  92791. * The main class of body.
  92792. * is for simplify creation process and data access of rigidRody
  92793. * Rigid body has the shape of a single or multiple collision processing,
  92794. * all setting in object
  92795. *
  92796. * @author loth
  92797. */
  92798. OIMO.Body = function (Obj) {
  92799. var obj = Obj || {};
  92800. if (!obj.world) return;
  92801. if (obj.type === undefined) obj.type = "box";
  92802. this.name = obj.name || '';
  92803. // obsolete use world.add(obj)
  92804. this.body = obj.world.add(obj);
  92805. /*
  92806. // the world where i am
  92807. this.parent = obj.world;
  92808. // Yep my name
  92809. this.name = obj.name || '';
  92810. // I'm dynamique or not
  92811. var move = obj.move || false;
  92812. // I can sleep or not
  92813. var noSleep = obj.noSleep || false;
  92814. // My start position
  92815. var p = obj.pos || [0,0,0];
  92816. p = p.map(function(x) { return x * OIMO.INV_SCALE; });
  92817. // My size
  92818. var s = obj.size || [1,1,1];
  92819. s = s.map(function(x) { return x * OIMO.INV_SCALE; });
  92820. // My rotation in degre
  92821. var rot = obj.rot || [0,0,0];
  92822. rot = rot.map(function(x) { return x * OIMO.TO_RAD; });
  92823. var r = [];
  92824. for (var i=0; i<rot.length/3; i++){
  92825. var tmp = OIMO.EulerToAxis(rot[i+0], rot[i+1], rot[i+2]);
  92826. r.push(tmp[0]); r.push(tmp[1]); r.push(tmp[2]); r.push(tmp[3]);
  92827. }
  92828. // My physics setting
  92829. var sc = obj.sc || new OIMO.ShapeConfig();
  92830. if(obj.config){
  92831. // The density of the shape.
  92832. sc.density = obj.config[0] || 1;
  92833. // The coefficient of friction of the shape.
  92834. sc.friction = obj.config[1] || 0.4;
  92835. // The coefficient of restitution of the shape.
  92836. sc.restitution = obj.config[2] || 0.2;
  92837. // The bits of the collision groups to which the shape belongs.
  92838. sc.belongsTo = obj.config[3] || 1;
  92839. // The bits of the collision groups with which the shape collides.
  92840. sc.collidesWith = obj.config[4] || 0xffffffff;
  92841. }
  92842. if(obj.massPos){
  92843. obj.massPos = obj.massPos.map(function(x) { return x * OIMO.INV_SCALE; });
  92844. sc.relativePosition.init(obj.massPos[0], obj.massPos[1], obj.massPos[2]);
  92845. }
  92846. if(obj.massRot){
  92847. obj.massRot = obj.massRot.map(function(x) { return x * OIMO.TO_RAD; });
  92848. sc.relativeRotation = OIMO.EulerToMatrix(obj.massRot[0], obj.massRot[1], obj.massRot[2]);
  92849. }
  92850. // My rigidbody
  92851. this.body = new OIMO.RigidBody(p[0], p[1], p[2], r[0], r[1], r[2], r[3]);
  92852. // My shapes
  92853. var shapes = [];
  92854. var type = obj.type || "box";
  92855. if( typeof type === 'string' ) type = [type];// single shape
  92856. var n, n2;
  92857. for(var i=0; i<type.length; i++){
  92858. n = i*3;
  92859. n2 = i*4;
  92860. switch(type[i]){
  92861. case "sphere": shapes[i] = new OIMO.SphereShape(sc, s[n+0]); break;
  92862. case "cylinder": shapes[i] = new OIMO.BoxShape(sc, s[n+0], s[n+1], s[n+2]); break; // fake cylinder
  92863. case "box": shapes[i] = new OIMO.BoxShape(sc, s[n+0], s[n+1], s[n+2]); break;
  92864. }
  92865. this.body.addShape(shapes[i]);
  92866. if(i>0){
  92867. //shapes[i].position.init(p[0]+p[n+0], p[1]+p[n+1], p[2]+p[n+2] );
  92868. shapes[i].relativePosition = new OIMO.Vec3( p[n+0], p[n+1], p[n+2] );
  92869. if(r[n2+0]) shapes[i].relativeRotation = [ r[n2+0], r[n2+1], r[n2+2], r[n2+3] ];
  92870. }
  92871. }
  92872. // I'm static or i move
  92873. if(move){
  92874. if(obj.massPos || obj.massRot)this.body.setupMass(0x1, false);
  92875. else this.body.setupMass(0x1, true);
  92876. if(noSleep) this.body.allowSleep = false;
  92877. else this.body.allowSleep = true;
  92878. } else {
  92879. this.body.setupMass(0x2);
  92880. }
  92881. this.body.name = this.name;
  92882. this.sleeping = this.body.sleeping;
  92883. // finaly add to physics world
  92884. this.parent.addRigidBody(this.body);*/
  92885. }
  92886. OIMO.Body.prototype = {
  92887. constructor: OIMO.Body,
  92888. // SET
  92889. setPosition: function (pos) {
  92890. this.body.setPosition(pos);
  92891. },
  92892. setQuaternion: function (q) {
  92893. this.body.setQuaternion(q);
  92894. },
  92895. setRotation: function (rot) {
  92896. this.body.setRotation(rot);
  92897. },
  92898. // GET
  92899. getPosition: function () {
  92900. return this.body.getPosition();
  92901. },
  92902. getRotation: function () {
  92903. return this.body.getRotation();
  92904. },
  92905. getQuaternion: function () {
  92906. return this.body.getQuaternion();
  92907. },
  92908. getMatrix: function () {
  92909. return this.body.getMatrix();
  92910. },
  92911. getSleep: function () {
  92912. return this.body.sleeping;
  92913. },
  92914. // RESET
  92915. resetPosition: function (x, y, z) {
  92916. this.body.resetPosition(x, y, z);
  92917. },
  92918. resetRotation: function (x, y, z) {
  92919. this.body.resetRotation(x, y, z);
  92920. },
  92921. // force wakeup
  92922. awake: function () {
  92923. this.body.awake();
  92924. },
  92925. // remove rigidbody
  92926. remove: function () {
  92927. this.body.dispose();
  92928. //this.parent.removeRigidBody(this.body);
  92929. },
  92930. // test if this object hit another
  92931. checkContact: function (name) {
  92932. this.body.checkContact(name);
  92933. //this.parent.checkContact(this.name, name);
  92934. }
  92935. }
  92936. /**
  92937. * The main class of link.
  92938. * is for simplify creation process and data access of Joint
  92939. * all setting in object
  92940. *
  92941. * @author loth
  92942. */
  92943. OIMO.Link = function (Obj) {
  92944. var obj = Obj || {};
  92945. if (!obj.world) return;
  92946. if (obj.type === undefined) obj.type = "jointHinge";
  92947. this.name = obj.name || '';
  92948. // obsolete use world.add(obj)
  92949. this.joint = obj.world.add(obj);
  92950. // the world where i am
  92951. /*this.parent = obj.world;
  92952. this.name = obj.name || '';
  92953. var type = obj.type || "jointHinge";
  92954. var axe1 = obj.axe1 || [1,0,0];
  92955. var axe2 = obj.axe2 || [1,0,0];
  92956. var pos1 = obj.pos1 || [0,0,0];
  92957. var pos2 = obj.pos2 || [0,0,0];
  92958. pos1 = pos1.map(function(x){ return x * OIMO.INV_SCALE; });
  92959. pos2 = pos2.map(function(x){ return x * OIMO.INV_SCALE; });
  92960. var min, max;
  92961. if(type==="jointDistance"){
  92962. min = obj.min || 0;
  92963. max = obj.max || 10;
  92964. min = min*OIMO.INV_SCALE;
  92965. max = max*OIMO.INV_SCALE;
  92966. }else{
  92967. min = obj.min || 57.29578;
  92968. max = obj.max || 0;
  92969. min = min*OIMO.TO_RAD;
  92970. max = max*OIMO.TO_RAD;
  92971. }
  92972. var limit = obj.limit || null;
  92973. var spring = obj.spring || null;
  92974. var motor = obj.motor || null;
  92975. // joint setting
  92976. var jc = new OIMO.JointConfig();
  92977. jc.allowCollision = obj.collision || false;;
  92978. jc.localAxis1.init(axe1[0], axe1[1], axe1[2]);
  92979. jc.localAxis2.init(axe2[0], axe2[1], axe2[2]);
  92980. jc.localAnchorPoint1.init(pos1[0], pos1[1], pos1[2]);
  92981. jc.localAnchorPoint2.init(pos2[0], pos2[1], pos2[2]);
  92982. if (typeof obj.body1 == 'string' || obj.body1 instanceof String) obj.body1 = obj.world.getByName(obj.body1);
  92983. if (typeof obj.body2 == 'string' || obj.body2 instanceof String) obj.body2 = obj.world.getByName(obj.body2);
  92984. jc.body1 = obj.body1;
  92985. jc.body2 = obj.body2;
  92986. switch(type){
  92987. case "jointDistance": this.joint = new OIMO.DistanceJoint(jc, min, max);
  92988. if(spring !== null) this.joint.limitMotor.setSpring(spring[0], spring[1]);
  92989. if(motor !== null) this.joint.limitMotor.setSpring(motor[0], motor[1]);
  92990. break;
  92991. case "jointHinge": this.joint = new OIMO.HingeJoint(jc, min, max);
  92992. if(spring !== null) this.joint.limitMotor.setSpring(spring[0], spring[1]);// soften the joint ex: 100, 0.2
  92993. if(motor !== null) this.joint.limitMotor.setSpring(motor[0], motor[1]);
  92994. break;
  92995. case "jointPrisme": this.joint = new OIMO.PrismaticJoint(jc, min, max); break;
  92996. case "jointSlide": this.joint = new OIMO.SliderJoint(jc, min, max); break;
  92997. case "jointBall": this.joint = new OIMO.BallAndSocketJoint(jc); break;
  92998. case "jointWheel": this.joint = new OIMO.WheelJoint(jc);
  92999. if(limit !== null) this.joint.rotationalLimitMotor1.setLimit(limit[0], limit[1]);
  93000. if(spring !== null) this.joint.rotationalLimitMotor1.setSpring(spring[0], spring[1]);
  93001. if(motor !== null) this.joint.rotationalLimitMotor1.setSpring(motor[0], motor[1]);
  93002. break;
  93003. }
  93004. this.joint.name = this.name;
  93005. // finaly add to physics world
  93006. this.parent.addJoint(this.joint);*/
  93007. }
  93008. OIMO.Link.prototype = {
  93009. constructor: OIMO.Link,
  93010. getPosition: function () {
  93011. // array of two vect3 [point1, point2]
  93012. return this.joint.getPosition();
  93013. },
  93014. getMatrix: function () {
  93015. return this.joint.getMatrix();
  93016. },
  93017. // remove joint
  93018. remove: function () {
  93019. this.joint.dispose();
  93020. //this.parent.removeJoint(this.joint);
  93021. },
  93022. // force wakeup linked body
  93023. awake: function () {
  93024. this.joint.awake();
  93025. }
  93026. }
  93027. /**
  93028. * The Dictionary class for testing
  93029. * @author lo-th
  93030. */
  93031. OIMO.Dictionary = function () {
  93032. this.data = {};
  93033. this.keys = [];
  93034. };
  93035. OIMO.Dictionary.prototype = {
  93036. constructor: OIMO.Dictionary,
  93037. set: function (value) {
  93038. var key = value.id;
  93039. if (!this.get[key]) this.keys.push(key);
  93040. this.data[key] = value;
  93041. },
  93042. get: function (id) {
  93043. return this.data[id];
  93044. },
  93045. del: function (value) {
  93046. var k = this.keys;
  93047. var n = k.indexOf(value.id);
  93048. if (n > -1) {
  93049. delete this.data[k[n]];
  93050. k.splice(n, 1);
  93051. }
  93052. },
  93053. reset: function () {
  93054. var data = this.data, keys = this.keys, key;
  93055. while (keys.length > 0) {
  93056. key = keys.pop();
  93057. delete data[key];
  93058. }
  93059. }
  93060. };
  93061. OIMO.Performance = function (world) {
  93062. this.parent = world;
  93063. this.infos = new OIMO_ARRAY_TYPE(13);
  93064. this.f = [0, 0, 0];
  93065. this.types = ['None', 'BruteForce', 'Sweep & Prune', 'Bounding Volume Tree'];
  93066. this.broadPhase = this.types[this.parent.broadPhase.types];
  93067. this.version = OIMO.REVISION;
  93068. this.fps = 0;
  93069. this.broadPhaseTime = 0;
  93070. this.narrowPhaseTime = 0;
  93071. this.solvingTime = 0;
  93072. //this.updatingTime = 0;
  93073. this.totalTime = 0;
  93074. };
  93075. OIMO.Performance.prototype = {
  93076. upfps: function () {
  93077. this.f[1] = Date.now();
  93078. 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]++;
  93079. },
  93080. updatingTime: function () {
  93081. return OIMO.fix(this.totalTime - (this.broadPhaseTime + this.narrowPhaseTime + this.solvingTime));
  93082. },
  93083. show: function () {
  93084. var info = [
  93085. "Oimo.js " + this.version + "<br>",
  93086. this.broadPhase + "<br><br>",
  93087. "FPS: " + this.fps + " fps<br><br>",
  93088. "rigidbody " + this.parent.numRigidBodies + "<br>",
  93089. "contact &nbsp;&nbsp;" + this.parent.numContacts + "<br>",
  93090. "ct-point &nbsp;" + this.parent.numContactPoints + "<br>",
  93091. "paircheck " + this.parent.broadPhase.numPairChecks + "<br>",
  93092. "island &nbsp;&nbsp;&nbsp;" + this.parent.numIslands + "<br><br>",
  93093. "Time in milliseconde<br><br>",
  93094. "broad-phase &nbsp;" + OIMO.fix(this.broadPhaseTime) + "<br>",
  93095. "narrow-phase " + OIMO.fix(this.narrowPhaseTime) + "<br>",
  93096. "solving &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" + OIMO.fix(this.solvingTime) + "<br>",
  93097. "total &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" + OIMO.fix(this.totalTime) + "<br>",
  93098. "updating &nbsp;&nbsp;&nbsp;&nbsp;" + this.updatingTime() + "<br>"
  93099. ].join("\n");
  93100. return info;
  93101. },
  93102. toArray: function () {
  93103. this.infos[0] = this.parent.broadPhase.types;
  93104. this.infos[1] = this.parent.numRigidBodies;
  93105. this.infos[2] = this.parent.numContacts;
  93106. this.infos[3] = this.parent.broadPhase.numPairChecks;
  93107. this.infos[4] = this.parent.numContactPoints;
  93108. this.infos[5] = this.parent.numIslands;
  93109. this.infos[6] = this.broadPhaseTime;
  93110. this.infos[7] = this.narrowPhaseTime;
  93111. this.infos[8] = this.solvingTime;
  93112. this.infos[9] = this.updatingTime();
  93113. this.infos[10] = this.totalTime;
  93114. this.infos[11] = this.fps;
  93115. return this.infos;
  93116. }
  93117. };
  93118. OIMO.Mat44 = function (n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44) {
  93119. this.elements = new OIMO_ARRAY_TYPE(16);
  93120. var te = this.elements;
  93121. te[0] = (n11 !== undefined) ? n11 : 1; te[4] = n12 || 0; te[8] = n13 || 0; te[12] = n14 || 0;
  93122. te[1] = n21 || 0; te[5] = (n22 !== undefined) ? n22 : 1; te[9] = n23 || 0; te[13] = n24 || 0;
  93123. te[2] = n31 || 0; te[6] = n32 || 0; te[10] = (n33 !== undefined) ? n33 : 1; te[14] = n34 || 0;
  93124. te[3] = n41 || 0; te[7] = n42 || 0; te[11] = n43 || 0; te[15] = (n44 !== undefined) ? n44 : 1;
  93125. };
  93126. OIMO.Mat44.prototype = {
  93127. constructor: OIMO.Mat44,
  93128. set: function (n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44) {
  93129. var te = this.elements;
  93130. te[0] = n11; te[4] = n12; te[8] = n13; te[12] = n14;
  93131. te[1] = n21; te[5] = n22; te[9] = n23; te[13] = n24;
  93132. te[2] = n31; te[6] = n32; te[10] = n33; te[14] = n34;
  93133. te[3] = n41; te[7] = n42; te[11] = n43; te[15] = n44;
  93134. return this;
  93135. }/*,
  93136. extractRotation: function () {
  93137. var v1 = new THREE.Vector3();
  93138. return function ( m ) {
  93139. var te = this.elements;
  93140. var me = m.elements;
  93141. var scaleX = 1 / v1.set( me[ 0 ], me[ 1 ], me[ 2 ] ).length();
  93142. var scaleY = 1 / v1.set( me[ 4 ], me[ 5 ], me[ 6 ] ).length();
  93143. var scaleZ = 1 / v1.set( me[ 8 ], me[ 9 ], me[ 10 ] ).length();
  93144. te[ 0 ] = me[ 0 ] * scaleX;
  93145. te[ 1 ] = me[ 1 ] * scaleX;
  93146. te[ 2 ] = me[ 2 ] * scaleX;
  93147. te[ 4 ] = me[ 4 ] * scaleY;
  93148. te[ 5 ] = me[ 5 ] * scaleY;
  93149. te[ 6 ] = me[ 6 ] * scaleY;
  93150. te[ 8 ] = me[ 8 ] * scaleZ;
  93151. te[ 9 ] = me[ 9 ] * scaleZ;
  93152. te[ 10 ] = me[ 10 ] * scaleZ;
  93153. return this;
  93154. };
  93155. }() */
  93156. }
  93157. OIMO.Mat33 = function (e00, e01, e02, e10, e11, e12, e20, e21, e22) {
  93158. this.elements = new OIMO_ARRAY_TYPE(9);
  93159. var te = this.elements;
  93160. this.init(
  93161. (e00 !== undefined) ? e00 : 1, e01 || 0, e02 || 0,
  93162. e10 || 0, (e11 !== undefined) ? e11 : 1, e12 || 0,
  93163. e20 || 0, e21 || 0, (e22 !== undefined) ? e22 : 1
  93164. );
  93165. };
  93166. OIMO.Mat33.prototype = {
  93167. constructor: OIMO.Mat33,
  93168. set: function (e00, e01, e02, e10, e11, e12, e20, e21, e22) {
  93169. var te = this.elements;
  93170. te[0] = e00; te[1] = e01; te[2] = e02;
  93171. te[3] = e10; te[4] = e11; te[5] = e12;
  93172. te[6] = e20; te[7] = e21; te[8] = e22;
  93173. return this;
  93174. },
  93175. init: function (e00, e01, e02, e10, e11, e12, e20, e21, e22) {
  93176. var te = this.elements;
  93177. te[0] = e00; te[1] = e01; te[2] = e02;
  93178. te[3] = e10; te[4] = e11; te[5] = e12;
  93179. te[6] = e20; te[7] = e21; te[8] = e22;
  93180. return this;
  93181. },
  93182. multiply: function (s) {
  93183. var te = this.elements;
  93184. te[0] *= s; te[1] *= s; te[2] *= s;
  93185. te[3] *= s; te[4] *= s; te[5] *= s;
  93186. te[6] *= s; te[7] *= s; te[8] *= s;
  93187. return this;
  93188. },
  93189. add: function (m1, m2) {
  93190. var te = this.elements, tem1 = m1.elements, tem2 = m2.elements;
  93191. te[0] = tem1[0] + tem2[0]; te[1] = tem1[1] + tem2[1]; te[2] = tem1[2] + tem2[2];
  93192. te[3] = tem1[3] + tem2[3]; te[4] = tem1[4] + tem2[4]; te[5] = tem1[5] + tem2[5];
  93193. te[6] = tem1[6] + tem2[6]; te[7] = tem1[7] + tem2[7]; te[8] = tem1[8] + tem2[8];
  93194. return this;
  93195. },
  93196. addEqual: function (m) {
  93197. var te = this.elements, tem = m.elements;
  93198. te[0] += tem[0]; te[1] += tem[1]; te[2] += tem[2];
  93199. te[3] += tem[3]; te[4] += tem[4]; te[5] += tem[5];
  93200. te[6] += tem[6]; te[7] += tem[7]; te[8] += tem[8];
  93201. return this;
  93202. },
  93203. sub: function (m1, m2) {
  93204. var te = this.elements, tem1 = m1.elements, tem2 = m2.elements;
  93205. te[0] = tem1[0] - tem2[0]; te[1] = tem1[1] - tem2[1]; te[2] = tem1[2] - tem2[2];
  93206. te[3] = tem1[3] - tem2[3]; te[4] = tem1[4] - tem2[4]; te[5] = tem1[5] - tem2[5];
  93207. te[6] = tem1[6] - tem2[6]; te[7] = tem1[7] - tem2[7]; te[8] = tem1[8] - tem2[8];
  93208. return this;
  93209. },
  93210. subEqual: function (m) {
  93211. var te = this.elements, tem = m.elements;
  93212. te[0] -= tem[0]; te[1] -= tem[1]; te[2] -= tem[2];
  93213. te[3] -= tem[3]; te[4] -= tem[4]; te[5] -= tem[5];
  93214. te[6] -= tem[6]; te[7] -= tem[7]; te[8] -= tem[8];
  93215. return this;
  93216. },
  93217. scale: function (m, s) {
  93218. var te = this.elements, tm = m.elements;
  93219. te[0] = tm[0] * s; te[1] = tm[1] * s; te[2] = tm[2] * s;
  93220. te[3] = tm[3] * s; te[4] = tm[4] * s; te[5] = tm[5] * s;
  93221. te[6] = tm[6] * s; te[7] = tm[7] * s; te[8] = tm[8] * s;
  93222. return this;
  93223. },
  93224. scaleEqual: function (s) {
  93225. var te = this.elements;
  93226. te[0] *= s; te[1] *= s; te[2] *= s;
  93227. te[3] *= s; te[4] *= s; te[5] *= s;
  93228. te[6] *= s; te[7] *= s; te[8] *= s;
  93229. return this;
  93230. },
  93231. mul: function (m1, m2) {
  93232. var te = this.elements, tm1 = m1.elements, tm2 = m2.elements,
  93233. a0 = tm1[0], a3 = tm1[3], a6 = tm1[6],
  93234. a1 = tm1[1], a4 = tm1[4], a7 = tm1[7],
  93235. a2 = tm1[2], a5 = tm1[5], a8 = tm1[8],
  93236. b0 = tm2[0], b3 = tm2[3], b6 = tm2[6],
  93237. b1 = tm2[1], b4 = tm2[4], b7 = tm2[7],
  93238. b2 = tm2[2], b5 = tm2[5], b8 = tm2[8];
  93239. te[0] = a0 * b0 + a1 * b3 + a2 * b6;
  93240. te[1] = a0 * b1 + a1 * b4 + a2 * b7;
  93241. te[2] = a0 * b2 + a1 * b5 + a2 * b8;
  93242. te[3] = a3 * b0 + a4 * b3 + a5 * b6;
  93243. te[4] = a3 * b1 + a4 * b4 + a5 * b7;
  93244. te[5] = a3 * b2 + a4 * b5 + a5 * b8;
  93245. te[6] = a6 * b0 + a7 * b3 + a8 * b6;
  93246. te[7] = a6 * b1 + a7 * b4 + a8 * b7;
  93247. te[8] = a6 * b2 + a7 * b5 + a8 * b8;
  93248. return this;
  93249. },
  93250. mulScale: function (m, sx, sy, sz, Prepend) {
  93251. var prepend = Prepend || false;
  93252. var te = this.elements, tm = m.elements;
  93253. if (prepend) {
  93254. te[0] = sx * tm[0]; te[1] = sx * tm[1]; te[2] = sx * tm[2];
  93255. te[3] = sy * tm[3]; te[4] = sy * tm[4]; te[5] = sy * tm[5];
  93256. te[6] = sz * tm[6]; te[7] = sz * tm[7]; te[8] = sz * tm[8];
  93257. } else {
  93258. te[0] = tm[0] * sx; te[1] = tm[1] * sy; te[2] = tm[2] * sz;
  93259. te[3] = tm[3] * sx; te[4] = tm[4] * sy; te[5] = tm[5] * sz;
  93260. te[6] = tm[6] * sx; te[7] = tm[7] * sy; te[8] = tm[8] * sz;
  93261. }
  93262. return this;
  93263. },
  93264. mulRotate: function (m, rad, ax, ay, az, Prepend) {
  93265. var prepend = Prepend || false;
  93266. var s = OIMO.sin(rad);
  93267. var c = OIMO.cos(rad);
  93268. var c1 = 1 - c;
  93269. var r00 = ax * ax * c1 + c;
  93270. var r01 = ax * ay * c1 - az * s;
  93271. var r02 = ax * az * c1 + ay * s;
  93272. var r10 = ay * ax * c1 + az * s;
  93273. var r11 = ay * ay * c1 + c;
  93274. var r12 = ay * az * c1 - ax * s;
  93275. var r20 = az * ax * c1 - ay * s;
  93276. var r21 = az * ay * c1 + ax * s;
  93277. var r22 = az * az * c1 + c;
  93278. var tm = m.elements;
  93279. var a0 = tm[0], a3 = tm[3], a6 = tm[6];
  93280. var a1 = tm[1], a4 = tm[4], a7 = tm[7];
  93281. var a2 = tm[2], a5 = tm[5], a8 = tm[8];
  93282. var te = this.elements;
  93283. if (prepend) {
  93284. te[0] = r00 * a0 + r01 * a3 + r02 * a6;
  93285. te[1] = r00 * a1 + r01 * a4 + r02 * a7;
  93286. te[2] = r00 * a2 + r01 * a5 + r02 * a8;
  93287. te[3] = r10 * a0 + r11 * a3 + r12 * a6;
  93288. te[4] = r10 * a1 + r11 * a4 + r12 * a7;
  93289. te[5] = r10 * a2 + r11 * a5 + r12 * a8;
  93290. te[6] = r20 * a0 + r21 * a3 + r22 * a6;
  93291. te[7] = r20 * a1 + r21 * a4 + r22 * a7;
  93292. te[8] = r20 * a2 + r21 * a5 + r22 * a8;
  93293. } else {
  93294. te[0] = a0 * r00 + a1 * r10 + a2 * r20;
  93295. te[1] = a0 * r01 + a1 * r11 + a2 * r21;
  93296. te[2] = a0 * r02 + a1 * r12 + a2 * r22;
  93297. te[3] = a3 * r00 + a4 * r10 + a5 * r20;
  93298. te[4] = a3 * r01 + a4 * r11 + a5 * r21;
  93299. te[5] = a3 * r02 + a4 * r12 + a5 * r22;
  93300. te[6] = a6 * r00 + a7 * r10 + a8 * r20;
  93301. te[7] = a6 * r01 + a7 * r11 + a8 * r21;
  93302. te[8] = a6 * r02 + a7 * r12 + a8 * r22;
  93303. }
  93304. return this;
  93305. },
  93306. transpose: function (m) {
  93307. var te = this.elements, tm = m.elements;
  93308. te[0] = tm[0]; te[1] = tm[3]; te[2] = tm[6];
  93309. te[3] = tm[1]; te[4] = tm[4]; te[5] = tm[7];
  93310. te[6] = tm[2]; te[7] = tm[5]; te[8] = tm[8];
  93311. return this;
  93312. },
  93313. setQuat: function (q) {
  93314. var te = this.elements,
  93315. x2 = 2 * q.x, y2 = 2 * q.y, z2 = 2 * q.z,
  93316. xx = q.x * x2, yy = q.y * y2, zz = q.z * z2,
  93317. xy = q.x * y2, yz = q.y * z2, xz = q.x * z2,
  93318. sx = q.s * x2, sy = q.s * y2, sz = q.s * z2;
  93319. te[0] = 1 - yy - zz;
  93320. te[1] = xy - sz;
  93321. te[2] = xz + sy;
  93322. te[3] = xy + sz;
  93323. te[4] = 1 - xx - zz;
  93324. te[5] = yz - sx;
  93325. te[6] = xz - sy;
  93326. te[7] = yz + sx;
  93327. te[8] = 1 - xx - yy;
  93328. return this;
  93329. },
  93330. invert: function (m) {
  93331. var te = this.elements, tm = m.elements,
  93332. a0 = tm[0], a3 = tm[3], a6 = tm[6],
  93333. a1 = tm[1], a4 = tm[4], a7 = tm[7],
  93334. a2 = tm[2], a5 = tm[5], a8 = tm[8],
  93335. b01 = a4 * a8 - a7 * a5,
  93336. b11 = a7 * a2 - a1 * a8,
  93337. b21 = a1 * a5 - a4 * a2,
  93338. dt = a0 * (b01) + a3 * (b11) + a6 * (b21);
  93339. if (dt != 0) { dt = 1.0 / dt; }
  93340. te[0] = dt * b01;//(a4*a8 - a5*a7);
  93341. te[1] = dt * b11;//(a2*a7 - a1*a8);
  93342. te[2] = dt * b21;//(a1*a5 - a2*a4);
  93343. te[3] = dt * (a5 * a6 - a3 * a8);
  93344. te[4] = dt * (a0 * a8 - a2 * a6);
  93345. te[5] = dt * (a2 * a3 - a0 * a5);
  93346. te[6] = dt * (a3 * a7 - a4 * a6);
  93347. te[7] = dt * (a1 * a6 - a0 * a7);
  93348. te[8] = dt * (a0 * a4 - a1 * a3);
  93349. return this;
  93350. },
  93351. /*copy: function(m){
  93352. var te = this.elements, tem = m.elements;
  93353. te[0] = tem[0]; te[1] = tem[1]; te[2] = tem[2];
  93354. te[3] = tem[3]; te[4] = tem[4]; te[5] = tem[5];
  93355. te[6] = tem[6]; te[7] = tem[7]; te[8] = tem[8];
  93356. return this;
  93357. },*/
  93358. toEuler: function () { // not work !!
  93359. function clamp(x) {
  93360. return OIMO.min(OIMO.max(x, -1), 1);
  93361. }
  93362. var te = this.elements;
  93363. var m11 = te[0], m12 = te[3], m13 = te[6];
  93364. var m21 = te[1], m22 = te[4], m23 = te[7];
  93365. var m31 = te[2], m32 = te[5], m33 = te[8];
  93366. var p = new OIMO.Vec3();
  93367. var d = new OIMO.Quat();
  93368. var s;
  93369. p.y = OIMO.asin(clamp(m13));
  93370. if (OIMO.abs(m13) < 0.99999) {
  93371. p.x = OIMO.atan2(-m23, m33);
  93372. p.z = OIMO.atan2(-m12, m11);
  93373. } else {
  93374. p.x = OIMO.atan2(m32, m22);
  93375. p.z = 0;
  93376. }
  93377. return p;
  93378. },
  93379. /*clone: function(){
  93380. var te = this.elements;
  93381. return new OIMO.Mat33(
  93382. te[0], te[1], te[2],
  93383. te[3], te[4], te[5],
  93384. te[6], te[7], te[8]
  93385. );
  93386. },*/
  93387. toString: function () {
  93388. var te = this.elements;
  93389. var text =
  93390. "Mat33|" + te[0].toFixed(4) + ", " + te[1].toFixed(4) + ", " + te[2].toFixed(4) + "|\n" +
  93391. " |" + te[3].toFixed(4) + ", " + te[4].toFixed(4) + ", " + te[5].toFixed(4) + "|\n" +
  93392. " |" + te[6].toFixed(4) + ", " + te[7].toFixed(4) + ", " + te[8].toFixed(4) + "|";
  93393. return text;
  93394. },
  93395. // OK
  93396. multiplyScalar: function (s) {
  93397. var te = this.elements;
  93398. te[0] *= s; te[3] *= s; te[6] *= s;
  93399. te[1] *= s; te[4] *= s; te[7] *= s;
  93400. te[2] *= s; te[5] *= s; te[8] *= s;
  93401. return this;
  93402. },
  93403. identity: function () {
  93404. this.set(1, 0, 0, 0, 1, 0, 0, 0, 1);
  93405. return this;
  93406. },
  93407. clone: function () {
  93408. return new this.constructor().fromArray(this.elements);
  93409. },
  93410. copy: function (m) {
  93411. var me = m.elements;
  93412. this.set(
  93413. me[0], me[3], me[6],
  93414. me[1], me[4], me[7],
  93415. me[2], me[5], me[8]
  93416. );
  93417. return this;
  93418. },
  93419. fromArray: function (array) {
  93420. this.elements.set(array);
  93421. return this;
  93422. },
  93423. toArray: function () {
  93424. var te = this.elements;
  93425. return [
  93426. te[0], te[1], te[2],
  93427. te[3], te[4], te[5],
  93428. te[6], te[7], te[8]
  93429. ];
  93430. }
  93431. };
  93432. OIMO.Quat = function (s, x, y, z) {
  93433. this.s = (s !== undefined) ? s : 1;
  93434. this.x = x || 0;
  93435. this.y = y || 0;
  93436. this.z = z || 0;
  93437. };
  93438. OIMO.Quat.prototype = {
  93439. constructor: OIMO.Quat,
  93440. set: function (x, y, z, w) {
  93441. this.x = x;
  93442. this.y = y;
  93443. this.z = z;
  93444. this.s = w;
  93445. return this;
  93446. },
  93447. init: function (s, x, y, z) {
  93448. this.s = (s !== undefined) ? s : 1;
  93449. this.x = x || 0;
  93450. this.y = y || 0;
  93451. this.z = z || 0;
  93452. return this;
  93453. },
  93454. add: function (q1, q2) {
  93455. this.s = q1.s + q2.s;
  93456. this.x = q1.x + q2.x;
  93457. this.y = q1.y + q2.y;
  93458. this.z = q1.z + q2.z;
  93459. return this;
  93460. },
  93461. addTime: function (v, t) {
  93462. var x = v.x;
  93463. var y = v.y;
  93464. var z = v.z;
  93465. var qs = this.s;
  93466. var qx = this.x;
  93467. var qy = this.y;
  93468. var qz = this.z;
  93469. t *= 0.5;
  93470. var ns = (-x * qx - y * qy - z * qz) * t;
  93471. var nx = (x * qs + y * qz - z * qy) * t;
  93472. var ny = (-x * qz + y * qs + z * qx) * t;
  93473. var nz = (x * qy - y * qx + z * qs) * t;
  93474. qs += ns;
  93475. qx += nx;
  93476. qy += ny;
  93477. qz += nz;
  93478. var s = 1 / OIMO.sqrt(qs * qs + qx * qx + qy * qy + qz * qz);
  93479. this.s = qs * s;
  93480. this.x = qx * s;
  93481. this.y = qy * s;
  93482. this.z = qz * s;
  93483. return this;
  93484. },
  93485. sub: function (q1, q2) {
  93486. this.s = q1.s - q2.s;
  93487. this.x = q1.x - q2.x;
  93488. this.y = q1.y - q2.y;
  93489. this.z = q1.z - q2.z;
  93490. return this;
  93491. },
  93492. scale: function (q, s) {
  93493. this.s = q.s * s;
  93494. this.x = q.x * s;
  93495. this.y = q.y * s;
  93496. this.z = q.z * s;
  93497. return this;
  93498. },
  93499. mul: function (q1, q2) {
  93500. var ax = q1.x, ay = q1.y, az = q1.z, as = q1.s,
  93501. bx = q2.x, by = q2.y, bz = q2.z, bs = q2.s;
  93502. this.x = ax * bs + as * bx + ay * bz - az * by;
  93503. this.y = ay * bs + as * by + az * bx - ax * bz;
  93504. this.z = az * bs + as * bz + ax * by - ay * bx;
  93505. this.s = as * bs - ax * bx - ay * by - az * bz;
  93506. return this;
  93507. },
  93508. arc: function (v1, v2) {
  93509. var x1 = v1.x;
  93510. var y1 = v1.y;
  93511. var z1 = v1.z;
  93512. var x2 = v2.x;
  93513. var y2 = v2.y;
  93514. var z2 = v2.z;
  93515. var d = x1 * x2 + y1 * y2 + z1 * z2;
  93516. if (d == -1) {
  93517. x2 = y1 * x1 - z1 * z1;
  93518. y2 = -z1 * y1 - x1 * x1;
  93519. z2 = x1 * z1 + y1 * y1;
  93520. d = 1 / OIMO.sqrt(x2 * x2 + y2 * y2 + z2 * z2);
  93521. this.s = 0;
  93522. this.x = x2 * d;
  93523. this.y = y2 * d;
  93524. this.z = z2 * d;
  93525. return this;
  93526. }
  93527. var cx = y1 * z2 - z1 * y2;
  93528. var cy = z1 * x2 - x1 * z2;
  93529. var cz = x1 * y2 - y1 * x2;
  93530. this.s = OIMO.sqrt((1 + d) * 0.5);
  93531. d = 0.5 / this.s;
  93532. this.x = cx * d;
  93533. this.y = cy * d;
  93534. this.z = cz * d;
  93535. return this;
  93536. },
  93537. normalize: function (q) {
  93538. var len = OIMO.sqrt(q.s * q.s + q.x * q.x + q.y * q.y + q.z * q.z);
  93539. if (len > 0) { len = 1 / len; }
  93540. this.s = q.s * len;
  93541. this.x = q.x * len;
  93542. this.y = q.y * len;
  93543. this.z = q.z * len;
  93544. return this;
  93545. },
  93546. invert: function (q) {
  93547. this.s = q.s;
  93548. this.x = -q.x;
  93549. this.y = -q.y;
  93550. this.z = -q.z;
  93551. return this;
  93552. },
  93553. length: function () {
  93554. return OIMO.sqrt(this.s * this.s + this.x * this.x + this.y * this.y + this.z * this.z);
  93555. },
  93556. copy: function (q) {
  93557. this.s = q.s;
  93558. this.x = q.x;
  93559. this.y = q.y;
  93560. this.z = q.z;
  93561. return this;
  93562. },
  93563. testDiff: function (q) {
  93564. if (this.s !== q.s || this.x !== q.x || this.y !== q.y || this.z !== q.z) return true;
  93565. else return false;
  93566. },
  93567. clone: function (q) {
  93568. return new OIMO.Quat(this.s, this.x, this.y, this.z);
  93569. },
  93570. toString: function () {
  93571. return "Quat[" + this.s.toFixed(4) + ", (" + this.x.toFixed(4) + ", " + this.y.toFixed(4) + ", " + this.z.toFixed(4) + ")]";
  93572. }
  93573. }
  93574. // for three easy export
  93575. OIMO.Quaternion = function (x, y, z, w) {
  93576. this.x = x || 0;
  93577. this.y = y || 0;
  93578. this.z = z || 0;
  93579. this.w = (w !== undefined) ? w : 1;
  93580. };
  93581. OIMO.Quaternion.prototype = {
  93582. constructor: OIMO.Quaternion,
  93583. setFromRotationMatrix: function (m) {
  93584. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  93585. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  93586. var te = m.elements,
  93587. m11 = te[0], m12 = te[1], m13 = te[2],
  93588. m21 = te[3], m22 = te[4], m23 = te[5],
  93589. m31 = te[6], m32 = te[7], m33 = te[8],
  93590. trace = m11 + m22 + m33,
  93591. s;
  93592. if (trace > 0) {
  93593. s = 0.5 / OIMO.sqrt(trace + 1.0);
  93594. this.w = 0.25 / s;
  93595. this.x = (m32 - m23) * s;
  93596. this.y = (m13 - m31) * s;
  93597. this.z = (m21 - m12) * s;
  93598. } else if (m11 > m22 && m11 > m33) {
  93599. s = 2.0 * OIMO.sqrt(1.0 + m11 - m22 - m33);
  93600. this.w = (m32 - m23) / s;
  93601. this.x = 0.25 * s;
  93602. this.y = (m12 + m21) / s;
  93603. this.z = (m13 + m31) / s;
  93604. } else if (m22 > m33) {
  93605. s = 2.0 * OIMO.sqrt(1.0 + m22 - m11 - m33);
  93606. this.w = (m13 - m31) / s;
  93607. this.x = (m12 + m21) / s;
  93608. this.y = 0.25 * s;
  93609. this.z = (m23 + m32) / s;
  93610. } else {
  93611. s = 2.0 * OIMO.sqrt(1.0 + m33 - m11 - m22);
  93612. this.w = (m21 - m12) / s;
  93613. this.x = (m13 + m31) / s;
  93614. this.y = (m23 + m32) / s;
  93615. this.z = 0.25 * s;
  93616. }
  93617. //this.onChangeCallback();
  93618. return this;
  93619. }
  93620. }
  93621. OIMO.Vec3 = function (x, y, z) {
  93622. this.x = x || 0;
  93623. this.y = y || 0;
  93624. this.z = z || 0;
  93625. };
  93626. OIMO.Vec3.prototype = {
  93627. constructor: OIMO.Vec3,
  93628. init: function (x, y, z) {
  93629. this.x = x || 0;
  93630. this.y = y || 0;
  93631. this.z = z || 0;
  93632. return this;
  93633. },
  93634. set: function (x, y, z) {
  93635. this.x = x;
  93636. this.y = y;
  93637. this.z = z;
  93638. return this;
  93639. },
  93640. add: function (v1, v2) {
  93641. this.x = v1.x + v2.x;
  93642. this.y = v1.y + v2.y;
  93643. this.z = v1.z + v2.z;
  93644. return this;
  93645. },
  93646. addEqual: function (v) {
  93647. this.x += v.x;
  93648. this.y += v.y;
  93649. this.z += v.z;
  93650. return this;
  93651. },
  93652. addTime: function (v, t) {
  93653. this.x += v.x * t;
  93654. this.y += v.y * t;
  93655. this.z += v.z * t;
  93656. return this;
  93657. },
  93658. sub: function (v1, v2) {
  93659. this.x = v1.x - v2.x;
  93660. this.y = v1.y - v2.y;
  93661. this.z = v1.z - v2.z;
  93662. return this;
  93663. },
  93664. subEqual: function (v) {
  93665. this.x -= v.x;
  93666. this.y -= v.y;
  93667. this.z -= v.z;
  93668. return this;
  93669. },
  93670. addScale: function (v, s) {
  93671. this.x += v.x * s;
  93672. this.y += v.y * s;
  93673. this.z += v.z * s;
  93674. return this;
  93675. },
  93676. scale: function (v, s) {
  93677. this.x = v.x * s;
  93678. this.y = v.y * s;
  93679. this.z = v.z * s;
  93680. return this;
  93681. },
  93682. scaleEqual: function (s) {
  93683. this.x *= s;
  93684. this.y *= s;
  93685. this.z *= s;
  93686. return this;
  93687. },
  93688. /*dot: function(v){
  93689. return this.x*v.x+this.y*v.y+this.z*v.z;
  93690. },*/
  93691. cross: function (v1, v2) {
  93692. var ax = v1.x, ay = v1.y, az = v1.z,
  93693. bx = v2.x, by = v2.y, bz = v2.z;
  93694. this.x = ay * bz - az * by;
  93695. this.y = az * bx - ax * bz;
  93696. this.z = ax * by - ay * bx;
  93697. return this;
  93698. },
  93699. mul: function (o, v, m) {
  93700. var te = m.elements;
  93701. this.x = o.x + v.x * te[0] + v.y * te[1] + v.z * te[2];
  93702. this.y = o.y + v.x * te[3] + v.y * te[4] + v.z * te[5];
  93703. this.z = o.z + v.x * te[6] + v.y * te[7] + v.z * te[8];
  93704. return this;
  93705. },
  93706. mulMat: function (m, v) {
  93707. var te = m.elements;
  93708. this.x = te[0] * v.x + te[1] * v.y + te[2] * v.z;
  93709. this.y = te[3] * v.x + te[4] * v.y + te[5] * v.z;
  93710. this.z = te[6] * v.x + te[7] * v.y + te[8] * v.z;
  93711. return this;
  93712. },
  93713. normalize: function (v) {
  93714. var x = v.x, y = v.y, z = v.z;
  93715. var l = x * x + y * y + z * z;
  93716. if (l > 0) {
  93717. l = 1 / OIMO.sqrt(l);
  93718. this.x = x * l;
  93719. this.y = y * l;
  93720. this.z = z * l;
  93721. }
  93722. return this;
  93723. },
  93724. /*norm: function(){
  93725. var x = this.x, y = this.y, z = this.z;
  93726. var l = x*x + y*y + z*z;
  93727. if (l > 0) {
  93728. l = 1 / OIMO.sqrt(l);
  93729. this.x = x*l;
  93730. this.y = y*l;
  93731. this.z = z*l;
  93732. }
  93733. return this;
  93734. },*/
  93735. invert: function (v) {
  93736. this.x = -v.x;
  93737. this.y = -v.y;
  93738. this.z = -v.z;
  93739. return this;
  93740. },
  93741. /*length: function(){
  93742. var x = this.x, y = this.y, z = this.z;
  93743. return OIMO.sqrt(x*x + y*y + z*z);
  93744. },*/
  93745. negate: function () {
  93746. this.x = -this.x;
  93747. this.y = -this.y;
  93748. this.z = -this.z;
  93749. return this;
  93750. },
  93751. dot: function (v) {
  93752. return this.x * v.x + this.y * v.y + this.z * v.z;
  93753. },
  93754. lengthSq: function () {
  93755. return this.x * this.x + this.y * this.y + this.z * this.z;
  93756. },
  93757. length: function () {
  93758. return OIMO.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  93759. },
  93760. /*len: function(){
  93761. var x = this.x, y = this.y, z = this.z;
  93762. return x*x + y*y + z*z;
  93763. },*/
  93764. copy: function (v) {
  93765. this.x = v.x;
  93766. this.y = v.y;
  93767. this.z = v.z;
  93768. return this;
  93769. },
  93770. applyQuaternion: function (q) {
  93771. var x = this.x;
  93772. var y = this.y;
  93773. var z = this.z;
  93774. var qx = q.x;
  93775. var qy = q.y;
  93776. var qz = q.z;
  93777. var qs = q.s;
  93778. // calculate quat * vector
  93779. var ix = qs * x + qy * z - qz * y;
  93780. var iy = qs * y + qz * x - qx * z;
  93781. var iz = qs * z + qx * y - qy * x;
  93782. var iw = -qx * x - qy * y - qz * z;
  93783. // calculate result * inverse quat
  93784. this.x = ix * qs + iw * -qx + iy * -qz - iz * -qy;
  93785. this.y = iy * qs + iw * -qy + iz * -qx - ix * -qz;
  93786. this.z = iz * qs + iw * -qz + ix * -qy - iy * -qx;
  93787. return this;
  93788. },
  93789. testZero: function () {
  93790. if (this.x !== 0 || this.y !== 0 || this.z !== 0) return true;
  93791. else return false;
  93792. },
  93793. testDiff: function (v) {
  93794. return ((v.x !== this.x) || (v.y !== this.y) || (v.z !== this.z));
  93795. //if(this.x!==v.x || this.y!==v.y || this.z!==v.z) return true;
  93796. //else return false;
  93797. },
  93798. equals: function (v) {
  93799. return ((v.x === this.x) && (v.y === this.y) && (v.z === this.z));
  93800. },
  93801. clone: function () {
  93802. return new this.constructor(this.x, this.y, this.z);
  93803. },
  93804. toString: function () {
  93805. return "Vec3[" + this.x.toFixed(4) + ", " + this.y.toFixed(4) + ", " + this.z.toFixed(4) + "]";
  93806. },
  93807. multiplyScalar: function (scalar) {
  93808. if (isFinite(scalar)) {
  93809. this.x *= scalar;
  93810. this.y *= scalar;
  93811. this.z *= scalar;
  93812. } else {
  93813. this.x = 0;
  93814. this.y = 0;
  93815. this.z = 0;
  93816. }
  93817. return this;
  93818. },
  93819. divideScalar: function (scalar) {
  93820. return this.multiplyScalar(1 / scalar);
  93821. },
  93822. // TODO rename to normalize
  93823. norm: function () {
  93824. return this.divideScalar(this.length());
  93825. },
  93826. }
  93827. OIMO.Euler = function (x, y, z, order) {
  93828. this._x = x || 0;
  93829. this._y = y || 0;
  93830. this._z = z || 0;
  93831. this._order = order || OIMO.Euler.DefaultOrder;
  93832. };
  93833. OIMO.Euler.RotationOrders = ['XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX'];
  93834. OIMO.Euler.DefaultOrder = 'XYZ';
  93835. OIMO.clamp = function (x, a, b) {
  93836. return (x < a) ? a : ((x > b) ? b : x);
  93837. }
  93838. OIMO.Euler.prototype = {
  93839. constructor: OIMO.Euler,
  93840. _x: 0, _y: 0, _z: 0, _order: OIMO.Euler.DefaultOrder,
  93841. get x() {
  93842. return this._x;
  93843. },
  93844. set x(value) {
  93845. this._x = value;
  93846. this.onChangeCallback();
  93847. },
  93848. get y() {
  93849. return this._y;
  93850. },
  93851. set y(value) {
  93852. this._y = value;
  93853. this.onChangeCallback();
  93854. },
  93855. get z() {
  93856. return this._z;
  93857. },
  93858. set z(value) {
  93859. this._z = value;
  93860. this.onChangeCallback();
  93861. },
  93862. get order() {
  93863. return this._order;
  93864. },
  93865. set order(value) {
  93866. this._order = value;
  93867. this.onChangeCallback();
  93868. },
  93869. set: function (x, y, z, order) {
  93870. this._x = x;
  93871. this._y = y;
  93872. this._z = z;
  93873. this._order = order || this._order;
  93874. this.onChangeCallback();
  93875. return this;
  93876. },
  93877. copy: function (euler) {
  93878. this._x = euler._x;
  93879. this._y = euler._y;
  93880. this._z = euler._z;
  93881. this._order = euler._order;
  93882. this.onChangeCallback();
  93883. return this;
  93884. },
  93885. setFromRotationMatrix: function (m, order) {
  93886. var clamp = OIMO.clamp;
  93887. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  93888. var te = m.elements;
  93889. /*var m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ];
  93890. var m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ];
  93891. var m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];*/
  93892. var m11 = te[0], m12 = te[1], m13 = te[2],
  93893. m21 = te[3], m22 = te[4], m23 = te[5],
  93894. m31 = te[6], m32 = te[7], m33 = te[8];
  93895. order = order || this._order;
  93896. if (order === 'XYZ') {
  93897. this._y = OIMO.asin(clamp(m13, -1, 1));
  93898. if (OIMO.abs(m13) < 0.99999) {
  93899. this._x = OIMO.atan2(-m23, m33);
  93900. this._z = OIMO.atan2(-m12, m11);
  93901. } else {
  93902. this._x = OIMO.atan2(m32, m22);
  93903. this._z = 0;
  93904. }
  93905. } else if (order === 'YXZ') {
  93906. this._x = OIMO.asin(-clamp(m23, -1, 1));
  93907. if (OIMO.abs(m23) < 0.99999) {
  93908. this._y = OIMO.atan2(m13, m33);
  93909. this._z = OIMO.atan2(m21, m22);
  93910. } else {
  93911. this._y = OIMO.atan2(-m31, m11);
  93912. this._z = 0;
  93913. }
  93914. } else if (order === 'ZXY') {
  93915. this._x = OIMO.asin(clamp(m32, -1, 1));
  93916. if (OIMO.abs(m32) < 0.99999) {
  93917. this._y = OIMO.atan2(-m31, m33);
  93918. this._z = OIMO.atan2(-m12, m22);
  93919. } else {
  93920. this._y = 0;
  93921. this._z = OIMO.atan2(m21, m11);
  93922. }
  93923. } else if (order === 'ZYX') {
  93924. this._y = OIMO.asin(-clamp(m31, -1, 1));
  93925. if (OIMO.abs(m31) < 0.99999) {
  93926. this._x = OIMO.atan2(m32, m33);
  93927. this._z = OIMO.atan2(m21, m11);
  93928. } else {
  93929. this._x = 0;
  93930. this._z = OIMO.atan2(-m12, m22);
  93931. }
  93932. } else if (order === 'YZX') {
  93933. this._z = OIMO.asin(clamp(m21, -1, 1));
  93934. if (OIMO.abs(m21) < 0.99999) {
  93935. this._x = OIMO.atan2(-m23, m22);
  93936. this._y = OIMO.atan2(-m31, m11);
  93937. } else {
  93938. this._x = 0;
  93939. this._y = OIMO.atan2(m13, m33);
  93940. }
  93941. } else if (order === 'XZY') {
  93942. this._z = OIMO.asin(-clamp(m12, -1, 1));
  93943. if (OIMO.abs(m12) < 0.99999) {
  93944. this._x = OIMO.atan2(m32, m22);
  93945. this._y = OIMO.atan2(m13, m11);
  93946. } else {
  93947. this._x = OIMO.atan2(-m23, m33);
  93948. this._y = 0;
  93949. }
  93950. } else {
  93951. console.warn('THREE.Euler: .setFromRotationMatrix() given unsupported order: ' + order)
  93952. }
  93953. this._order = order;
  93954. this.onChangeCallback();
  93955. return this;
  93956. },
  93957. setFromQuaternion: function (q, order, update) {
  93958. var clamp = OIMO.clamp;
  93959. // q is assumed to be normalized
  93960. // http://www.mathworks.com/matlabcentral/fileexchange/20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/content/SpinCalc.m
  93961. var sqx = q.x * q.x;
  93962. var sqy = q.y * q.y;
  93963. var sqz = q.z * q.z;
  93964. var sqw = q.s * q.s;
  93965. order = order || this._order;
  93966. if (order === 'XYZ') {
  93967. this._x = OIMO.atan2(2 * (q.x * q.s - q.y * q.z), (sqw - sqx - sqy + sqz));
  93968. this._y = OIMO.asin(clamp(2 * (q.x * q.z + q.y * q.s), -1, 1));
  93969. this._z = OIMO.atan2(2 * (q.z * q.s - q.x * q.y), (sqw + sqx - sqy - sqz));
  93970. } else if (order === 'YXZ') {
  93971. this._x = OIMO.asin(clamp(2 * (q.x * q.s - q.y * q.z), -1, 1));
  93972. this._y = OIMO.atan2(2 * (q.x * q.z + q.y * q.s), (sqw - sqx - sqy + sqz));
  93973. this._z = OIMO.atan2(2 * (q.x * q.y + q.z * q.s), (sqw - sqx + sqy - sqz));
  93974. } else if (order === 'ZXY') {
  93975. this._x = OIMO.asin(clamp(2 * (q.x * q.s + q.y * q.z), -1, 1));
  93976. this._y = OIMO.atan2(2 * (q.y * q.s - q.z * q.x), (sqw - sqx - sqy + sqz));
  93977. this._z = OIMO.atan2(2 * (q.z * q.s - q.x * q.y), (sqw - sqx + sqy - sqz));
  93978. } else if (order === 'ZYX') {
  93979. this._x = OIMO.atan2(2 * (q.x * q.s + q.z * q.y), (sqw - sqx - sqy + sqz));
  93980. this._y = OIMO.asin(clamp(2 * (q.y * q.s - q.x * q.z), -1, 1));
  93981. this._z = OIMO.atan2(2 * (q.x * q.y + q.z * q.s), (sqw + sqx - sqy - sqz));
  93982. } else if (order === 'YZX') {
  93983. this._x = OIMO.atan2(2 * (q.x * q.s - q.z * q.y), (sqw - sqx + sqy - sqz));
  93984. this._y = OIMO.atan2(2 * (q.y * q.s - q.x * q.z), (sqw + sqx - sqy - sqz));
  93985. this._z = OIMO.asin(clamp(2 * (q.x * q.y + q.z * q.s), -1, 1));
  93986. } else if (order === 'XZY') {
  93987. this._x = OIMO.atan2(2 * (q.x * q.s + q.y * q.z), (sqw - sqx + sqy - sqz));
  93988. this._y = OIMO.atan2(2 * (q.x * q.z + q.y * q.s), (sqw + sqx - sqy - sqz));
  93989. this._z = OIMO.asin(clamp(2 * (q.z * q.s - q.x * q.y), -1, 1));
  93990. } else {
  93991. console.warn('OIMO.Euler: .setFromQuaternion() given unsupported order: ' + order)
  93992. }
  93993. this._order = order;
  93994. if (update !== false) this.onChangeCallback();
  93995. return this;
  93996. },
  93997. reorder: function () {
  93998. // WARNING: this discards revolution information -bhouston
  93999. var q = new OIMO.Quat();
  94000. return function (newOrder) {
  94001. q.setFromEuler(this);
  94002. this.setFromQuaternion(q, newOrder);
  94003. };
  94004. }(),
  94005. equals: function (euler) {
  94006. return (euler._x === this._x) && (euler._y === this._y) && (euler._z === this._z) && (euler._order === this._order);
  94007. },
  94008. fromArray: function (array) {
  94009. this._x = array[0];
  94010. this._y = array[1];
  94011. this._z = array[2];
  94012. if (array[3] !== undefined) this._order = array[3];
  94013. this.onChangeCallback();
  94014. return this;
  94015. },
  94016. toArray: function () {
  94017. return [this._x, this._y, this._z, this._order];
  94018. },
  94019. onChange: function (callback) {
  94020. this.onChangeCallback = callback;
  94021. return this;
  94022. },
  94023. onChangeCallback: function () { },
  94024. clone: function () {
  94025. return new OIMO.Euler(this._x, this._y, this._z, this._order);
  94026. }
  94027. };
  94028. OIMO.EulerToAxis = function (ox, oy, oz) {// angles in radians
  94029. var c1 = OIMO.cos(oy * 0.5);//heading
  94030. var s1 = OIMO.sin(oy * 0.5);
  94031. var c2 = OIMO.cos(oz * 0.5);//altitude
  94032. var s2 = OIMO.sin(oz * 0.5);
  94033. var c3 = OIMO.cos(ox * 0.5);//bank
  94034. var s3 = OIMO.sin(ox * 0.5);
  94035. var c1c2 = c1 * c2;
  94036. var s1s2 = s1 * s2;
  94037. var w = c1c2 * c3 - s1s2 * s3;
  94038. var x = c1c2 * s3 + s1s2 * c3;
  94039. var y = s1 * c2 * c3 + c1 * s2 * s3;
  94040. var z = c1 * s2 * c3 - s1 * c2 * s3;
  94041. var angle = 2 * OIMO.acos(w);
  94042. var norm = x * x + y * y + z * z;
  94043. if (norm < 0.001) {
  94044. x = 1;
  94045. y = z = 0;
  94046. } else {
  94047. norm = OIMO.sqrt(norm);
  94048. x /= norm;
  94049. y /= norm;
  94050. z /= norm;
  94051. }
  94052. return [angle, x, y, z];
  94053. }
  94054. OIMO.EulerToMatrix = function (ox, oy, oz) {// angles in radians
  94055. var ch = OIMO.cos(oy);//heading
  94056. var sh = OIMO.sin(oy);
  94057. var ca = OIMO.cos(oz);//altitude
  94058. var sa = OIMO.sin(oz);
  94059. var cb = OIMO.cos(ox);//bank
  94060. var sb = OIMO.sin(ox);
  94061. var mtx = new OIMO.Mat33();
  94062. var te = mtx.elements;
  94063. te[0] = ch * ca;
  94064. te[1] = sh * sb - ch * sa * cb;
  94065. te[2] = ch * sa * sb + sh * cb;
  94066. te[3] = sa;
  94067. te[4] = ca * cb;
  94068. te[5] = -ca * sb;
  94069. te[6] = -sh * ca;
  94070. te[7] = sh * sa * cb + ch * sb;
  94071. te[8] = -sh * sa * sb + ch * cb;
  94072. return mtx;
  94073. }
  94074. OIMO.MatrixToEuler = function (mtx) {// angles in radians
  94075. var te = mtx.elements;
  94076. var x, y, z;
  94077. if (te[3] > 0.998) { // singularity at north pole
  94078. y = OIMO.atan2(te[2], te[8]);
  94079. z = OIMO.PI / 2;
  94080. x = 0;
  94081. } else if (te[3] < -0.998) { // singularity at south pole
  94082. y = OIMO.atan2(te[2], te[8]);
  94083. z = -OIMO.PI / 2;
  94084. x = 0;
  94085. } else {
  94086. y = OIMO.atan2(-te[6], te[0]);
  94087. x = OIMO.atan2(-te[5], te[4]);
  94088. z = OIMO.asin(te[3]);
  94089. }
  94090. return [x, y, z];
  94091. }
  94092. OIMO.unwrapDegrees = function (r) {
  94093. r = r % 360;
  94094. if (r > 180) r -= 360;
  94095. if (r < -180) r += 360;
  94096. return r;
  94097. }
  94098. OIMO.unwrapRadian = function (r) {
  94099. r = r % OIMO.TwoPI;
  94100. if (r > OIMO.PI) r -= OIMO.TwoPI;
  94101. if (r < -OIMO.PI) r += OIMO.TwoPI;
  94102. return r;
  94103. }
  94104. OIMO.Distance3d = function (p1, p2) {
  94105. var xd = p2[0] - p1[0];
  94106. var yd = p2[1] - p1[1];
  94107. var zd = p2[2] - p1[2];
  94108. return OIMO.sqrt(xd * xd + yd * yd + zd * zd);
  94109. }
  94110. /**
  94111. * The base class of all type of the constraints.
  94112. * @author saharan
  94113. */
  94114. OIMO.Constraint = function () {
  94115. // The parent world of the constraint.
  94116. this.parent = null;
  94117. // The first body of the constraint.
  94118. this.body1 = null;
  94119. // The second body of the constraint.
  94120. this.body2 = null;
  94121. // Internal
  94122. this.addedToIsland = false;
  94123. }
  94124. OIMO.Constraint.prototype = {
  94125. constructor: OIMO.Constraint,
  94126. /**
  94127. * Prepare for solving the constraint.
  94128. * @param timeStep
  94129. * @param invTimeStep
  94130. */
  94131. preSolve: function (timeStep, invTimeStep) {
  94132. OIMO.Error("Constraint", "Inheritance error.");
  94133. },
  94134. /**
  94135. * Solve the constraint.
  94136. * This is usually called iteratively.
  94137. */
  94138. solve: function () {
  94139. OIMO.Error("Constraint", "Inheritance error.");
  94140. },
  94141. /**
  94142. * Do the post-processing.
  94143. */
  94144. postSolve: function () {
  94145. OIMO.Error("Constraint", "Inheritance error.");
  94146. }
  94147. }
  94148. /**
  94149. * Joints are used to constrain the motion between two rigid bodies.
  94150. * @author saharan
  94151. * @author lo-th
  94152. */
  94153. OIMO.Joint = function (config) {
  94154. OIMO.Constraint.call(this);
  94155. // joint name
  94156. this.name = "";
  94157. // The type of the joint.
  94158. this.type = OIMO.JOINT_NULL;
  94159. // The previous joint in the world.
  94160. this.prev = null;
  94161. // The next joint in the world.
  94162. this.next = null;
  94163. this.body1 = config.body1;
  94164. this.body2 = config.body2;
  94165. // The anchor point on the first rigid body in local coordinate system.
  94166. this.localAnchorPoint1 = new OIMO.Vec3().copy(config.localAnchorPoint1);
  94167. // The anchor point on the second rigid body in local coordinate system.
  94168. this.localAnchorPoint2 = new OIMO.Vec3().copy(config.localAnchorPoint2);
  94169. // The anchor point on the first rigid body in world coordinate system relative to the body's origin.
  94170. this.relativeAnchorPoint1 = new OIMO.Vec3();
  94171. // The anchor point on the second rigid body in world coordinate system relative to the body's origin.
  94172. this.relativeAnchorPoint2 = new OIMO.Vec3();
  94173. // The anchor point on the first rigid body in world coordinate system.
  94174. this.anchorPoint1 = new OIMO.Vec3();
  94175. // The anchor point on the second rigid body in world coordinate system.
  94176. this.anchorPoint2 = new OIMO.Vec3();
  94177. // Whether allow collision between connected rigid bodies or not.
  94178. this.allowCollision = config.allowCollision;
  94179. this.b1Link = new OIMO.JointLink(this);
  94180. this.b2Link = new OIMO.JointLink(this);
  94181. this.matrix = new OIMO.Mat44();
  94182. };
  94183. OIMO.Joint.prototype = Object.create(OIMO.Constraint.prototype);
  94184. OIMO.Joint.prototype.constructor = OIMO.Joint;
  94185. // Update all the anchor points.
  94186. OIMO.Joint.prototype.updateAnchorPoints = function () {
  94187. this.relativeAnchorPoint1.mulMat(this.body1.rotation, this.localAnchorPoint1);
  94188. this.relativeAnchorPoint2.mulMat(this.body2.rotation, this.localAnchorPoint2);
  94189. this.anchorPoint1.add(this.relativeAnchorPoint1, this.body1.position);
  94190. this.anchorPoint2.add(this.relativeAnchorPoint2, this.body2.position);
  94191. };
  94192. // Attach the joint from the bodies.
  94193. OIMO.Joint.prototype.attach = function () {
  94194. this.b1Link.body = this.body2;
  94195. this.b2Link.body = this.body1;
  94196. if (this.body1.jointLink != null) (this.b1Link.next = this.body1.jointLink).prev = this.b1Link;
  94197. else this.b1Link.next = null;
  94198. this.body1.jointLink = this.b1Link;
  94199. this.body1.numJoints++;
  94200. if (this.body2.jointLink != null) (this.b2Link.next = this.body2.jointLink).prev = this.b2Link;
  94201. else this.b2Link.next = null;
  94202. this.body2.jointLink = this.b2Link;
  94203. this.body2.numJoints++;
  94204. };
  94205. // Detach the joint from the bodies.
  94206. OIMO.Joint.prototype.detach = function () {
  94207. var prev = this.b1Link.prev;
  94208. var next = this.b1Link.next;
  94209. if (prev != null) prev.next = next;
  94210. if (next != null) next.prev = prev;
  94211. if (this.body1.jointLink == this.b1Link) this.body1.jointLink = next;
  94212. this.b1Link.prev = null;
  94213. this.b1Link.next = null;
  94214. this.b1Link.body = null;
  94215. this.body1.numJoints--;
  94216. prev = this.b2Link.prev;
  94217. next = this.b2Link.next;
  94218. if (prev != null) prev.next = next;
  94219. if (next != null) next.prev = prev;
  94220. if (this.body2.jointLink == this.b2Link) this.body2.jointLink = next;
  94221. this.b2Link.prev = null;
  94222. this.b2Link.next = null;
  94223. this.b2Link.body = null;
  94224. this.body2.numJoints--;
  94225. this.b1Link.body = null;
  94226. this.b2Link.body = null;
  94227. };
  94228. // Awake the bodies.
  94229. OIMO.Joint.prototype.awake = function () {
  94230. this.body1.awake();
  94231. this.body2.awake();
  94232. };
  94233. // calculation function
  94234. OIMO.Joint.prototype.preSolve = function (timeStep, invTimeStep) {
  94235. };
  94236. OIMO.Joint.prototype.solve = function () {
  94237. };
  94238. OIMO.Joint.prototype.postSolve = function () {
  94239. };
  94240. // Delete process
  94241. OIMO.Joint.prototype.remove = function () {
  94242. this.dispose();
  94243. };
  94244. OIMO.Joint.prototype.dispose = function () {
  94245. this.parent.removeJoint(this);
  94246. };
  94247. // Three js add
  94248. OIMO.Joint.prototype.getPosition = function () {
  94249. var p1 = new OIMO.Vec3().scale(this.anchorPoint1, OIMO.WORLD_SCALE);
  94250. var p2 = new OIMO.Vec3().scale(this.anchorPoint2, OIMO.WORLD_SCALE);
  94251. return [p1, p2];
  94252. };
  94253. OIMO.Joint.prototype.getMatrix = function () {
  94254. var m = this.matrix.elements;
  94255. var p1 = this.anchorPoint1;
  94256. var p2 = this.anchorPoint2;
  94257. m[0] = p1.x * OIMO.WORLD_SCALE;
  94258. m[1] = p1.y * OIMO.WORLD_SCALE;
  94259. m[2] = p1.z * OIMO.WORLD_SCALE;
  94260. m[3] = 0;
  94261. m[4] = p2.x * OIMO.WORLD_SCALE;
  94262. m[5] = p2.y * OIMO.WORLD_SCALE;
  94263. m[6] = p2.z * OIMO.WORLD_SCALE;
  94264. m[7] = 0;
  94265. return m;
  94266. };
  94267. /**
  94268. * A joint configuration holds all configuration data for constructing a joint.
  94269. * Joint configurations can be reused safely.
  94270. * @author saharan
  94271. */
  94272. OIMO.JointConfig = function () {
  94273. // The first rigid body of the joint.
  94274. this.body1 = null;
  94275. // The second rigid body of the joint.
  94276. this.body2 = null;
  94277. // The anchor point on the first rigid body in local coordinate system.
  94278. this.localAnchorPoint1 = new OIMO.Vec3();
  94279. // The anchor point on the second rigid body in local coordinate system.
  94280. this.localAnchorPoint2 = new OIMO.Vec3();
  94281. // The axis in the first body's coordinate system.
  94282. // his property is available in some joints.
  94283. this.localAxis1 = new OIMO.Vec3();
  94284. // The axis in the second body's coordinate system.
  94285. // This property is available in some joints.
  94286. this.localAxis2 = new OIMO.Vec3();
  94287. // Whether allow collision between connected rigid bodies or not.
  94288. this.allowCollision = false;
  94289. };
  94290. /**
  94291. * A link list of joints.
  94292. * @author saharan
  94293. */
  94294. OIMO.JointLink = function (joint) {
  94295. // The previous joint link.
  94296. this.prev = null;
  94297. // The next joint link.
  94298. this.next = null;
  94299. // The other rigid body connected to the joint.
  94300. this.body = null;
  94301. // The joint of the link.
  94302. this.joint = joint;
  94303. };
  94304. /**
  94305. * An information of limit and motor.
  94306. * @author saharan
  94307. */
  94308. OIMO.LimitMotor = function (axis, fixed) {
  94309. fixed = fixed || false;
  94310. // The axis of the constraint.
  94311. this.axis = axis;
  94312. // The current angle for rotational constraints.
  94313. this.angle = 0;
  94314. // The lower limit. Set lower > upper to disable
  94315. this.lowerLimit = fixed ? 0 : 1;
  94316. //if(fixed)this.lowerLimit = 0;
  94317. //else this.lowerLimit = 1;
  94318. // The upper limit. Set lower > upper to disable.
  94319. this.upperLimit = 0;
  94320. // The target motor speed.
  94321. this.motorSpeed = 0;
  94322. // The maximum motor force or torque. Set 0 to disable.
  94323. this.maxMotorForce = 0;
  94324. // The frequency of the spring. Set 0 to disable.
  94325. this.frequency = 0;
  94326. // The damping ratio of the spring. Set 0 for no damping, 1 for critical damping.
  94327. this.dampingRatio = 0;
  94328. };
  94329. OIMO.LimitMotor.prototype = {
  94330. constructor: OIMO.LimitMotor,
  94331. /**
  94332. * Set limit data into this constraint.
  94333. * @param lowerLimit
  94334. * @param upperLimit
  94335. */
  94336. setLimit: function (lowerLimit, upperLimit) {
  94337. this.lowerLimit = lowerLimit;
  94338. this.upperLimit = upperLimit;
  94339. },
  94340. /**
  94341. * Set motor data into this constraint.
  94342. * @param motorSpeed
  94343. * @param maxMotorForce
  94344. */
  94345. setMotor: function (motorSpeed, maxMotorForce) {
  94346. this.motorSpeed = motorSpeed;
  94347. this.maxMotorForce = maxMotorForce;
  94348. },
  94349. /**
  94350. * Set spring data into this constraint.
  94351. * @param frequency
  94352. * @param dampingRatio
  94353. */
  94354. setSpring: function (frequency, dampingRatio) {
  94355. this.frequency = frequency;
  94356. this.dampingRatio = dampingRatio;
  94357. }
  94358. };
  94359. /**
  94360. * A ball-and-socket joint limits relative translation on two anchor points on rigid bodies.
  94361. * @author saharan
  94362. * @author lo-th
  94363. */
  94364. OIMO.BallAndSocketJoint = function (config) {
  94365. OIMO.Joint.call(this, config);
  94366. this.type = OIMO.JOINT_BALL_AND_SOCKET;
  94367. this.lc = new OIMO.LinearConstraint(this);
  94368. };
  94369. OIMO.BallAndSocketJoint.prototype = Object.create(OIMO.Joint.prototype);
  94370. OIMO.BallAndSocketJoint.prototype.constructor = OIMO.BallAndSocketJoint;
  94371. OIMO.BallAndSocketJoint.prototype.preSolve = function (timeStep, invTimeStep) {
  94372. this.updateAnchorPoints();
  94373. this.lc.preSolve(timeStep, invTimeStep);
  94374. };
  94375. OIMO.BallAndSocketJoint.prototype.solve = function () {
  94376. this.lc.solve();
  94377. };
  94378. OIMO.BallAndSocketJoint.prototype.postSolve = function () {
  94379. };
  94380. /**
  94381. * A distance joint limits the distance between two anchor points on rigid bodies.
  94382. * @author saharan
  94383. * @author lo-th
  94384. */
  94385. OIMO.DistanceJoint = function (config, minDistance, maxDistance) {
  94386. OIMO.Joint.call(this, config);
  94387. this.type = OIMO.JOINT_DISTANCE;
  94388. this.normal = new OIMO.Vec3();
  94389. this.nr = new OIMO.Vec3();
  94390. // The limit and motor information of the joint.
  94391. this.limitMotor = new OIMO.LimitMotor(this.normal, true);
  94392. this.limitMotor.lowerLimit = minDistance;
  94393. this.limitMotor.upperLimit = maxDistance;
  94394. this.t = new OIMO.TranslationalConstraint(this, this.limitMotor);
  94395. };
  94396. OIMO.DistanceJoint.prototype = Object.create(OIMO.Joint.prototype);
  94397. OIMO.DistanceJoint.prototype.constructor = OIMO.DistanceJoint;
  94398. OIMO.DistanceJoint.prototype.preSolve = function (timeStep, invTimeStep) {
  94399. this.updateAnchorPoints();
  94400. //var nr = this.nr;
  94401. this.nr.sub(this.anchorPoint2, this.anchorPoint1);
  94402. //var len = OIMO.sqrt( nr.x*nr.x + nr.y*nr.y + nr.z*nr.z );
  94403. //if(len>0) len = 1/len;
  94404. //this.normal.scale( nr, len );
  94405. this.normal.normalize(this.nr);
  94406. this.t.preSolve(timeStep, invTimeStep);
  94407. };
  94408. OIMO.DistanceJoint.prototype.solve = function () {
  94409. this.t.solve();
  94410. };
  94411. OIMO.DistanceJoint.prototype.postSolve = function () {
  94412. };
  94413. /**
  94414. * A hinge joint allows only for relative rotation of rigid bodies along the axis.
  94415. * @author saharan
  94416. * @author lo-th
  94417. */
  94418. OIMO.HingeJoint = function (config, lowerAngleLimit, upperAngleLimit) {
  94419. OIMO.Joint.call(this, config);
  94420. this.type = OIMO.JOINT_HINGE;
  94421. // The axis in the first body's coordinate system.
  94422. this.localAxis1 = config.localAxis1.clone().norm();
  94423. // The axis in the second body's coordinate system.
  94424. this.localAxis2 = config.localAxis2.clone().norm();
  94425. // make angle axis 1
  94426. this.localAngle1 = new OIMO.Vec3(
  94427. this.localAxis1.y * this.localAxis1.x - this.localAxis1.z * this.localAxis1.z,
  94428. -this.localAxis1.z * this.localAxis1.y - this.localAxis1.x * this.localAxis1.x,
  94429. this.localAxis1.x * this.localAxis1.z + this.localAxis1.y * this.localAxis1.y
  94430. ).norm();
  94431. // make angle axis 2
  94432. var arc = new OIMO.Mat33().setQuat(new OIMO.Quat().arc(this.localAxis1, this.localAxis2));
  94433. this.localAngle2 = new OIMO.Vec3().mulMat(arc, this.localAngle1);
  94434. this.nor = new OIMO.Vec3();
  94435. this.tan = new OIMO.Vec3();
  94436. this.bin = new OIMO.Vec3();
  94437. this.ax1 = new OIMO.Vec3();
  94438. this.ax2 = new OIMO.Vec3();
  94439. this.an1 = new OIMO.Vec3();
  94440. this.an2 = new OIMO.Vec3();
  94441. // The rotational limit and motor information of the joint.
  94442. this.limitMotor = new OIMO.LimitMotor(this.nor, false);
  94443. this.limitMotor.lowerLimit = lowerAngleLimit;
  94444. this.limitMotor.upperLimit = upperAngleLimit;
  94445. this.lc = new OIMO.LinearConstraint(this);
  94446. this.r3 = new OIMO.Rotational3Constraint(this, this.limitMotor, new OIMO.LimitMotor(this.tan, true), new OIMO.LimitMotor(this.bin, true));
  94447. };
  94448. OIMO.HingeJoint.prototype = Object.create(OIMO.Joint.prototype);
  94449. OIMO.HingeJoint.prototype.constructor = OIMO.HingeJoint;
  94450. OIMO.HingeJoint.prototype.preSolve = function (timeStep, invTimeStep) {
  94451. var tmp1X, tmp1Y, tmp1Z, limite;//, nx, ny, nz, tx, ty, tz, bx, by, bz;
  94452. this.updateAnchorPoints();
  94453. this.ax1.mulMat(this.body1.rotation, this.localAxis1);
  94454. this.ax2.mulMat(this.body2.rotation, this.localAxis2);
  94455. this.an1.mulMat(this.body1.rotation, this.localAngle1);
  94456. this.an2.mulMat(this.body2.rotation, this.localAngle2);
  94457. this.nor.set(
  94458. this.ax1.x * this.body2.inverseMass + this.ax2.x * this.body1.inverseMass,
  94459. this.ax1.y * this.body2.inverseMass + this.ax2.y * this.body1.inverseMass,
  94460. this.ax1.z * this.body2.inverseMass + this.ax2.z * this.body1.inverseMass
  94461. ).norm();
  94462. this.tan.set(
  94463. this.nor.y * this.nor.x - this.nor.z * this.nor.z,
  94464. -this.nor.z * this.nor.y - this.nor.x * this.nor.x,
  94465. this.nor.x * this.nor.z + this.nor.y * this.nor.y
  94466. ).norm();
  94467. this.bin.set(
  94468. this.nor.y * this.tan.z - this.nor.z * this.tan.y,
  94469. this.nor.z * this.tan.x - this.nor.x * this.tan.z,
  94470. this.nor.x * this.tan.y - this.nor.y * this.tan.x
  94471. );
  94472. // calculate hinge angle
  94473. limite = this.acosClamp(this.an1.x * this.an2.x + this.an1.y * this.an2.y + this.an1.z * this.an2.z)
  94474. if (
  94475. this.nor.x * (this.an1.y * this.an2.z - this.an1.z * this.an2.y) +
  94476. this.nor.y * (this.an1.z * this.an2.x - this.an1.x * this.an2.z) +
  94477. this.nor.z * (this.an1.x * this.an2.y - this.an1.y * this.an2.x) < 0
  94478. ) {
  94479. this.limitMotor.angle = -limite;
  94480. } else {
  94481. this.limitMotor.angle = limite;
  94482. }
  94483. tmp1X = this.ax1.y * this.ax2.z - this.ax1.z * this.ax2.y;
  94484. tmp1Y = this.ax1.z * this.ax2.x - this.ax1.x * this.ax2.z;
  94485. tmp1Z = this.ax1.x * this.ax2.y - this.ax1.y * this.ax2.x;
  94486. this.r3.limitMotor2.angle = this.tan.x * tmp1X + this.tan.y * tmp1Y + this.tan.z * tmp1Z;
  94487. this.r3.limitMotor3.angle = this.bin.x * tmp1X + this.bin.y * tmp1Y + this.bin.z * tmp1Z;
  94488. this.r3.preSolve(timeStep, invTimeStep);
  94489. this.lc.preSolve(timeStep, invTimeStep);
  94490. };
  94491. OIMO.HingeJoint.prototype.solve = function () {
  94492. this.r3.solve();
  94493. this.lc.solve();
  94494. };
  94495. OIMO.HingeJoint.prototype.postSolve = function () {
  94496. };
  94497. OIMO.HingeJoint.prototype.acosClamp = function (cos) {
  94498. if (cos > 1) return 0;
  94499. else if (cos < -1) return OIMO.PI;
  94500. else return OIMO.acos(cos);
  94501. };
  94502. /**
  94503. * A prismatic joint allows only for relative translation of rigid bodies along the axis.
  94504. * @author saharan
  94505. * @author lo-th
  94506. */
  94507. OIMO.PrismaticJoint = function (config, lowerTranslation, upperTranslation) {
  94508. OIMO.Joint.call(this, config);
  94509. this.type = OIMO.JOINT_PRISMATIC;
  94510. // The axis in the first body's coordinate system.
  94511. this.localAxis1 = new OIMO.Vec3().normalize(config.localAxis1);
  94512. // The axis in the second body's coordinate system.
  94513. this.localAxis2 = new OIMO.Vec3().normalize(config.localAxis2);
  94514. this.localAxis1X = this.localAxis1.x;
  94515. this.localAxis1Y = this.localAxis1.y;
  94516. this.localAxis1Z = this.localAxis1.z;
  94517. this.localAxis2X = this.localAxis2.x;
  94518. this.localAxis2Y = this.localAxis2.y;
  94519. this.localAxis2Z = this.localAxis2.z;
  94520. this.nor = new OIMO.Vec3();
  94521. this.tan = new OIMO.Vec3();
  94522. this.bin = new OIMO.Vec3();
  94523. this.ac = new OIMO.AngularConstraint(this, new OIMO.Quat().arc(this.localAxis1, this.localAxis2));
  94524. // The translational limit and motor information of the joint.
  94525. this.limitMotor = new OIMO.LimitMotor(this.nor, true);
  94526. this.limitMotor.lowerLimit = lowerTranslation;
  94527. this.limitMotor.upperLimit = upperTranslation;
  94528. this.t3 = new OIMO.Translational3Constraint(this, this.limitMotor, new OIMO.LimitMotor(this.tan, true), new OIMO.LimitMotor(this.bin, true));
  94529. };
  94530. OIMO.PrismaticJoint.prototype = Object.create(OIMO.Joint.prototype);
  94531. OIMO.PrismaticJoint.prototype.constructor = OIMO.PrismaticJoint;
  94532. OIMO.PrismaticJoint.prototype.preSolve = function (timeStep, invTimeStep) {
  94533. var tmpM;
  94534. var tmp1X;
  94535. var tmp1Y;
  94536. var tmp1Z;
  94537. this.updateAnchorPoints();
  94538. tmpM = this.body1.rotation.elements;
  94539. var axis1X = this.localAxis1X * tmpM[0] + this.localAxis1Y * tmpM[1] + this.localAxis1Z * tmpM[2];
  94540. var axis1Y = this.localAxis1X * tmpM[3] + this.localAxis1Y * tmpM[4] + this.localAxis1Z * tmpM[5];
  94541. var axis1Z = this.localAxis1X * tmpM[6] + this.localAxis1Y * tmpM[7] + this.localAxis1Z * tmpM[8];
  94542. tmpM = this.body2.rotation.elements;
  94543. var axis2X = this.localAxis2X * tmpM[0] + this.localAxis2Y * tmpM[1] + this.localAxis2Z * tmpM[2];
  94544. var axis2Y = this.localAxis2X * tmpM[3] + this.localAxis2Y * tmpM[4] + this.localAxis2Z * tmpM[5];
  94545. var axis2Z = this.localAxis2X * tmpM[6] + this.localAxis2Y * tmpM[7] + this.localAxis2Z * tmpM[8];
  94546. var nx = axis1X * this.body2.inverseMass + axis2X * this.body1.inverseMass;
  94547. var ny = axis1Y * this.body2.inverseMass + axis2Y * this.body1.inverseMass;
  94548. var nz = axis1Z * this.body2.inverseMass + axis2Z * this.body1.inverseMass;
  94549. tmp1X = OIMO.sqrt(nx * nx + ny * ny + nz * nz);
  94550. if (tmp1X > 0) tmp1X = 1 / tmp1X;
  94551. nx *= tmp1X;
  94552. ny *= tmp1X;
  94553. nz *= tmp1X;
  94554. var tx = ny * nx - nz * nz;
  94555. var ty = -nz * ny - nx * nx;
  94556. var tz = nx * nz + ny * ny;
  94557. tmp1X = 1 / OIMO.sqrt(tx * tx + ty * ty + tz * tz);
  94558. tx *= tmp1X;
  94559. ty *= tmp1X;
  94560. tz *= tmp1X;
  94561. var bx = ny * tz - nz * ty;
  94562. var by = nz * tx - nx * tz;
  94563. var bz = nx * ty - ny * tx;
  94564. this.nor.init(nx, ny, nz);
  94565. this.tan.init(tx, ty, tz);
  94566. this.bin.init(bx, by, bz);
  94567. this.ac.preSolve(timeStep, invTimeStep);
  94568. this.t3.preSolve(timeStep, invTimeStep);
  94569. };
  94570. OIMO.PrismaticJoint.prototype.solve = function () {
  94571. this.ac.solve();
  94572. this.t3.solve();
  94573. };
  94574. OIMO.PrismaticJoint.prototype.postSolve = function () {
  94575. };
  94576. /**
  94577. * A slider joint allows for relative translation and relative rotation between two rigid bodies along the axis.
  94578. * @author saharan
  94579. * @author lo-th
  94580. */
  94581. OIMO.SliderJoint = function (config, lowerTranslation, upperTranslation) {
  94582. OIMO.Joint.call(this, config);
  94583. this.type = OIMO.JOINT_SLIDER;
  94584. // The first axis in local coordinate system.
  94585. this.localAxis1 = new OIMO.Vec3().normalize(config.localAxis1);
  94586. // The second axis in local coordinate system.
  94587. this.localAxis2 = new OIMO.Vec3().normalize(config.localAxis2);
  94588. var len;
  94589. this.localAxis1X = this.localAxis1.x;
  94590. this.localAxis1Y = this.localAxis1.y;
  94591. this.localAxis1Z = this.localAxis1.z;
  94592. this.localAngAxis1X = this.localAxis1Y * this.localAxis1X - this.localAxis1Z * this.localAxis1Z;
  94593. this.localAngAxis1Y = -this.localAxis1Z * this.localAxis1Y - this.localAxis1X * this.localAxis1X;
  94594. this.localAngAxis1Z = this.localAxis1X * this.localAxis1Z + this.localAxis1Y * this.localAxis1Y;
  94595. len = 1 / OIMO.sqrt(this.localAngAxis1X * this.localAngAxis1X + this.localAngAxis1Y * this.localAngAxis1Y + this.localAngAxis1Z * this.localAngAxis1Z);
  94596. this.localAngAxis1X *= len;
  94597. this.localAngAxis1Y *= len;
  94598. this.localAngAxis1Z *= len;
  94599. this.localAxis2X = this.localAxis2.x;
  94600. this.localAxis2Y = this.localAxis2.y;
  94601. this.localAxis2Z = this.localAxis2.z;
  94602. // make angle axis 2
  94603. var arc = new OIMO.Mat33().setQuat(new OIMO.Quat().arc(this.localAxis1, this.localAxis2));
  94604. var tarc = arc.elements;
  94605. this.localAngAxis2X = this.localAngAxis1X * tarc[0] + this.localAngAxis1Y * tarc[1] + this.localAngAxis1Z * tarc[2];
  94606. this.localAngAxis2Y = this.localAngAxis1X * tarc[3] + this.localAngAxis1Y * tarc[4] + this.localAngAxis1Z * tarc[5];
  94607. this.localAngAxis2Z = this.localAngAxis1X * tarc[6] + this.localAngAxis1Y * tarc[7] + this.localAngAxis1Z * tarc[8];
  94608. this.nor = new OIMO.Vec3();
  94609. this.tan = new OIMO.Vec3();
  94610. this.bin = new OIMO.Vec3();
  94611. // The limit and motor for the rotation
  94612. this.rotationalLimitMotor = new OIMO.LimitMotor(this.nor, false);
  94613. this.r3 = new OIMO.Rotational3Constraint(this, this.rotationalLimitMotor, new OIMO.LimitMotor(this.tan, true), new OIMO.LimitMotor(this.bin, true));
  94614. // The limit and motor for the translation.
  94615. this.translationalLimitMotor = new OIMO.LimitMotor(this.nor, true);
  94616. this.translationalLimitMotor.lowerLimit = lowerTranslation;
  94617. this.translationalLimitMotor.upperLimit = upperTranslation;
  94618. this.t3 = new OIMO.Translational3Constraint(this, this.translationalLimitMotor, new OIMO.LimitMotor(this.tan, true), new OIMO.LimitMotor(this.bin, true));
  94619. };
  94620. OIMO.SliderJoint.prototype = Object.create(OIMO.Joint.prototype);
  94621. OIMO.SliderJoint.prototype.constructor = OIMO.SliderJoint;
  94622. OIMO.SliderJoint.prototype.preSolve = function (timeStep, invTimeStep) {
  94623. var tmpM;
  94624. var tmp1X;
  94625. var tmp1Y;
  94626. var tmp1Z;
  94627. this.updateAnchorPoints();
  94628. tmpM = this.body1.rotation.elements;
  94629. var axis1X = this.localAxis1X * tmpM[0] + this.localAxis1Y * tmpM[1] + this.localAxis1Z * tmpM[2];
  94630. var axis1Y = this.localAxis1X * tmpM[3] + this.localAxis1Y * tmpM[4] + this.localAxis1Z * tmpM[5];
  94631. var axis1Z = this.localAxis1X * tmpM[6] + this.localAxis1Y * tmpM[7] + this.localAxis1Z * tmpM[8];
  94632. var angAxis1X = this.localAngAxis1X * tmpM[0] + this.localAngAxis1Y * tmpM[1] + this.localAngAxis1Z * tmpM[2];
  94633. var angAxis1Y = this.localAngAxis1X * tmpM[3] + this.localAngAxis1Y * tmpM[4] + this.localAngAxis1Z * tmpM[5];
  94634. var angAxis1Z = this.localAngAxis1X * tmpM[6] + this.localAngAxis1Y * tmpM[7] + this.localAngAxis1Z * tmpM[8];
  94635. tmpM = this.body2.rotation.elements;
  94636. var axis2X = this.localAxis2X * tmpM[0] + this.localAxis2Y * tmpM[1] + this.localAxis2Z * tmpM[2];
  94637. var axis2Y = this.localAxis2X * tmpM[3] + this.localAxis2Y * tmpM[4] + this.localAxis2Z * tmpM[5];
  94638. var axis2Z = this.localAxis2X * tmpM[6] + this.localAxis2Y * tmpM[7] + this.localAxis2Z * tmpM[8];
  94639. var angAxis2X = this.localAngAxis2X * tmpM[0] + this.localAngAxis2Y * tmpM[1] + this.localAngAxis2Z * tmpM[2];
  94640. var angAxis2Y = this.localAngAxis2X * tmpM[3] + this.localAngAxis2Y * tmpM[4] + this.localAngAxis2Z * tmpM[5];
  94641. var angAxis2Z = this.localAngAxis2X * tmpM[6] + this.localAngAxis2Y * tmpM[7] + this.localAngAxis2Z * tmpM[8];
  94642. var nx = axis1X * this.body2.inverseMass + axis2X * this.body1.inverseMass;
  94643. var ny = axis1Y * this.body2.inverseMass + axis2Y * this.body1.inverseMass;
  94644. var nz = axis1Z * this.body2.inverseMass + axis2Z * this.body1.inverseMass;
  94645. tmp1X = OIMO.sqrt(nx * nx + ny * ny + nz * nz);
  94646. if (tmp1X > 0) tmp1X = 1 / tmp1X;
  94647. nx *= tmp1X;
  94648. ny *= tmp1X;
  94649. nz *= tmp1X;
  94650. var tx = ny * nx - nz * nz;
  94651. var ty = -nz * ny - nx * nx;
  94652. var tz = nx * nz + ny * ny;
  94653. tmp1X = 1 / OIMO.sqrt(tx * tx + ty * ty + tz * tz);
  94654. tx *= tmp1X;
  94655. ty *= tmp1X;
  94656. tz *= tmp1X;
  94657. var bx = ny * tz - nz * ty;
  94658. var by = nz * tx - nx * tz;
  94659. var bz = nx * ty - ny * tx;
  94660. this.nor.init(nx, ny, nz);
  94661. this.tan.init(tx, ty, tz);
  94662. this.bin.init(bx, by, bz);
  94663. // ----------------------------------------------
  94664. // calculate hinge angle
  94665. // ----------------------------------------------
  94666. if (
  94667. nx * (angAxis1Y * angAxis2Z - angAxis1Z * angAxis2Y) +
  94668. ny * (angAxis1Z * angAxis2X - angAxis1X * angAxis2Z) +
  94669. nz * (angAxis1X * angAxis2Y - angAxis1Y * angAxis2X) < 0
  94670. ) {
  94671. this.rotationalLimitMotor.angle = -this.acosClamp(angAxis1X * angAxis2X + angAxis1Y * angAxis2Y + angAxis1Z * angAxis2Z);
  94672. } else {
  94673. this.rotationalLimitMotor.angle = this.acosClamp(angAxis1X * angAxis2X + angAxis1Y * angAxis2Y + angAxis1Z * angAxis2Z);
  94674. }
  94675. // angular error
  94676. tmp1X = axis1Y * axis2Z - axis1Z * axis2Y;
  94677. tmp1Y = axis1Z * axis2X - axis1X * axis2Z;
  94678. tmp1Z = axis1X * axis2Y - axis1Y * axis2X;
  94679. this.r3.limitMotor2.angle = tx * tmp1X + ty * tmp1Y + tz * tmp1Z;
  94680. this.r3.limitMotor3.angle = bx * tmp1X + by * tmp1Y + bz * tmp1Z;
  94681. this.r3.preSolve(timeStep, invTimeStep);
  94682. this.t3.preSolve(timeStep, invTimeStep);
  94683. };
  94684. OIMO.SliderJoint.prototype.solve = function () {
  94685. this.r3.solve();
  94686. this.t3.solve();
  94687. };
  94688. OIMO.SliderJoint.prototype.postSolve = function () {
  94689. };
  94690. OIMO.SliderJoint.prototype.acosClamp = function (cos) {
  94691. if (cos > 1) return 0;
  94692. else if (cos < -1) return OIMO.PI;
  94693. else return OIMO.acos(cos);
  94694. };
  94695. /**
  94696. * A wheel joint allows for relative rotation between two rigid bodies along two axes.
  94697. * The wheel joint also allows for relative translation for the suspension.
  94698. * @author saharan
  94699. * @author lo-th
  94700. */
  94701. OIMO.WheelJoint = function (config) {
  94702. OIMO.Joint.call(this, config);
  94703. this.type = OIMO.JOINT_WHEEL;
  94704. // The first axis in local coordinate system.
  94705. this.localAxis1 = new OIMO.Vec3().normalize(config.localAxis1);
  94706. // The second axis in local coordinate system.
  94707. this.localAxis2 = new OIMO.Vec3().normalize(config.localAxis2);
  94708. var len;
  94709. this.localAxis1X = this.localAxis1.x;
  94710. this.localAxis1Y = this.localAxis1.y;
  94711. this.localAxis1Z = this.localAxis1.z;
  94712. this.localAxis2X = this.localAxis2.x;
  94713. this.localAxis2Y = this.localAxis2.y;
  94714. this.localAxis2Z = this.localAxis2.z;
  94715. var dot = this.localAxis1X * this.localAxis2X + this.localAxis1Y * this.localAxis2Y + this.localAxis1Z * this.localAxis2Z;
  94716. if (dot > -1 && dot < 1) {
  94717. this.localAngAxis1X = this.localAxis2X - dot * this.localAxis1X;
  94718. this.localAngAxis1Y = this.localAxis2Y - dot * this.localAxis1Y;
  94719. this.localAngAxis1Z = this.localAxis2Z - dot * this.localAxis1Z;
  94720. this.localAngAxis2X = this.localAxis1X - dot * this.localAxis2X;
  94721. this.localAngAxis2Y = this.localAxis1Y - dot * this.localAxis2Y;
  94722. this.localAngAxis2Z = this.localAxis1Z - dot * this.localAxis2Z;
  94723. len = 1 / OIMO.sqrt(this.localAngAxis1X * this.localAngAxis1X + this.localAngAxis1Y * this.localAngAxis1Y + this.localAngAxis1Z * this.localAngAxis1Z);
  94724. this.localAngAxis1X *= len;
  94725. this.localAngAxis1Y *= len;
  94726. this.localAngAxis1Z *= len;
  94727. len = 1 / OIMO.sqrt(this.localAngAxis2X * this.localAngAxis2X + this.localAngAxis2Y * this.localAngAxis2Y + this.localAngAxis2Z * this.localAngAxis2Z);
  94728. this.localAngAxis2X *= len;
  94729. this.localAngAxis2Y *= len;
  94730. this.localAngAxis2Z *= len;
  94731. } else {
  94732. this.localAngAxis1X = this.localAxis1Y * this.localAxis1X - this.localAxis1Z * this.localAxis1Z;
  94733. this.localAngAxis1Y = -this.localAxis1Z * this.localAxis1Y - this.localAxis1X * this.localAxis1X;
  94734. this.localAngAxis1Z = this.localAxis1X * this.localAxis1Z + this.localAxis1Y * this.localAxis1Y;
  94735. len = 1 / OIMO.sqrt(this.localAngAxis1X * this.localAngAxis1X + this.localAngAxis1Y * this.localAngAxis1Y + this.localAngAxis1Z * this.localAngAxis1Z);
  94736. this.localAngAxis1X *= len;
  94737. this.localAngAxis1Y *= len;
  94738. this.localAngAxis1Z *= len;
  94739. var arc = new OIMO.Mat33().setQuat(new OIMO.Quat().arc(this.localAxis1, this.localAxis2));
  94740. var tarc = arc.elements;
  94741. this.localAngAxis2X = this.localAngAxis1X * tarc[0] + this.localAngAxis1Y * tarc[1] + this.localAngAxis1Z * tarc[2];
  94742. this.localAngAxis2Y = this.localAngAxis1X * tarc[3] + this.localAngAxis1Y * tarc[4] + this.localAngAxis1Z * tarc[5];
  94743. this.localAngAxis2Z = this.localAngAxis1X * tarc[6] + this.localAngAxis1Y * tarc[7] + this.localAngAxis1Z * tarc[8];
  94744. }
  94745. this.nor = new OIMO.Vec3();
  94746. this.tan = new OIMO.Vec3();
  94747. this.bin = new OIMO.Vec3();
  94748. // The translational limit and motor information of the joint.
  94749. this.translationalLimitMotor = new OIMO.LimitMotor(this.tan, true);
  94750. this.translationalLimitMotor.frequency = 8;
  94751. this.translationalLimitMotor.dampingRatio = 1;
  94752. // The first rotational limit and motor information of the joint.
  94753. this.rotationalLimitMotor1 = new OIMO.LimitMotor(this.tan, false);
  94754. // The second rotational limit and motor information of the joint.
  94755. this.rotationalLimitMotor2 = new OIMO.LimitMotor(this.bin, false);
  94756. this.t3 = new OIMO.Translational3Constraint(this, new OIMO.LimitMotor(this.nor, true), this.translationalLimitMotor, new OIMO.LimitMotor(this.bin, true));
  94757. this.t3.weight = 1;
  94758. this.r3 = new OIMO.Rotational3Constraint(this, new OIMO.LimitMotor(this.nor, true), this.rotationalLimitMotor1, this.rotationalLimitMotor2);
  94759. };
  94760. OIMO.WheelJoint.prototype = Object.create(OIMO.Joint.prototype);
  94761. OIMO.WheelJoint.prototype.constructor = OIMO.WheelJoint;
  94762. OIMO.WheelJoint.prototype.preSolve = function (timeStep, invTimeStep) {
  94763. var tmpM;
  94764. var tmp1X;
  94765. var tmp1Y;
  94766. var tmp1Z;
  94767. this.updateAnchorPoints();
  94768. tmpM = this.body1.rotation.elements;
  94769. var x1 = this.localAxis1X * tmpM[0] + this.localAxis1Y * tmpM[1] + this.localAxis1Z * tmpM[2];
  94770. var y1 = this.localAxis1X * tmpM[3] + this.localAxis1Y * tmpM[4] + this.localAxis1Z * tmpM[5];
  94771. var z1 = this.localAxis1X * tmpM[6] + this.localAxis1Y * tmpM[7] + this.localAxis1Z * tmpM[8];
  94772. var angAxis1X = this.localAngAxis1X * tmpM[0] + this.localAngAxis1Y * tmpM[1] + this.localAngAxis1Z * tmpM[2];
  94773. var angAxis1Y = this.localAngAxis1X * tmpM[3] + this.localAngAxis1Y * tmpM[4] + this.localAngAxis1Z * tmpM[5];
  94774. var angAxis1Z = this.localAngAxis1X * tmpM[6] + this.localAngAxis1Y * tmpM[7] + this.localAngAxis1Z * tmpM[8];
  94775. tmpM = this.body2.rotation.elements;
  94776. var x2 = this.localAxis2X * tmpM[0] + this.localAxis2Y * tmpM[1] + this.localAxis2Z * tmpM[2];
  94777. var y2 = this.localAxis2X * tmpM[3] + this.localAxis2Y * tmpM[4] + this.localAxis2Z * tmpM[5];
  94778. var z2 = this.localAxis2X * tmpM[6] + this.localAxis2Y * tmpM[7] + this.localAxis2Z * tmpM[8];
  94779. var angAxis2X = this.localAngAxis2X * tmpM[0] + this.localAngAxis2Y * tmpM[1] + this.localAngAxis2Z * tmpM[2];
  94780. var angAxis2Y = this.localAngAxis2X * tmpM[3] + this.localAngAxis2Y * tmpM[4] + this.localAngAxis2Z * tmpM[5];
  94781. var angAxis2Z = this.localAngAxis2X * tmpM[6] + this.localAngAxis2Y * tmpM[7] + this.localAngAxis2Z * tmpM[8];
  94782. this.r3.limitMotor1.angle = x1 * x2 + y1 * y2 + z1 * z2;
  94783. if (x1 * (angAxis1Y * z2 - angAxis1Z * y2) + y1 * (angAxis1Z * x2 - angAxis1X * z2) + z1 * (angAxis1X * y2 - angAxis1Y * x2) < 0) {
  94784. this.rotationalLimitMotor1.angle = -this.acosClamp(angAxis1X * x2 + angAxis1Y * y2 + angAxis1Z * z2);
  94785. } else {
  94786. this.rotationalLimitMotor1.angle = this.acosClamp(angAxis1X * x2 + angAxis1Y * y2 + angAxis1Z * z2);
  94787. }
  94788. if (x2 * (angAxis2Y * z1 - angAxis2Z * y1) + y2 * (angAxis2Z * x1 - angAxis2X * z1) + z2 * (angAxis2X * y1 - angAxis2Y * x1) < 0) {
  94789. this.rotationalLimitMotor2.angle = this.acosClamp(angAxis2X * x1 + angAxis2Y * y1 + angAxis2Z * z1);
  94790. } else {
  94791. this.rotationalLimitMotor2.angle = -this.acosClamp(angAxis2X * x1 + angAxis2Y * y1 + angAxis2Z * z1);
  94792. }
  94793. var nx = y2 * z1 - z2 * y1;
  94794. var ny = z2 * x1 - x2 * z1;
  94795. var nz = x2 * y1 - y2 * x1;
  94796. tmp1X = OIMO.sqrt(nx * nx + ny * ny + nz * nz);
  94797. if (tmp1X > 0) tmp1X = 1 / tmp1X;
  94798. nx *= tmp1X;
  94799. ny *= tmp1X;
  94800. nz *= tmp1X;
  94801. var tx = ny * z2 - nz * y2;
  94802. var ty = nz * x2 - nx * z2;
  94803. var tz = nx * y2 - ny * x2;
  94804. tmp1X = OIMO.sqrt(tx * tx + ty * ty + tz * tz);
  94805. if (tmp1X > 0) tmp1X = 1 / tmp1X;
  94806. tx *= tmp1X;
  94807. ty *= tmp1X;
  94808. tz *= tmp1X;
  94809. var bx = y1 * nz - z1 * ny;
  94810. var by = z1 * nx - x1 * nz;
  94811. var bz = x1 * ny - y1 * nx;
  94812. tmp1X = OIMO.sqrt(bx * bx + by * by + bz * bz);
  94813. if (tmp1X > 0) tmp1X = 1 / tmp1X;
  94814. bx *= tmp1X;
  94815. by *= tmp1X;
  94816. bz *= tmp1X;
  94817. this.nor.init(nx, ny, nz);
  94818. this.tan.init(tx, ty, tz);
  94819. this.bin.init(bx, by, bz);
  94820. this.r3.preSolve(timeStep, invTimeStep);
  94821. this.t3.preSolve(timeStep, invTimeStep);
  94822. };
  94823. OIMO.WheelJoint.prototype.solve = function () {
  94824. this.r3.solve();
  94825. this.t3.solve();
  94826. };
  94827. OIMO.WheelJoint.prototype.postSolve = function () {
  94828. };
  94829. OIMO.WheelJoint.prototype.acosClamp = function (cos) {
  94830. if (cos > 1) return 0;
  94831. else if (cos < -1) return OIMO.PI;
  94832. else return OIMO.acos(cos);
  94833. };
  94834. /**
  94835. * An angular constraint for all axes for various joints.
  94836. * @author saharan
  94837. */
  94838. OIMO.AngularConstraint = function (joint, targetOrientation) {
  94839. this.joint = joint;
  94840. this.targetOrientation = new OIMO.Quat().invert(targetOrientation);
  94841. this.relativeOrientation = new OIMO.Quat();
  94842. this.ii1 = null;
  94843. this.ii2 = null;
  94844. this.dd = null;
  94845. this.vel = new OIMO.Vec3();
  94846. this.imp = new OIMO.Vec3();
  94847. this.rn0 = new OIMO.Vec3();
  94848. this.rn1 = new OIMO.Vec3();
  94849. this.rn2 = new OIMO.Vec3();
  94850. this.b1 = joint.body1;
  94851. this.b2 = joint.body2;
  94852. this.a1 = this.b1.angularVelocity;
  94853. this.a2 = this.b2.angularVelocity;
  94854. this.i1 = this.b1.inverseInertia;
  94855. this.i2 = this.b2.inverseInertia;
  94856. };
  94857. OIMO.AngularConstraint.prototype = {
  94858. constructor: OIMO.AngularConstraint,
  94859. preSolve: function (timeStep, invTimeStep) {
  94860. var inv, len, v, vv;
  94861. this.ii1 = this.i1.clone();
  94862. this.ii2 = this.i2.clone();
  94863. v = new OIMO.Mat33().add(this.ii1, this.ii2).elements;
  94864. 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]));
  94865. this.dd = new OIMO.Mat33(
  94866. v[4] * v[8] - v[5] * v[7], v[2] * v[7] - v[1] * v[8], v[1] * v[5] - v[2] * v[4],
  94867. v[5] * v[6] - v[3] * v[8], v[0] * v[8] - v[2] * v[6], v[2] * v[3] - v[0] * v[5],
  94868. v[3] * v[7] - v[4] * v[6], v[1] * v[6] - v[0] * v[7], v[0] * v[4] - v[1] * v[3]
  94869. ).multiply(inv);
  94870. this.relativeOrientation.invert(this.b1.orientation);
  94871. this.relativeOrientation.mul(this.targetOrientation, this.relativeOrientation);
  94872. this.relativeOrientation.mul(this.b2.orientation, this.relativeOrientation);
  94873. inv = this.relativeOrientation.s * 2;
  94874. this.vel.scale(this.relativeOrientation, inv);
  94875. len = this.vel.length();
  94876. if (len > 0.02) {
  94877. len = (0.02 - len) / len * invTimeStep * 0.05;
  94878. this.vel.scaleEqual(len);
  94879. } else {
  94880. this.vel.init();
  94881. }
  94882. this.rn1.mulMat(this.ii1, this.imp);
  94883. this.rn2.mulMat(this.ii2, this.imp);
  94884. this.a1.addEqual(this.rn1);
  94885. this.a2.subEqual(this.rn2);
  94886. },
  94887. solve: function () {
  94888. var r = this.a2.clone().subEqual(this.a1).subEqual(this.vel);
  94889. this.rn0.mulMat(this.dd, r);
  94890. this.rn1.mulMat(this.ii1, this.rn0);
  94891. this.rn2.mulMat(this.ii2, this.rn0);
  94892. this.imp.addEqual(this.rn0);
  94893. this.a1.addEqual(this.rn1);
  94894. this.a2.subEqual(this.rn2);
  94895. }
  94896. };
  94897. /**
  94898. * A linear constraint for all axes for various joints.
  94899. * @author saharan
  94900. */
  94901. OIMO.LinearConstraint = function (joint) {
  94902. this.m1 = NaN;
  94903. this.m2 = NaN;
  94904. this.ii1 = null;
  94905. this.ii2 = null;
  94906. this.dd = null;
  94907. this.r1x = NaN;
  94908. this.r1y = NaN;
  94909. this.r1z = NaN;
  94910. this.r2x = NaN;
  94911. this.r2y = NaN;
  94912. this.r2z = NaN;
  94913. this.ax1x = NaN;
  94914. this.ax1y = NaN;
  94915. this.ax1z = NaN;
  94916. this.ay1x = NaN;
  94917. this.ay1y = NaN;
  94918. this.ay1z = NaN;
  94919. this.az1x = NaN;
  94920. this.az1y = NaN;
  94921. this.az1z = NaN;
  94922. this.ax2x = NaN;
  94923. this.ax2y = NaN;
  94924. this.ax2z = NaN;
  94925. this.ay2x = NaN;
  94926. this.ay2y = NaN;
  94927. this.ay2z = NaN;
  94928. this.az2x = NaN;
  94929. this.az2y = NaN;
  94930. this.az2z = NaN;
  94931. this.vel = NaN;
  94932. this.velx = NaN;
  94933. this.vely = NaN;
  94934. this.velz = NaN;
  94935. this.joint = joint;
  94936. this.r1 = joint.relativeAnchorPoint1;
  94937. this.r2 = joint.relativeAnchorPoint2;
  94938. this.p1 = joint.anchorPoint1;
  94939. this.p2 = joint.anchorPoint2;
  94940. this.b1 = joint.body1;
  94941. this.b2 = joint.body2;
  94942. this.l1 = this.b1.linearVelocity;
  94943. this.l2 = this.b2.linearVelocity;
  94944. this.a1 = this.b1.angularVelocity;
  94945. this.a2 = this.b2.angularVelocity;
  94946. this.i1 = this.b1.inverseInertia;
  94947. this.i2 = this.b2.inverseInertia;
  94948. this.impx = 0;
  94949. this.impy = 0;
  94950. this.impz = 0;
  94951. }
  94952. OIMO.LinearConstraint.prototype = {
  94953. constructor: OIMO.LinearConstraint,
  94954. preSolve: function (timeStep, invTimeStep) {
  94955. this.r1x = this.r1.x;
  94956. this.r1y = this.r1.y;
  94957. this.r1z = this.r1.z;
  94958. this.r2x = this.r2.x;
  94959. this.r2y = this.r2.y;
  94960. this.r2z = this.r2.z;
  94961. this.m1 = this.b1.inverseMass;
  94962. this.m2 = this.b2.inverseMass;
  94963. this.ii1 = this.i1.clone();
  94964. this.ii2 = this.i2.clone();
  94965. var ii1 = this.ii1.elements;
  94966. var ii2 = this.ii2.elements;
  94967. this.ax1x = this.r1z * ii1[1] + -this.r1y * ii1[2];
  94968. this.ax1y = this.r1z * ii1[4] + -this.r1y * ii1[5];
  94969. this.ax1z = this.r1z * ii1[7] + -this.r1y * ii1[8];
  94970. this.ay1x = -this.r1z * ii1[0] + this.r1x * ii1[2];
  94971. this.ay1y = -this.r1z * ii1[3] + this.r1x * ii1[5];
  94972. this.ay1z = -this.r1z * ii1[6] + this.r1x * ii1[8];
  94973. this.az1x = this.r1y * ii1[0] + -this.r1x * ii1[1];
  94974. this.az1y = this.r1y * ii1[3] + -this.r1x * ii1[4];
  94975. this.az1z = this.r1y * ii1[6] + -this.r1x * ii1[7];
  94976. this.ax2x = this.r2z * ii2[1] + -this.r2y * ii2[2];
  94977. this.ax2y = this.r2z * ii2[4] + -this.r2y * ii2[5];
  94978. this.ax2z = this.r2z * ii2[7] + -this.r2y * ii2[8];
  94979. this.ay2x = -this.r2z * ii2[0] + this.r2x * ii2[2];
  94980. this.ay2y = -this.r2z * ii2[3] + this.r2x * ii2[5];
  94981. this.ay2z = -this.r2z * ii2[6] + this.r2x * ii2[8];
  94982. this.az2x = this.r2y * ii2[0] + -this.r2x * ii2[1];
  94983. this.az2y = this.r2y * ii2[3] + -this.r2x * ii2[4];
  94984. this.az2z = this.r2y * ii2[6] + -this.r2x * ii2[7];
  94985. // calculate point-to-point mass matrix
  94986. // from impulse equation
  94987. //
  94988. // M = ([/m] - [r^][/I][r^]) ^ -1
  94989. //
  94990. // where
  94991. //
  94992. // [/m] = |1/m, 0, 0|
  94993. // |0, 1/m, 0|
  94994. // |0, 0, 1/m|
  94995. //
  94996. // [r^] = |0, -rz, ry|
  94997. // |rz, 0, -rx|
  94998. // |-ry, rx, 0|
  94999. //
  95000. // [/I] = Inverted moment inertia
  95001. var rxx = this.m1 + this.m2;
  95002. var kk = new OIMO.Mat33(rxx, 0, 0, 0, rxx, 0, 0, 0, rxx);
  95003. var k = kk.elements;
  95004. k[0] += ii1[4] * this.r1z * this.r1z - (ii1[7] + ii1[5]) * this.r1y * this.r1z + ii1[8] * this.r1y * this.r1y;
  95005. k[1] += (ii1[6] * this.r1y + ii1[5] * this.r1x) * this.r1z - ii1[3] * this.r1z * this.r1z - ii1[8] * this.r1x * this.r1y;
  95006. k[2] += (ii1[3] * this.r1y - ii1[4] * this.r1x) * this.r1z - ii1[6] * this.r1y * this.r1y + ii1[7] * this.r1x * this.r1y;
  95007. k[3] += (ii1[2] * this.r1y + ii1[7] * this.r1x) * this.r1z - ii1[1] * this.r1z * this.r1z - ii1[8] * this.r1x * this.r1y;
  95008. k[4] += ii1[0] * this.r1z * this.r1z - (ii1[6] + ii1[2]) * this.r1x * this.r1z + ii1[8] * this.r1x * this.r1x;
  95009. k[5] += (ii1[1] * this.r1x - ii1[0] * this.r1y) * this.r1z - ii1[7] * this.r1x * this.r1x + ii1[6] * this.r1x * this.r1y;
  95010. k[6] += (ii1[1] * this.r1y - ii1[4] * this.r1x) * this.r1z - ii1[2] * this.r1y * this.r1y + ii1[5] * this.r1x * this.r1y;
  95011. k[7] += (ii1[3] * this.r1x - ii1[0] * this.r1y) * this.r1z - ii1[5] * this.r1x * this.r1x + ii1[2] * this.r1x * this.r1y;
  95012. k[8] += ii1[0] * this.r1y * this.r1y - (ii1[3] + ii1[1]) * this.r1x * this.r1y + ii1[4] * this.r1x * this.r1x;
  95013. k[0] += ii2[4] * this.r2z * this.r2z - (ii2[7] + ii2[5]) * this.r2y * this.r2z + ii2[8] * this.r2y * this.r2y;
  95014. k[1] += (ii2[6] * this.r2y + ii2[5] * this.r2x) * this.r2z - ii2[3] * this.r2z * this.r2z - ii2[8] * this.r2x * this.r2y;
  95015. k[2] += (ii2[3] * this.r2y - ii2[4] * this.r2x) * this.r2z - ii2[6] * this.r2y * this.r2y + ii2[7] * this.r2x * this.r2y;
  95016. k[3] += (ii2[2] * this.r2y + ii2[7] * this.r2x) * this.r2z - ii2[1] * this.r2z * this.r2z - ii2[8] * this.r2x * this.r2y;
  95017. k[4] += ii2[0] * this.r2z * this.r2z - (ii2[6] + ii2[2]) * this.r2x * this.r2z + ii2[8] * this.r2x * this.r2x;
  95018. k[5] += (ii2[1] * this.r2x - ii2[0] * this.r2y) * this.r2z - ii2[7] * this.r2x * this.r2x + ii2[6] * this.r2x * this.r2y;
  95019. k[6] += (ii2[1] * this.r2y - ii2[4] * this.r2x) * this.r2z - ii2[2] * this.r2y * this.r2y + ii2[5] * this.r2x * this.r2y;
  95020. k[7] += (ii2[3] * this.r2x - ii2[0] * this.r2y) * this.r2z - ii2[5] * this.r2x * this.r2x + ii2[2] * this.r2x * this.r2y;
  95021. k[8] += ii2[0] * this.r2y * this.r2y - (ii2[3] + ii2[1]) * this.r2x * this.r2y + ii2[4] * this.r2x * this.r2x;
  95022. 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]));
  95023. this.dd = new OIMO.Mat33(
  95024. k[4] * k[8] - k[5] * k[7], k[2] * k[7] - k[1] * k[8], k[1] * k[5] - k[2] * k[4],
  95025. k[5] * k[6] - k[3] * k[8], k[0] * k[8] - k[2] * k[6], k[2] * k[3] - k[0] * k[5],
  95026. k[3] * k[7] - k[4] * k[6], k[1] * k[6] - k[0] * k[7], k[0] * k[4] - k[1] * k[3]
  95027. ).multiply(inv);
  95028. this.velx = this.p2.x - this.p1.x;
  95029. this.vely = this.p2.y - this.p1.y;
  95030. this.velz = this.p2.z - this.p1.z;
  95031. var len = OIMO.sqrt(this.velx * this.velx + this.vely * this.vely + this.velz * this.velz);
  95032. if (len > 0.005) {
  95033. len = (0.005 - len) / len * invTimeStep * 0.05;
  95034. this.velx *= len;
  95035. this.vely *= len;
  95036. this.velz *= len;
  95037. } else {
  95038. this.velx = 0;
  95039. this.vely = 0;
  95040. this.velz = 0;
  95041. }
  95042. this.impx *= 0.95;
  95043. this.impy *= 0.95;
  95044. this.impz *= 0.95;
  95045. this.l1.x += this.impx * this.m1;
  95046. this.l1.y += this.impy * this.m1;
  95047. this.l1.z += this.impz * this.m1;
  95048. this.a1.x += this.impx * this.ax1x + this.impy * this.ay1x + this.impz * this.az1x;
  95049. this.a1.y += this.impx * this.ax1y + this.impy * this.ay1y + this.impz * this.az1y;
  95050. this.a1.z += this.impx * this.ax1z + this.impy * this.ay1z + this.impz * this.az1z;
  95051. this.l2.x -= this.impx * this.m2;
  95052. this.l2.y -= this.impy * this.m2;
  95053. this.l2.z -= this.impz * this.m2;
  95054. this.a2.x -= this.impx * this.ax2x + this.impy * this.ay2x + this.impz * this.az2x;
  95055. this.a2.y -= this.impx * this.ax2y + this.impy * this.ay2y + this.impz * this.az2y;
  95056. this.a2.z -= this.impx * this.ax2z + this.impy * this.ay2z + this.impz * this.az2z;
  95057. },
  95058. solve: function () {
  95059. var d = this.dd.elements;
  95060. 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;
  95061. 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;
  95062. 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;
  95063. var nimpx = rvx * d[0] + rvy * d[1] + rvz * d[2];
  95064. var nimpy = rvx * d[3] + rvy * d[4] + rvz * d[5];
  95065. var nimpz = rvx * d[6] + rvy * d[7] + rvz * d[8];
  95066. this.impx += nimpx;
  95067. this.impy += nimpy;
  95068. this.impz += nimpz;
  95069. this.l1.x += nimpx * this.m1;
  95070. this.l1.y += nimpy * this.m1;
  95071. this.l1.z += nimpz * this.m1;
  95072. this.a1.x += nimpx * this.ax1x + nimpy * this.ay1x + nimpz * this.az1x;
  95073. this.a1.y += nimpx * this.ax1y + nimpy * this.ay1y + nimpz * this.az1y;
  95074. this.a1.z += nimpx * this.ax1z + nimpy * this.ay1z + nimpz * this.az1z;
  95075. this.l2.x -= nimpx * this.m2;
  95076. this.l2.y -= nimpy * this.m2;
  95077. this.l2.z -= nimpz * this.m2;
  95078. this.a2.x -= nimpx * this.ax2x + nimpy * this.ay2x + nimpz * this.az2x;
  95079. this.a2.y -= nimpx * this.ax2y + nimpy * this.ay2y + nimpz * this.az2y;
  95080. this.a2.z -= nimpx * this.ax2z + nimpy * this.ay2z + nimpz * this.az2z;
  95081. }
  95082. }
  95083. /**
  95084. * A three-axis rotational constraint for various joints.
  95085. * @author saharan
  95086. */
  95087. OIMO.Rotational3Constraint = function (joint, limitMotor1, limitMotor2, limitMotor3) {
  95088. this.cfm1 = NaN;
  95089. this.cfm2 = NaN;
  95090. this.cfm3 = NaN;
  95091. this.i1e00 = NaN;
  95092. this.i1e01 = NaN;
  95093. this.i1e02 = NaN;
  95094. this.i1e10 = NaN;
  95095. this.i1e11 = NaN;
  95096. this.i1e12 = NaN;
  95097. this.i1e20 = NaN;
  95098. this.i1e21 = NaN;
  95099. this.i1e22 = NaN;
  95100. this.i2e00 = NaN;
  95101. this.i2e01 = NaN;
  95102. this.i2e02 = NaN;
  95103. this.i2e10 = NaN;
  95104. this.i2e11 = NaN;
  95105. this.i2e12 = NaN;
  95106. this.i2e20 = NaN;
  95107. this.i2e21 = NaN;
  95108. this.i2e22 = NaN;
  95109. this.ax1 = NaN;
  95110. this.ay1 = NaN;
  95111. this.az1 = NaN;
  95112. this.ax2 = NaN;
  95113. this.ay2 = NaN;
  95114. this.az2 = NaN;
  95115. this.ax3 = NaN;
  95116. this.ay3 = NaN;
  95117. this.az3 = NaN;
  95118. this.a1x1 = NaN; // jacoians
  95119. this.a1y1 = NaN;
  95120. this.a1z1 = NaN;
  95121. this.a2x1 = NaN;
  95122. this.a2y1 = NaN;
  95123. this.a2z1 = NaN;
  95124. this.a1x2 = NaN;
  95125. this.a1y2 = NaN;
  95126. this.a1z2 = NaN;
  95127. this.a2x2 = NaN;
  95128. this.a2y2 = NaN;
  95129. this.a2z2 = NaN;
  95130. this.a1x3 = NaN;
  95131. this.a1y3 = NaN;
  95132. this.a1z3 = NaN;
  95133. this.a2x3 = NaN;
  95134. this.a2y3 = NaN;
  95135. this.a2z3 = NaN;
  95136. this.lowerLimit1 = NaN;
  95137. this.upperLimit1 = NaN;
  95138. this.limitVelocity1 = NaN;
  95139. this.limitState1 = 0; // -1: at lower, 0: locked, 1: at upper, 2: free
  95140. this.enableMotor1 = false;
  95141. this.motorSpeed1 = NaN;
  95142. this.maxMotorForce1 = NaN;
  95143. this.maxMotorImpulse1 = NaN;
  95144. this.lowerLimit2 = NaN;
  95145. this.upperLimit2 = NaN;
  95146. this.limitVelocity2 = NaN;
  95147. this.limitState2 = 0; // -1: at lower, 0: locked, 1: at upper, 2: free
  95148. this.enableMotor2 = false;
  95149. this.motorSpeed2 = NaN;
  95150. this.maxMotorForce2 = NaN;
  95151. this.maxMotorImpulse2 = NaN;
  95152. this.lowerLimit3 = NaN;
  95153. this.upperLimit3 = NaN;
  95154. this.limitVelocity3 = NaN;
  95155. this.limitState3 = 0; // -1: at lower, 0: locked, 1: at upper, 2: free
  95156. this.enableMotor3 = false;
  95157. this.motorSpeed3 = NaN;
  95158. this.maxMotorForce3 = NaN;
  95159. this.maxMotorImpulse3 = NaN;
  95160. this.k00 = NaN; // K = J*M*JT
  95161. this.k01 = NaN;
  95162. this.k02 = NaN;
  95163. this.k10 = NaN;
  95164. this.k11 = NaN;
  95165. this.k12 = NaN;
  95166. this.k20 = NaN;
  95167. this.k21 = NaN;
  95168. this.k22 = NaN;
  95169. this.kv00 = NaN; // diagonals without CFMs
  95170. this.kv11 = NaN;
  95171. this.kv22 = NaN;
  95172. this.dv00 = NaN; // ...inverted
  95173. this.dv11 = NaN;
  95174. this.dv22 = NaN;
  95175. this.d00 = NaN; // K^-1
  95176. this.d01 = NaN;
  95177. this.d02 = NaN;
  95178. this.d10 = NaN;
  95179. this.d11 = NaN;
  95180. this.d12 = NaN;
  95181. this.d20 = NaN;
  95182. this.d21 = NaN;
  95183. this.d22 = NaN;
  95184. this.limitMotor1 = limitMotor1;
  95185. this.limitMotor2 = limitMotor2;
  95186. this.limitMotor3 = limitMotor3;
  95187. this.b1 = joint.body1;
  95188. this.b2 = joint.body2;
  95189. this.a1 = this.b1.angularVelocity;
  95190. this.a2 = this.b2.angularVelocity;
  95191. this.i1 = this.b1.inverseInertia;
  95192. this.i2 = this.b2.inverseInertia;
  95193. this.limitImpulse1 = 0;
  95194. this.motorImpulse1 = 0;
  95195. this.limitImpulse2 = 0;
  95196. this.motorImpulse2 = 0;
  95197. this.limitImpulse3 = 0;
  95198. this.motorImpulse3 = 0;
  95199. }
  95200. OIMO.Rotational3Constraint.prototype = {
  95201. constructor: OIMO.Rotational3Constraint,
  95202. preSolve: function (timeStep, invTimeStep) {
  95203. this.ax1 = this.limitMotor1.axis.x;
  95204. this.ay1 = this.limitMotor1.axis.y;
  95205. this.az1 = this.limitMotor1.axis.z;
  95206. this.ax2 = this.limitMotor2.axis.x;
  95207. this.ay2 = this.limitMotor2.axis.y;
  95208. this.az2 = this.limitMotor2.axis.z;
  95209. this.ax3 = this.limitMotor3.axis.x;
  95210. this.ay3 = this.limitMotor3.axis.y;
  95211. this.az3 = this.limitMotor3.axis.z;
  95212. this.lowerLimit1 = this.limitMotor1.lowerLimit;
  95213. this.upperLimit1 = this.limitMotor1.upperLimit;
  95214. this.motorSpeed1 = this.limitMotor1.motorSpeed;
  95215. this.maxMotorForce1 = this.limitMotor1.maxMotorForce;
  95216. this.enableMotor1 = this.maxMotorForce1 > 0;
  95217. this.lowerLimit2 = this.limitMotor2.lowerLimit;
  95218. this.upperLimit2 = this.limitMotor2.upperLimit;
  95219. this.motorSpeed2 = this.limitMotor2.motorSpeed;
  95220. this.maxMotorForce2 = this.limitMotor2.maxMotorForce;
  95221. this.enableMotor2 = this.maxMotorForce2 > 0;
  95222. this.lowerLimit3 = this.limitMotor3.lowerLimit;
  95223. this.upperLimit3 = this.limitMotor3.upperLimit;
  95224. this.motorSpeed3 = this.limitMotor3.motorSpeed;
  95225. this.maxMotorForce3 = this.limitMotor3.maxMotorForce;
  95226. this.enableMotor3 = this.maxMotorForce3 > 0;
  95227. var ti1 = this.i1.elements;
  95228. var ti2 = this.i2.elements;
  95229. this.i1e00 = ti1[0];
  95230. this.i1e01 = ti1[1];
  95231. this.i1e02 = ti1[2];
  95232. this.i1e10 = ti1[3];
  95233. this.i1e11 = ti1[4];
  95234. this.i1e12 = ti1[5];
  95235. this.i1e20 = ti1[6];
  95236. this.i1e21 = ti1[7];
  95237. this.i1e22 = ti1[8];
  95238. this.i2e00 = ti2[0];
  95239. this.i2e01 = ti2[1];
  95240. this.i2e02 = ti2[2];
  95241. this.i2e10 = ti2[3];
  95242. this.i2e11 = ti2[4];
  95243. this.i2e12 = ti2[5];
  95244. this.i2e20 = ti2[6];
  95245. this.i2e21 = ti2[7];
  95246. this.i2e22 = ti2[8];
  95247. var frequency1 = this.limitMotor1.frequency;
  95248. var frequency2 = this.limitMotor2.frequency;
  95249. var frequency3 = this.limitMotor3.frequency;
  95250. var enableSpring1 = frequency1 > 0;
  95251. var enableSpring2 = frequency2 > 0;
  95252. var enableSpring3 = frequency3 > 0;
  95253. var enableLimit1 = this.lowerLimit1 <= this.upperLimit1;
  95254. var enableLimit2 = this.lowerLimit2 <= this.upperLimit2;
  95255. var enableLimit3 = this.lowerLimit3 <= this.upperLimit3;
  95256. var angle1 = this.limitMotor1.angle;
  95257. if (enableLimit1) {
  95258. if (this.lowerLimit1 == this.upperLimit1) {
  95259. if (this.limitState1 != 0) {
  95260. this.limitState1 = 0;
  95261. this.limitImpulse1 = 0;
  95262. }
  95263. this.limitVelocity1 = this.lowerLimit1 - angle1;
  95264. } else if (angle1 < this.lowerLimit1) {
  95265. if (this.limitState1 != -1) {
  95266. this.limitState1 = -1;
  95267. this.limitImpulse1 = 0;
  95268. }
  95269. this.limitVelocity1 = this.lowerLimit1 - angle1;
  95270. } else if (angle1 > this.upperLimit1) {
  95271. if (this.limitState1 != 1) {
  95272. this.limitState1 = 1;
  95273. this.limitImpulse1 = 0;
  95274. }
  95275. this.limitVelocity1 = this.upperLimit1 - angle1;
  95276. } else {
  95277. this.limitState1 = 2;
  95278. this.limitImpulse1 = 0;
  95279. this.limitVelocity1 = 0;
  95280. }
  95281. if (!enableSpring1) {
  95282. if (this.limitVelocity1 > 0.02) this.limitVelocity1 -= 0.02;
  95283. else if (this.limitVelocity1 < -0.02) this.limitVelocity1 += 0.02;
  95284. else this.limitVelocity1 = 0;
  95285. }
  95286. } else {
  95287. this.limitState1 = 2;
  95288. this.limitImpulse1 = 0;
  95289. }
  95290. var angle2 = this.limitMotor2.angle;
  95291. if (enableLimit2) {
  95292. if (this.lowerLimit2 == this.upperLimit2) {
  95293. if (this.limitState2 != 0) {
  95294. this.limitState2 = 0;
  95295. this.limitImpulse2 = 0;
  95296. }
  95297. this.limitVelocity2 = this.lowerLimit2 - angle2;
  95298. } else if (angle2 < this.lowerLimit2) {
  95299. if (this.limitState2 != -1) {
  95300. this.limitState2 = -1;
  95301. this.limitImpulse2 = 0;
  95302. }
  95303. this.limitVelocity2 = this.lowerLimit2 - angle2;
  95304. } else if (angle2 > this.upperLimit2) {
  95305. if (this.limitState2 != 1) {
  95306. this.limitState2 = 1;
  95307. this.limitImpulse2 = 0;
  95308. }
  95309. this.limitVelocity2 = this.upperLimit2 - angle2;
  95310. } else {
  95311. this.limitState2 = 2;
  95312. this.limitImpulse2 = 0;
  95313. this.limitVelocity2 = 0;
  95314. }
  95315. if (!enableSpring2) {
  95316. if (this.limitVelocity2 > 0.02) this.limitVelocity2 -= 0.02;
  95317. else if (this.limitVelocity2 < -0.02) this.limitVelocity2 += 0.02;
  95318. else this.limitVelocity2 = 0;
  95319. }
  95320. } else {
  95321. this.limitState2 = 2;
  95322. this.limitImpulse2 = 0;
  95323. }
  95324. var angle3 = this.limitMotor3.angle;
  95325. if (enableLimit3) {
  95326. if (this.lowerLimit3 == this.upperLimit3) {
  95327. if (this.limitState3 != 0) {
  95328. this.limitState3 = 0;
  95329. this.limitImpulse3 = 0;
  95330. }
  95331. this.limitVelocity3 = this.lowerLimit3 - angle3;
  95332. } else if (angle3 < this.lowerLimit3) {
  95333. if (this.limitState3 != -1) {
  95334. this.limitState3 = -1;
  95335. this.limitImpulse3 = 0;
  95336. }
  95337. this.limitVelocity3 = this.lowerLimit3 - angle3;
  95338. } else if (angle3 > this.upperLimit3) {
  95339. if (this.limitState3 != 1) {
  95340. this.limitState3 = 1;
  95341. this.limitImpulse3 = 0;
  95342. }
  95343. this.limitVelocity3 = this.upperLimit3 - angle3;
  95344. } else {
  95345. this.limitState3 = 2;
  95346. this.limitImpulse3 = 0;
  95347. this.limitVelocity3 = 0;
  95348. }
  95349. if (!enableSpring3) {
  95350. if (this.limitVelocity3 > 0.02) this.limitVelocity3 -= 0.02;
  95351. else if (this.limitVelocity3 < -0.02) this.limitVelocity3 += 0.02;
  95352. else this.limitVelocity3 = 0;
  95353. }
  95354. } else {
  95355. this.limitState3 = 2;
  95356. this.limitImpulse3 = 0;
  95357. }
  95358. if (this.enableMotor1 && (this.limitState1 != 0 || enableSpring1)) {
  95359. this.maxMotorImpulse1 = this.maxMotorForce1 * timeStep;
  95360. } else {
  95361. this.motorImpulse1 = 0;
  95362. this.maxMotorImpulse1 = 0;
  95363. }
  95364. if (this.enableMotor2 && (this.limitState2 != 0 || enableSpring2)) {
  95365. this.maxMotorImpulse2 = this.maxMotorForce2 * timeStep;
  95366. } else {
  95367. this.motorImpulse2 = 0;
  95368. this.maxMotorImpulse2 = 0;
  95369. }
  95370. if (this.enableMotor3 && (this.limitState3 != 0 || enableSpring3)) {
  95371. this.maxMotorImpulse3 = this.maxMotorForce3 * timeStep;
  95372. } else {
  95373. this.motorImpulse3 = 0;
  95374. this.maxMotorImpulse3 = 0;
  95375. }
  95376. // build jacobians
  95377. this.a1x1 = this.ax1 * this.i1e00 + this.ay1 * this.i1e01 + this.az1 * this.i1e02;
  95378. this.a1y1 = this.ax1 * this.i1e10 + this.ay1 * this.i1e11 + this.az1 * this.i1e12;
  95379. this.a1z1 = this.ax1 * this.i1e20 + this.ay1 * this.i1e21 + this.az1 * this.i1e22;
  95380. this.a2x1 = this.ax1 * this.i2e00 + this.ay1 * this.i2e01 + this.az1 * this.i2e02;
  95381. this.a2y1 = this.ax1 * this.i2e10 + this.ay1 * this.i2e11 + this.az1 * this.i2e12;
  95382. this.a2z1 = this.ax1 * this.i2e20 + this.ay1 * this.i2e21 + this.az1 * this.i2e22;
  95383. this.a1x2 = this.ax2 * this.i1e00 + this.ay2 * this.i1e01 + this.az2 * this.i1e02;
  95384. this.a1y2 = this.ax2 * this.i1e10 + this.ay2 * this.i1e11 + this.az2 * this.i1e12;
  95385. this.a1z2 = this.ax2 * this.i1e20 + this.ay2 * this.i1e21 + this.az2 * this.i1e22;
  95386. this.a2x2 = this.ax2 * this.i2e00 + this.ay2 * this.i2e01 + this.az2 * this.i2e02;
  95387. this.a2y2 = this.ax2 * this.i2e10 + this.ay2 * this.i2e11 + this.az2 * this.i2e12;
  95388. this.a2z2 = this.ax2 * this.i2e20 + this.ay2 * this.i2e21 + this.az2 * this.i2e22;
  95389. this.a1x3 = this.ax3 * this.i1e00 + this.ay3 * this.i1e01 + this.az3 * this.i1e02;
  95390. this.a1y3 = this.ax3 * this.i1e10 + this.ay3 * this.i1e11 + this.az3 * this.i1e12;
  95391. this.a1z3 = this.ax3 * this.i1e20 + this.ay3 * this.i1e21 + this.az3 * this.i1e22;
  95392. this.a2x3 = this.ax3 * this.i2e00 + this.ay3 * this.i2e01 + this.az3 * this.i2e02;
  95393. this.a2y3 = this.ax3 * this.i2e10 + this.ay3 * this.i2e11 + this.az3 * this.i2e12;
  95394. this.a2z3 = this.ax3 * this.i2e20 + this.ay3 * this.i2e21 + this.az3 * this.i2e22;
  95395. // build an impulse matrix
  95396. this.k00 = this.ax1 * (this.a1x1 + this.a2x1) + this.ay1 * (this.a1y1 + this.a2y1) + this.az1 * (this.a1z1 + this.a2z1);
  95397. this.k01 = this.ax1 * (this.a1x2 + this.a2x2) + this.ay1 * (this.a1y2 + this.a2y2) + this.az1 * (this.a1z2 + this.a2z2);
  95398. this.k02 = this.ax1 * (this.a1x3 + this.a2x3) + this.ay1 * (this.a1y3 + this.a2y3) + this.az1 * (this.a1z3 + this.a2z3);
  95399. this.k10 = this.ax2 * (this.a1x1 + this.a2x1) + this.ay2 * (this.a1y1 + this.a2y1) + this.az2 * (this.a1z1 + this.a2z1);
  95400. this.k11 = this.ax2 * (this.a1x2 + this.a2x2) + this.ay2 * (this.a1y2 + this.a2y2) + this.az2 * (this.a1z2 + this.a2z2);
  95401. this.k12 = this.ax2 * (this.a1x3 + this.a2x3) + this.ay2 * (this.a1y3 + this.a2y3) + this.az2 * (this.a1z3 + this.a2z3);
  95402. this.k20 = this.ax3 * (this.a1x1 + this.a2x1) + this.ay3 * (this.a1y1 + this.a2y1) + this.az3 * (this.a1z1 + this.a2z1);
  95403. this.k21 = this.ax3 * (this.a1x2 + this.a2x2) + this.ay3 * (this.a1y2 + this.a2y2) + this.az3 * (this.a1z2 + this.a2z2);
  95404. this.k22 = this.ax3 * (this.a1x3 + this.a2x3) + this.ay3 * (this.a1y3 + this.a2y3) + this.az3 * (this.a1z3 + this.a2z3);
  95405. this.kv00 = this.k00;
  95406. this.kv11 = this.k11;
  95407. this.kv22 = this.k22;
  95408. this.dv00 = 1 / this.kv00;
  95409. this.dv11 = 1 / this.kv11;
  95410. this.dv22 = 1 / this.kv22;
  95411. if (enableSpring1 && this.limitState1 != 2) {
  95412. var omega = 6.2831853 * frequency1;
  95413. var k = omega * omega * timeStep;
  95414. var dmp = invTimeStep / (k + 2 * this.limitMotor1.dampingRatio * omega);
  95415. this.cfm1 = this.kv00 * dmp;
  95416. this.limitVelocity1 *= k * dmp;
  95417. } else {
  95418. this.cfm1 = 0;
  95419. this.limitVelocity1 *= invTimeStep * 0.05;
  95420. }
  95421. if (enableSpring2 && this.limitState2 != 2) {
  95422. omega = 6.2831853 * frequency2;
  95423. k = omega * omega * timeStep;
  95424. dmp = invTimeStep / (k + 2 * this.limitMotor2.dampingRatio * omega);
  95425. this.cfm2 = this.kv11 * dmp;
  95426. this.limitVelocity2 *= k * dmp;
  95427. } else {
  95428. this.cfm2 = 0;
  95429. this.limitVelocity2 *= invTimeStep * 0.05;
  95430. }
  95431. if (enableSpring3 && this.limitState3 != 2) {
  95432. omega = 6.2831853 * frequency3;
  95433. k = omega * omega * timeStep;
  95434. dmp = invTimeStep / (k + 2 * this.limitMotor3.dampingRatio * omega);
  95435. this.cfm3 = this.kv22 * dmp;
  95436. this.limitVelocity3 *= k * dmp;
  95437. } else {
  95438. this.cfm3 = 0;
  95439. this.limitVelocity3 *= invTimeStep * 0.05;
  95440. }
  95441. this.k00 += this.cfm1;
  95442. this.k11 += this.cfm2;
  95443. this.k22 += this.cfm3;
  95444. var inv = 1 / (
  95445. this.k00 * (this.k11 * this.k22 - this.k21 * this.k12) +
  95446. this.k10 * (this.k21 * this.k02 - this.k01 * this.k22) +
  95447. this.k20 * (this.k01 * this.k12 - this.k11 * this.k02)
  95448. );
  95449. this.d00 = (this.k11 * this.k22 - this.k12 * this.k21) * inv;
  95450. this.d01 = (this.k02 * this.k21 - this.k01 * this.k22) * inv;
  95451. this.d02 = (this.k01 * this.k12 - this.k02 * this.k11) * inv;
  95452. this.d10 = (this.k12 * this.k20 - this.k10 * this.k22) * inv;
  95453. this.d11 = (this.k00 * this.k22 - this.k02 * this.k20) * inv;
  95454. this.d12 = (this.k02 * this.k10 - this.k00 * this.k12) * inv;
  95455. this.d20 = (this.k10 * this.k21 - this.k11 * this.k20) * inv;
  95456. this.d21 = (this.k01 * this.k20 - this.k00 * this.k21) * inv;
  95457. this.d22 = (this.k00 * this.k11 - this.k01 * this.k10) * inv;
  95458. this.limitImpulse1 *= 0.95;
  95459. this.motorImpulse1 *= 0.95;
  95460. this.limitImpulse2 *= 0.95;
  95461. this.motorImpulse2 *= 0.95;
  95462. this.limitImpulse3 *= 0.95;
  95463. this.motorImpulse3 *= 0.95;
  95464. var totalImpulse1 = this.limitImpulse1 + this.motorImpulse1;
  95465. var totalImpulse2 = this.limitImpulse2 + this.motorImpulse2;
  95466. var totalImpulse3 = this.limitImpulse3 + this.motorImpulse3;
  95467. this.a1.x += totalImpulse1 * this.a1x1 + totalImpulse2 * this.a1x2 + totalImpulse3 * this.a1x3;
  95468. this.a1.y += totalImpulse1 * this.a1y1 + totalImpulse2 * this.a1y2 + totalImpulse3 * this.a1y3;
  95469. this.a1.z += totalImpulse1 * this.a1z1 + totalImpulse2 * this.a1z2 + totalImpulse3 * this.a1z3;
  95470. this.a2.x -= totalImpulse1 * this.a2x1 + totalImpulse2 * this.a2x2 + totalImpulse3 * this.a2x3;
  95471. this.a2.y -= totalImpulse1 * this.a2y1 + totalImpulse2 * this.a2y2 + totalImpulse3 * this.a2y3;
  95472. this.a2.z -= totalImpulse1 * this.a2z1 + totalImpulse2 * this.a2z2 + totalImpulse3 * this.a2z3;
  95473. },
  95474. solve_: function () {
  95475. var rvx = this.a2.x - this.a1.x;
  95476. var rvy = this.a2.y - this.a1.y;
  95477. var rvz = this.a2.z - this.a1.z;
  95478. this.limitVelocity3 = 30;
  95479. var rvn1 = rvx * this.ax1 + rvy * this.ay1 + rvz * this.az1 - this.limitVelocity1;
  95480. var rvn2 = rvx * this.ax2 + rvy * this.ay2 + rvz * this.az2 - this.limitVelocity2;
  95481. var rvn3 = rvx * this.ax3 + rvy * this.ay3 + rvz * this.az3 - this.limitVelocity3;
  95482. var dLimitImpulse1 = rvn1 * this.d00 + rvn2 * this.d01 + rvn3 * this.d02;
  95483. var dLimitImpulse2 = rvn1 * this.d10 + rvn2 * this.d11 + rvn3 * this.d12;
  95484. var dLimitImpulse3 = rvn1 * this.d20 + rvn2 * this.d21 + rvn3 * this.d22;
  95485. this.limitImpulse1 += dLimitImpulse1;
  95486. this.limitImpulse2 += dLimitImpulse2;
  95487. this.limitImpulse3 += dLimitImpulse3;
  95488. this.a1.x += dLimitImpulse1 * this.a1x1 + dLimitImpulse2 * this.a1x2 + dLimitImpulse3 * this.a1x3;
  95489. this.a1.y += dLimitImpulse1 * this.a1y1 + dLimitImpulse2 * this.a1y2 + dLimitImpulse3 * this.a1y3;
  95490. this.a1.z += dLimitImpulse1 * this.a1z1 + dLimitImpulse2 * this.a1z2 + dLimitImpulse3 * this.a1z3;
  95491. this.a2.x -= dLimitImpulse1 * this.a2x1 + dLimitImpulse2 * this.a2x2 + dLimitImpulse3 * this.a2x3;
  95492. this.a2.y -= dLimitImpulse1 * this.a2y1 + dLimitImpulse2 * this.a2y2 + dLimitImpulse3 * this.a2y3;
  95493. this.a2.z -= dLimitImpulse1 * this.a2z1 + dLimitImpulse2 * this.a2z2 + dLimitImpulse3 * this.a2z3;
  95494. },
  95495. solve: function () {
  95496. var rvx = this.a2.x - this.a1.x;
  95497. var rvy = this.a2.y - this.a1.y;
  95498. var rvz = this.a2.z - this.a1.z;
  95499. var rvn1 = rvx * this.ax1 + rvy * this.ay1 + rvz * this.az1;
  95500. var rvn2 = rvx * this.ax2 + rvy * this.ay2 + rvz * this.az2;
  95501. var rvn3 = rvx * this.ax3 + rvy * this.ay3 + rvz * this.az3;
  95502. var oldMotorImpulse1 = this.motorImpulse1;
  95503. var oldMotorImpulse2 = this.motorImpulse2;
  95504. var oldMotorImpulse3 = this.motorImpulse3;
  95505. var dMotorImpulse1 = 0;
  95506. var dMotorImpulse2 = 0;
  95507. var dMotorImpulse3 = 0;
  95508. if (this.enableMotor1) {
  95509. dMotorImpulse1 = (rvn1 - this.motorSpeed1) * this.dv00;
  95510. this.motorImpulse1 += dMotorImpulse1;
  95511. if (this.motorImpulse1 > this.maxMotorImpulse1) { // clamp motor impulse
  95512. this.motorImpulse1 = this.maxMotorImpulse1;
  95513. } else if (this.motorImpulse1 < -this.maxMotorImpulse1) {
  95514. this.motorImpulse1 = -this.maxMotorImpulse1;
  95515. }
  95516. dMotorImpulse1 = this.motorImpulse1 - oldMotorImpulse1;
  95517. }
  95518. if (this.enableMotor2) {
  95519. dMotorImpulse2 = (rvn2 - this.motorSpeed2) * this.dv11;
  95520. this.motorImpulse2 += dMotorImpulse2;
  95521. if (this.motorImpulse2 > this.maxMotorImpulse2) { // clamp motor impulse
  95522. this.motorImpulse2 = this.maxMotorImpulse2;
  95523. } else if (this.motorImpulse2 < -this.maxMotorImpulse2) {
  95524. this.motorImpulse2 = -this.maxMotorImpulse2;
  95525. }
  95526. dMotorImpulse2 = this.motorImpulse2 - oldMotorImpulse2;
  95527. }
  95528. if (this.enableMotor3) {
  95529. dMotorImpulse3 = (rvn3 - this.motorSpeed3) * this.dv22;
  95530. this.motorImpulse3 += dMotorImpulse3;
  95531. if (this.motorImpulse3 > this.maxMotorImpulse3) { // clamp motor impulse
  95532. this.motorImpulse3 = this.maxMotorImpulse3;
  95533. } else if (this.motorImpulse3 < -this.maxMotorImpulse3) {
  95534. this.motorImpulse3 = -this.maxMotorImpulse3;
  95535. }
  95536. dMotorImpulse3 = this.motorImpulse3 - oldMotorImpulse3;
  95537. }
  95538. // apply motor impulse to relative velocity
  95539. rvn1 += dMotorImpulse1 * this.kv00 + dMotorImpulse2 * this.k01 + dMotorImpulse3 * this.k02;
  95540. rvn2 += dMotorImpulse1 * this.k10 + dMotorImpulse2 * this.kv11 + dMotorImpulse3 * this.k12;
  95541. rvn3 += dMotorImpulse1 * this.k20 + dMotorImpulse2 * this.k21 + dMotorImpulse3 * this.kv22;
  95542. // subtract target velocity and applied impulse
  95543. rvn1 -= this.limitVelocity1 + this.limitImpulse1 * this.cfm1;
  95544. rvn2 -= this.limitVelocity2 + this.limitImpulse2 * this.cfm2;
  95545. rvn3 -= this.limitVelocity3 + this.limitImpulse3 * this.cfm3;
  95546. var oldLimitImpulse1 = this.limitImpulse1;
  95547. var oldLimitImpulse2 = this.limitImpulse2;
  95548. var oldLimitImpulse3 = this.limitImpulse3;
  95549. var dLimitImpulse1 = rvn1 * this.d00 + rvn2 * this.d01 + rvn3 * this.d02;
  95550. var dLimitImpulse2 = rvn1 * this.d10 + rvn2 * this.d11 + rvn3 * this.d12;
  95551. var dLimitImpulse3 = rvn1 * this.d20 + rvn2 * this.d21 + rvn3 * this.d22;
  95552. this.limitImpulse1 += dLimitImpulse1;
  95553. this.limitImpulse2 += dLimitImpulse2;
  95554. this.limitImpulse3 += dLimitImpulse3;
  95555. // clamp
  95556. var clampState = 0;
  95557. if (this.limitState1 == 2 || this.limitImpulse1 * this.limitState1 < 0) {
  95558. dLimitImpulse1 = -oldLimitImpulse1;
  95559. rvn2 += dLimitImpulse1 * this.k10;
  95560. rvn3 += dLimitImpulse1 * this.k20;
  95561. clampState |= 1;
  95562. }
  95563. if (this.limitState2 == 2 || this.limitImpulse2 * this.limitState2 < 0) {
  95564. dLimitImpulse2 = -oldLimitImpulse2;
  95565. rvn1 += dLimitImpulse2 * this.k01;
  95566. rvn3 += dLimitImpulse2 * this.k21;
  95567. clampState |= 2;
  95568. }
  95569. if (this.limitState3 == 2 || this.limitImpulse3 * this.limitState3 < 0) {
  95570. dLimitImpulse3 = -oldLimitImpulse3;
  95571. rvn1 += dLimitImpulse3 * this.k02;
  95572. rvn2 += dLimitImpulse3 * this.k12;
  95573. clampState |= 4;
  95574. }
  95575. // update un-clamped impulse
  95576. // TODO: isolate division
  95577. var det;
  95578. switch (clampState) {
  95579. case 1: // update 2 3
  95580. det = 1 / (this.k11 * this.k22 - this.k12 * this.k21);
  95581. dLimitImpulse2 = (this.k22 * rvn2 + -this.k12 * rvn3) * det;
  95582. dLimitImpulse3 = (-this.k21 * rvn2 + this.k11 * rvn3) * det;
  95583. break;
  95584. case 2: // update 1 3
  95585. det = 1 / (this.k00 * this.k22 - this.k02 * this.k20);
  95586. dLimitImpulse1 = (this.k22 * rvn1 + -this.k02 * rvn3) * det;
  95587. dLimitImpulse3 = (-this.k20 * rvn1 + this.k00 * rvn3) * det;
  95588. break;
  95589. case 3: // update 3
  95590. dLimitImpulse3 = rvn3 / this.k22;
  95591. break;
  95592. case 4: // update 1 2
  95593. det = 1 / (this.k00 * this.k11 - this.k01 * this.k10);
  95594. dLimitImpulse1 = (this.k11 * rvn1 + -this.k01 * rvn2) * det;
  95595. dLimitImpulse2 = (-this.k10 * rvn1 + this.k00 * rvn2) * det;
  95596. break;
  95597. case 5: // update 2
  95598. dLimitImpulse2 = rvn2 / this.k11;
  95599. break;
  95600. case 6: // update 1
  95601. dLimitImpulse1 = rvn1 / this.k00;
  95602. break;
  95603. }
  95604. this.limitImpulse1 = dLimitImpulse1 + oldLimitImpulse1;
  95605. this.limitImpulse2 = dLimitImpulse2 + oldLimitImpulse2;
  95606. this.limitImpulse3 = dLimitImpulse3 + oldLimitImpulse3;
  95607. var dImpulse1 = dMotorImpulse1 + dLimitImpulse1;
  95608. var dImpulse2 = dMotorImpulse2 + dLimitImpulse2;
  95609. var dImpulse3 = dMotorImpulse3 + dLimitImpulse3;
  95610. // apply impulse
  95611. this.a1.x += dImpulse1 * this.a1x1 + dImpulse2 * this.a1x2 + dImpulse3 * this.a1x3;
  95612. this.a1.y += dImpulse1 * this.a1y1 + dImpulse2 * this.a1y2 + dImpulse3 * this.a1y3;
  95613. this.a1.z += dImpulse1 * this.a1z1 + dImpulse2 * this.a1z2 + dImpulse3 * this.a1z3;
  95614. this.a2.x -= dImpulse1 * this.a2x1 + dImpulse2 * this.a2x2 + dImpulse3 * this.a2x3;
  95615. this.a2.y -= dImpulse1 * this.a2y1 + dImpulse2 * this.a2y2 + dImpulse3 * this.a2y3;
  95616. this.a2.z -= dImpulse1 * this.a2z1 + dImpulse2 * this.a2z2 + dImpulse3 * this.a2z3;
  95617. rvx = this.a2.x - this.a1.x;
  95618. rvy = this.a2.y - this.a1.y;
  95619. rvz = this.a2.z - this.a1.z;
  95620. rvn2 = rvx * this.ax2 + rvy * this.ay2 + rvz * this.az2;
  95621. }
  95622. }
  95623. /**
  95624. * A rotational constraint for various joints.
  95625. * @author saharan
  95626. */
  95627. OIMO.RotationalConstraint = function (joint, limitMotor) {
  95628. this.cfm = NaN;
  95629. this.i1e00 = NaN;
  95630. this.i1e01 = NaN;
  95631. this.i1e02 = NaN;
  95632. this.i1e10 = NaN;
  95633. this.i1e11 = NaN;
  95634. this.i1e12 = NaN;
  95635. this.i1e20 = NaN;
  95636. this.i1e21 = NaN;
  95637. this.i1e22 = NaN;
  95638. this.i2e00 = NaN;
  95639. this.i2e01 = NaN;
  95640. this.i2e02 = NaN;
  95641. this.i2e10 = NaN;
  95642. this.i2e11 = NaN;
  95643. this.i2e12 = NaN;
  95644. this.i2e20 = NaN;
  95645. this.i2e21 = NaN;
  95646. this.i2e22 = NaN;
  95647. this.motorDenom = NaN;
  95648. this.invMotorDenom = NaN;
  95649. this.invDenom = NaN;
  95650. this.ax = NaN;
  95651. this.ay = NaN;
  95652. this.az = NaN;
  95653. this.a1x = NaN;
  95654. this.a1y = NaN;
  95655. this.a1z = NaN;
  95656. this.a2x = NaN;
  95657. this.a2y = NaN;
  95658. this.a2z = NaN;
  95659. this.enableLimit = false;
  95660. this.lowerLimit = NaN;
  95661. this.upperLimit = NaN;
  95662. this.limitVelocity = NaN;
  95663. this.limitState = 0; // -1: at lower, 0: locked, 1: at upper, 2: free
  95664. this.enableMotor = false;
  95665. this.motorSpeed = NaN;
  95666. this.maxMotorForce = NaN;
  95667. this.maxMotorImpulse = NaN;
  95668. this.limitMotor = limitMotor;
  95669. this.b1 = joint.body1;
  95670. this.b2 = joint.body2;
  95671. this.a1 = this.b1.angularVelocity;
  95672. this.a2 = this.b2.angularVelocity;
  95673. this.i1 = this.b1.inverseInertia;
  95674. this.i2 = this.b2.inverseInertia;
  95675. this.limitImpulse = 0;
  95676. this.motorImpulse = 0;
  95677. }
  95678. OIMO.RotationalConstraint.prototype = {
  95679. constructor: OIMO.RotationalConstraint,
  95680. preSolve: function (timeStep, invTimeStep) {
  95681. this.ax = this.limitMotor.axis.x;
  95682. this.ay = this.limitMotor.axis.y;
  95683. this.az = this.limitMotor.axis.z;
  95684. this.lowerLimit = this.limitMotor.lowerLimit;
  95685. this.upperLimit = this.limitMotor.upperLimit;
  95686. this.motorSpeed = this.limitMotor.motorSpeed;
  95687. this.maxMotorForce = this.limitMotor.maxMotorForce;
  95688. this.enableMotor = this.maxMotorForce > 0;
  95689. var ti1 = this.i1.elements;
  95690. var ti2 = this.i2.elements;
  95691. this.i1e00 = ti1[0];
  95692. this.i1e01 = ti1[1];
  95693. this.i1e02 = ti1[2];
  95694. this.i1e10 = ti1[3];
  95695. this.i1e11 = ti1[4];
  95696. this.i1e12 = ti1[5];
  95697. this.i1e20 = ti1[6];
  95698. this.i1e21 = ti1[7];
  95699. this.i1e22 = ti1[8];
  95700. this.i2e00 = ti2[0];
  95701. this.i2e01 = ti2[1];
  95702. this.i2e02 = ti2[2];
  95703. this.i2e10 = ti2[3];
  95704. this.i2e11 = ti2[4];
  95705. this.i2e12 = ti2[5];
  95706. this.i2e20 = ti2[6];
  95707. this.i2e21 = ti2[7];
  95708. this.i2e22 = ti2[8];
  95709. var frequency = this.limitMotor.frequency;
  95710. var enableSpring = frequency > 0;
  95711. var enableLimit = this.lowerLimit <= this.upperLimit;
  95712. var angle = this.limitMotor.angle;
  95713. if (enableLimit) {
  95714. if (this.lowerLimit == this.upperLimit) {
  95715. if (this.limitState != 0) {
  95716. this.limitState = 0;
  95717. this.limitImpulse = 0;
  95718. }
  95719. this.limitVelocity = this.lowerLimit - angle;
  95720. } else if (angle < this.lowerLimit) {
  95721. if (this.limitState != -1) {
  95722. this.limitState = -1;
  95723. this.limitImpulse = 0;
  95724. }
  95725. this.limitVelocity = this.lowerLimit - angle;
  95726. } else if (angle > this.upperLimit) {
  95727. if (this.limitState != 1) {
  95728. this.limitState = 1;
  95729. this.limitImpulse = 0;
  95730. }
  95731. this.limitVelocity = this.upperLimit - angle;
  95732. } else {
  95733. this.limitState = 2;
  95734. this.limitImpulse = 0;
  95735. this.limitVelocity = 0;
  95736. }
  95737. if (!enableSpring) {
  95738. if (this.limitVelocity > 0.02) this.limitVelocity -= 0.02;
  95739. else if (this.limitVelocity < -0.02) this.limitVelocity += 0.02;
  95740. else this.limitVelocity = 0;
  95741. }
  95742. } else {
  95743. this.limitState = 2;
  95744. this.limitImpulse = 0;
  95745. }
  95746. if (this.enableMotor && (this.limitState != 0 || enableSpring)) {
  95747. this.maxMotorImpulse = this.maxMotorForce * timeStep;
  95748. } else {
  95749. this.motorImpulse = 0;
  95750. this.maxMotorImpulse = 0;
  95751. }
  95752. this.a1x = this.ax * this.i1e00 + this.ay * this.i1e01 + this.az * this.i1e02;
  95753. this.a1y = this.ax * this.i1e10 + this.ay * this.i1e11 + this.az * this.i1e12;
  95754. this.a1z = this.ax * this.i1e20 + this.ay * this.i1e21 + this.az * this.i1e22;
  95755. this.a2x = this.ax * this.i2e00 + this.ay * this.i2e01 + this.az * this.i2e02;
  95756. this.a2y = this.ax * this.i2e10 + this.ay * this.i2e11 + this.az * this.i2e12;
  95757. this.a2z = this.ax * this.i2e20 + this.ay * this.i2e21 + this.az * this.i2e22;
  95758. this.motorDenom = this.ax * (this.a1x + this.a2x) + this.ay * (this.a1y + this.a2y) + this.az * (this.a1z + this.a2z);
  95759. this.invMotorDenom = 1 / this.motorDenom;
  95760. if (enableSpring && this.limitState != 2) {
  95761. var omega = 6.2831853 * frequency;
  95762. var k = omega * omega * timeStep;
  95763. var dmp = invTimeStep / (k + 2 * this.limitMotor.dampingRatio * omega);
  95764. this.cfm = this.motorDenom * dmp;
  95765. this.limitVelocity *= k * dmp;
  95766. } else {
  95767. this.cfm = 0;
  95768. this.limitVelocity *= invTimeStep * 0.05;
  95769. }
  95770. this.invDenom = 1 / (this.motorDenom + this.cfm);
  95771. this.limitImpulse *= 0.95;
  95772. this.motorImpulse *= 0.95;
  95773. var totalImpulse = this.limitImpulse + this.motorImpulse;
  95774. this.a1.x += totalImpulse * this.a1x;
  95775. this.a1.y += totalImpulse * this.a1y;
  95776. this.a1.z += totalImpulse * this.a1z;
  95777. this.a2.x -= totalImpulse * this.a2x;
  95778. this.a2.y -= totalImpulse * this.a2y;
  95779. this.a2.z -= totalImpulse * this.a2z;
  95780. },
  95781. solve: function () {
  95782. 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);
  95783. // motor part
  95784. var newMotorImpulse;
  95785. if (this.enableMotor) {
  95786. newMotorImpulse = (rvn - this.motorSpeed) * this.invMotorDenom;
  95787. var oldMotorImpulse = this.motorImpulse;
  95788. this.motorImpulse += newMotorImpulse;
  95789. if (this.motorImpulse > this.maxMotorImpulse) this.motorImpulse = this.maxMotorImpulse;
  95790. else if (this.motorImpulse < -this.maxMotorImpulse) this.motorImpulse = -this.maxMotorImpulse;
  95791. newMotorImpulse = this.motorImpulse - oldMotorImpulse;
  95792. rvn -= newMotorImpulse * this.motorDenom;
  95793. } else newMotorImpulse = 0;
  95794. // limit part
  95795. var newLimitImpulse;
  95796. if (this.limitState != 2) {
  95797. newLimitImpulse = (rvn - this.limitVelocity - this.limitImpulse * this.cfm) * this.invDenom;
  95798. var oldLimitImpulse = this.limitImpulse;
  95799. this.limitImpulse += newLimitImpulse;
  95800. if (this.limitImpulse * this.limitState < 0) this.limitImpulse = 0;
  95801. newLimitImpulse = this.limitImpulse - oldLimitImpulse;
  95802. } else newLimitImpulse = 0;
  95803. var totalImpulse = newLimitImpulse + newMotorImpulse;
  95804. this.a1.x += totalImpulse * this.a1x;
  95805. this.a1.y += totalImpulse * this.a1y;
  95806. this.a1.z += totalImpulse * this.a1z;
  95807. this.a2.x -= totalImpulse * this.a2x;
  95808. this.a2.y -= totalImpulse * this.a2y;
  95809. this.a2.z -= totalImpulse * this.a2z;
  95810. }
  95811. }
  95812. /**
  95813. * A three-axis translational constraint for various joints.
  95814. * @author saharan
  95815. */
  95816. OIMO.Translational3Constraint = function (joint, limitMotor1, limitMotor2, limitMotor3) {
  95817. this.m1 = NaN;
  95818. this.m2 = NaN;
  95819. this.i1e00 = NaN;
  95820. this.i1e01 = NaN;
  95821. this.i1e02 = NaN;
  95822. this.i1e10 = NaN;
  95823. this.i1e11 = NaN;
  95824. this.i1e12 = NaN;
  95825. this.i1e20 = NaN;
  95826. this.i1e21 = NaN;
  95827. this.i1e22 = NaN;
  95828. this.i2e00 = NaN;
  95829. this.i2e01 = NaN;
  95830. this.i2e02 = NaN;
  95831. this.i2e10 = NaN;
  95832. this.i2e11 = NaN;
  95833. this.i2e12 = NaN;
  95834. this.i2e20 = NaN;
  95835. this.i2e21 = NaN;
  95836. this.i2e22 = NaN;
  95837. this.ax1 = NaN;
  95838. this.ay1 = NaN;
  95839. this.az1 = NaN;
  95840. this.ax2 = NaN;
  95841. this.ay2 = NaN;
  95842. this.az2 = NaN;
  95843. this.ax3 = NaN;
  95844. this.ay3 = NaN;
  95845. this.az3 = NaN;
  95846. this.r1x = NaN;
  95847. this.r1y = NaN;
  95848. this.r1z = NaN;
  95849. this.r2x = NaN;
  95850. this.r2y = NaN;
  95851. this.r2z = NaN;
  95852. this.t1x1 = NaN;// jacobians
  95853. this.t1y1 = NaN;
  95854. this.t1z1 = NaN;
  95855. this.t2x1 = NaN;
  95856. this.t2y1 = NaN;
  95857. this.t2z1 = NaN;
  95858. this.l1x1 = NaN;
  95859. this.l1y1 = NaN;
  95860. this.l1z1 = NaN;
  95861. this.l2x1 = NaN;
  95862. this.l2y1 = NaN;
  95863. this.l2z1 = NaN;
  95864. this.a1x1 = NaN;
  95865. this.a1y1 = NaN;
  95866. this.a1z1 = NaN;
  95867. this.a2x1 = NaN;
  95868. this.a2y1 = NaN;
  95869. this.a2z1 = NaN;
  95870. this.t1x2 = NaN;
  95871. this.t1y2 = NaN;
  95872. this.t1z2 = NaN;
  95873. this.t2x2 = NaN;
  95874. this.t2y2 = NaN;
  95875. this.t2z2 = NaN;
  95876. this.l1x2 = NaN;
  95877. this.l1y2 = NaN;
  95878. this.l1z2 = NaN;
  95879. this.l2x2 = NaN;
  95880. this.l2y2 = NaN;
  95881. this.l2z2 = NaN;
  95882. this.a1x2 = NaN;
  95883. this.a1y2 = NaN;
  95884. this.a1z2 = NaN;
  95885. this.a2x2 = NaN;
  95886. this.a2y2 = NaN;
  95887. this.a2z2 = NaN;
  95888. this.t1x3 = NaN;
  95889. this.t1y3 = NaN;
  95890. this.t1z3 = NaN;
  95891. this.t2x3 = NaN;
  95892. this.t2y3 = NaN;
  95893. this.t2z3 = NaN;
  95894. this.l1x3 = NaN;
  95895. this.l1y3 = NaN;
  95896. this.l1z3 = NaN;
  95897. this.l2x3 = NaN;
  95898. this.l2y3 = NaN;
  95899. this.l2z3 = NaN;
  95900. this.a1x3 = NaN;
  95901. this.a1y3 = NaN;
  95902. this.a1z3 = NaN;
  95903. this.a2x3 = NaN;
  95904. this.a2y3 = NaN;
  95905. this.a2z3 = NaN;
  95906. this.lowerLimit1 = NaN;
  95907. this.upperLimit1 = NaN;
  95908. this.limitVelocity1 = NaN;
  95909. this.limitState1 = 0; // -1: at lower, 0: locked, 1: at upper, 2: unlimited
  95910. this.enableMotor1 = false;
  95911. this.motorSpeed1 = NaN;
  95912. this.maxMotorForce1 = NaN;
  95913. this.maxMotorImpulse1 = NaN;
  95914. this.lowerLimit2 = NaN;
  95915. this.upperLimit2 = NaN;
  95916. this.limitVelocity2 = NaN;
  95917. this.limitState2 = 0; // -1: at lower, 0: locked, 1: at upper, 2: unlimited
  95918. this.enableMotor2 = false;
  95919. this.motorSpeed2 = NaN;
  95920. this.maxMotorForce2 = NaN;
  95921. this.maxMotorImpulse2 = NaN;
  95922. this.lowerLimit3 = NaN;
  95923. this.upperLimit3 = NaN;
  95924. this.limitVelocity3 = NaN;
  95925. this.limitState3 = 0; // -1: at lower, 0: locked, 1: at upper, 2: unlimited
  95926. this.enableMotor3 = false;
  95927. this.motorSpeed3 = NaN;
  95928. this.maxMotorForce3 = NaN;
  95929. this.maxMotorImpulse3 = NaN;
  95930. this.k00 = NaN; // K = J*M*JT
  95931. this.k01 = NaN;
  95932. this.k02 = NaN;
  95933. this.k10 = NaN;
  95934. this.k11 = NaN;
  95935. this.k12 = NaN;
  95936. this.k20 = NaN;
  95937. this.k21 = NaN;
  95938. this.k22 = NaN;
  95939. this.kv00 = NaN; // diagonals without CFMs
  95940. this.kv11 = NaN;
  95941. this.kv22 = NaN;
  95942. this.dv00 = NaN; // ...inverted
  95943. this.dv11 = NaN;
  95944. this.dv22 = NaN;
  95945. this.d00 = NaN; // K^-1
  95946. this.d01 = NaN;
  95947. this.d02 = NaN;
  95948. this.d10 = NaN;
  95949. this.d11 = NaN;
  95950. this.d12 = NaN;
  95951. this.d20 = NaN;
  95952. this.d21 = NaN;
  95953. this.d22 = NaN;
  95954. this.limitMotor1 = limitMotor1;
  95955. this.limitMotor2 = limitMotor2;
  95956. this.limitMotor3 = limitMotor3;
  95957. this.b1 = joint.body1;
  95958. this.b2 = joint.body2;
  95959. this.p1 = joint.anchorPoint1;
  95960. this.p2 = joint.anchorPoint2;
  95961. this.r1 = joint.relativeAnchorPoint1;
  95962. this.r2 = joint.relativeAnchorPoint2;
  95963. this.l1 = this.b1.linearVelocity;
  95964. this.l2 = this.b2.linearVelocity;
  95965. this.a1 = this.b1.angularVelocity;
  95966. this.a2 = this.b2.angularVelocity;
  95967. this.i1 = this.b1.inverseInertia;
  95968. this.i2 = this.b2.inverseInertia;
  95969. this.limitImpulse1 = 0;
  95970. this.motorImpulse1 = 0;
  95971. this.limitImpulse2 = 0;
  95972. this.motorImpulse2 = 0;
  95973. this.limitImpulse3 = 0;
  95974. this.motorImpulse3 = 0;
  95975. this.cfm1 = 0;// Constraint Force Mixing
  95976. this.cfm2 = 0;
  95977. this.cfm3 = 0;
  95978. this.weight = -1;
  95979. }
  95980. OIMO.Translational3Constraint.prototype = {
  95981. constructor: OIMO.Translational3Constraint,
  95982. preSolve: function (timeStep, invTimeStep) {
  95983. this.ax1 = this.limitMotor1.axis.x;
  95984. this.ay1 = this.limitMotor1.axis.y;
  95985. this.az1 = this.limitMotor1.axis.z;
  95986. this.ax2 = this.limitMotor2.axis.x;
  95987. this.ay2 = this.limitMotor2.axis.y;
  95988. this.az2 = this.limitMotor2.axis.z;
  95989. this.ax3 = this.limitMotor3.axis.x;
  95990. this.ay3 = this.limitMotor3.axis.y;
  95991. this.az3 = this.limitMotor3.axis.z;
  95992. this.lowerLimit1 = this.limitMotor1.lowerLimit;
  95993. this.upperLimit1 = this.limitMotor1.upperLimit;
  95994. this.motorSpeed1 = this.limitMotor1.motorSpeed;
  95995. this.maxMotorForce1 = this.limitMotor1.maxMotorForce;
  95996. this.enableMotor1 = this.maxMotorForce1 > 0;
  95997. this.lowerLimit2 = this.limitMotor2.lowerLimit;
  95998. this.upperLimit2 = this.limitMotor2.upperLimit;
  95999. this.motorSpeed2 = this.limitMotor2.motorSpeed;
  96000. this.maxMotorForce2 = this.limitMotor2.maxMotorForce;
  96001. this.enableMotor2 = this.maxMotorForce2 > 0;
  96002. this.lowerLimit3 = this.limitMotor3.lowerLimit;
  96003. this.upperLimit3 = this.limitMotor3.upperLimit;
  96004. this.motorSpeed3 = this.limitMotor3.motorSpeed;
  96005. this.maxMotorForce3 = this.limitMotor3.maxMotorForce;
  96006. this.enableMotor3 = this.maxMotorForce3 > 0;
  96007. this.m1 = this.b1.inverseMass;
  96008. this.m2 = this.b2.inverseMass;
  96009. var ti1 = this.i1.elements;
  96010. var ti2 = this.i2.elements;
  96011. this.i1e00 = ti1[0];
  96012. this.i1e01 = ti1[1];
  96013. this.i1e02 = ti1[2];
  96014. this.i1e10 = ti1[3];
  96015. this.i1e11 = ti1[4];
  96016. this.i1e12 = ti1[5];
  96017. this.i1e20 = ti1[6];
  96018. this.i1e21 = ti1[7];
  96019. this.i1e22 = ti1[8];
  96020. this.i2e00 = ti2[0];
  96021. this.i2e01 = ti2[1];
  96022. this.i2e02 = ti2[2];
  96023. this.i2e10 = ti2[3];
  96024. this.i2e11 = ti2[4];
  96025. this.i2e12 = ti2[5];
  96026. this.i2e20 = ti2[6];
  96027. this.i2e21 = ti2[7];
  96028. this.i2e22 = ti2[8];
  96029. var dx = this.p2.x - this.p1.x;
  96030. var dy = this.p2.y - this.p1.y;
  96031. var dz = this.p2.z - this.p1.z;
  96032. var d1 = dx * this.ax1 + dy * this.ay1 + dz * this.az1;
  96033. var d2 = dx * this.ax2 + dy * this.ay2 + dz * this.az2;
  96034. var d3 = dx * this.ax3 + dy * this.ay3 + dz * this.az3;
  96035. var frequency1 = this.limitMotor1.frequency;
  96036. var frequency2 = this.limitMotor2.frequency;
  96037. var frequency3 = this.limitMotor3.frequency;
  96038. var enableSpring1 = frequency1 > 0;
  96039. var enableSpring2 = frequency2 > 0;
  96040. var enableSpring3 = frequency3 > 0;
  96041. var enableLimit1 = this.lowerLimit1 <= this.upperLimit1;
  96042. var enableLimit2 = this.lowerLimit2 <= this.upperLimit2;
  96043. var enableLimit3 = this.lowerLimit3 <= this.upperLimit3;
  96044. // for stability
  96045. if (enableSpring1 && d1 > 20 || d1 < -20) {
  96046. enableSpring1 = false;
  96047. }
  96048. if (enableSpring2 && d2 > 20 || d2 < -20) {
  96049. enableSpring2 = false;
  96050. }
  96051. if (enableSpring3 && d3 > 20 || d3 < -20) {
  96052. enableSpring3 = false;
  96053. }
  96054. if (enableLimit1) {
  96055. if (this.lowerLimit1 == this.upperLimit1) {
  96056. if (this.limitState1 != 0) {
  96057. this.limitState1 = 0;
  96058. this.limitImpulse1 = 0;
  96059. }
  96060. this.limitVelocity1 = this.lowerLimit1 - d1;
  96061. if (!enableSpring1) d1 = this.lowerLimit1;
  96062. } else if (d1 < this.lowerLimit1) {
  96063. if (this.limitState1 != -1) {
  96064. this.limitState1 = -1;
  96065. this.limitImpulse1 = 0;
  96066. }
  96067. this.limitVelocity1 = this.lowerLimit1 - d1;
  96068. if (!enableSpring1) d1 = this.lowerLimit1;
  96069. } else if (d1 > this.upperLimit1) {
  96070. if (this.limitState1 != 1) {
  96071. this.limitState1 = 1;
  96072. this.limitImpulse1 = 0;
  96073. }
  96074. this.limitVelocity1 = this.upperLimit1 - d1;
  96075. if (!enableSpring1) d1 = this.upperLimit1;
  96076. } else {
  96077. this.limitState1 = 2;
  96078. this.limitImpulse1 = 0;
  96079. this.limitVelocity1 = 0;
  96080. }
  96081. if (!enableSpring1) {
  96082. if (this.limitVelocity1 > 0.005) this.limitVelocity1 -= 0.005;
  96083. else if (this.limitVelocity1 < -0.005) this.limitVelocity1 += 0.005;
  96084. else this.limitVelocity1 = 0;
  96085. }
  96086. } else {
  96087. this.limitState1 = 2;
  96088. this.limitImpulse1 = 0;
  96089. }
  96090. if (enableLimit2) {
  96091. if (this.lowerLimit2 == this.upperLimit2) {
  96092. if (this.limitState2 != 0) {
  96093. this.limitState2 = 0;
  96094. this.limitImpulse2 = 0;
  96095. }
  96096. this.limitVelocity2 = this.lowerLimit2 - d2;
  96097. if (!enableSpring2) d2 = this.lowerLimit2;
  96098. } else if (d2 < this.lowerLimit2) {
  96099. if (this.limitState2 != -1) {
  96100. this.limitState2 = -1;
  96101. this.limitImpulse2 = 0;
  96102. }
  96103. this.limitVelocity2 = this.lowerLimit2 - d2;
  96104. if (!enableSpring2) d2 = this.lowerLimit2;
  96105. } else if (d2 > this.upperLimit2) {
  96106. if (this.limitState2 != 1) {
  96107. this.limitState2 = 1;
  96108. this.limitImpulse2 = 0;
  96109. }
  96110. this.limitVelocity2 = this.upperLimit2 - d2;
  96111. if (!enableSpring2) d2 = this.upperLimit2;
  96112. } else {
  96113. this.limitState2 = 2;
  96114. this.limitImpulse2 = 0;
  96115. this.limitVelocity2 = 0;
  96116. }
  96117. if (!enableSpring2) {
  96118. if (this.limitVelocity2 > 0.005) this.limitVelocity2 -= 0.005;
  96119. else if (this.limitVelocity2 < -0.005) this.limitVelocity2 += 0.005;
  96120. else this.limitVelocity2 = 0;
  96121. }
  96122. } else {
  96123. this.limitState2 = 2;
  96124. this.limitImpulse2 = 0;
  96125. }
  96126. if (enableLimit3) {
  96127. if (this.lowerLimit3 == this.upperLimit3) {
  96128. if (this.limitState3 != 0) {
  96129. this.limitState3 = 0;
  96130. this.limitImpulse3 = 0;
  96131. }
  96132. this.limitVelocity3 = this.lowerLimit3 - d3;
  96133. if (!enableSpring3) d3 = this.lowerLimit3;
  96134. } else if (d3 < this.lowerLimit3) {
  96135. if (this.limitState3 != -1) {
  96136. this.limitState3 = -1;
  96137. this.limitImpulse3 = 0;
  96138. }
  96139. this.limitVelocity3 = this.lowerLimit3 - d3;
  96140. if (!enableSpring3) d3 = this.lowerLimit3;
  96141. } else if (d3 > this.upperLimit3) {
  96142. if (this.limitState3 != 1) {
  96143. this.limitState3 = 1;
  96144. this.limitImpulse3 = 0;
  96145. }
  96146. this.limitVelocity3 = this.upperLimit3 - d3;
  96147. if (!enableSpring3) d3 = this.upperLimit3;
  96148. } else {
  96149. this.limitState3 = 2;
  96150. this.limitImpulse3 = 0;
  96151. this.limitVelocity3 = 0;
  96152. }
  96153. if (!enableSpring3) {
  96154. if (this.limitVelocity3 > 0.005) this.limitVelocity3 -= 0.005;
  96155. else if (this.limitVelocity3 < -0.005) this.limitVelocity3 += 0.005;
  96156. else this.limitVelocity3 = 0;
  96157. }
  96158. } else {
  96159. this.limitState3 = 2;
  96160. this.limitImpulse3 = 0;
  96161. }
  96162. if (this.enableMotor1 && (this.limitState1 != 0 || enableSpring1)) {
  96163. this.maxMotorImpulse1 = this.maxMotorForce1 * timeStep;
  96164. } else {
  96165. this.motorImpulse1 = 0;
  96166. this.maxMotorImpulse1 = 0;
  96167. }
  96168. if (this.enableMotor2 && (this.limitState2 != 0 || enableSpring2)) {
  96169. this.maxMotorImpulse2 = this.maxMotorForce2 * timeStep;
  96170. } else {
  96171. this.motorImpulse2 = 0;
  96172. this.maxMotorImpulse2 = 0;
  96173. }
  96174. if (this.enableMotor3 && (this.limitState3 != 0 || enableSpring3)) {
  96175. this.maxMotorImpulse3 = this.maxMotorForce3 * timeStep;
  96176. } else {
  96177. this.motorImpulse3 = 0;
  96178. this.maxMotorImpulse3 = 0;
  96179. }
  96180. var rdx = d1 * this.ax1 + d2 * this.ax2 + d3 * this.ax2;
  96181. var rdy = d1 * this.ay1 + d2 * this.ay2 + d3 * this.ay2;
  96182. var rdz = d1 * this.az1 + d2 * this.az2 + d3 * this.az2;
  96183. var w1 = this.m2 / (this.m1 + this.m2);
  96184. if (this.weight >= 0) w1 = this.weight; // use given weight
  96185. var w2 = 1 - w1;
  96186. this.r1x = this.r1.x + rdx * w1;
  96187. this.r1y = this.r1.y + rdy * w1;
  96188. this.r1z = this.r1.z + rdz * w1;
  96189. this.r2x = this.r2.x - rdx * w2;
  96190. this.r2y = this.r2.y - rdy * w2;
  96191. this.r2z = this.r2.z - rdz * w2;
  96192. // build jacobians
  96193. this.t1x1 = this.r1y * this.az1 - this.r1z * this.ay1;
  96194. this.t1y1 = this.r1z * this.ax1 - this.r1x * this.az1;
  96195. this.t1z1 = this.r1x * this.ay1 - this.r1y * this.ax1;
  96196. this.t2x1 = this.r2y * this.az1 - this.r2z * this.ay1;
  96197. this.t2y1 = this.r2z * this.ax1 - this.r2x * this.az1;
  96198. this.t2z1 = this.r2x * this.ay1 - this.r2y * this.ax1;
  96199. this.l1x1 = this.ax1 * this.m1;
  96200. this.l1y1 = this.ay1 * this.m1;
  96201. this.l1z1 = this.az1 * this.m1;
  96202. this.l2x1 = this.ax1 * this.m2;
  96203. this.l2y1 = this.ay1 * this.m2;
  96204. this.l2z1 = this.az1 * this.m2;
  96205. this.a1x1 = this.t1x1 * this.i1e00 + this.t1y1 * this.i1e01 + this.t1z1 * this.i1e02;
  96206. this.a1y1 = this.t1x1 * this.i1e10 + this.t1y1 * this.i1e11 + this.t1z1 * this.i1e12;
  96207. this.a1z1 = this.t1x1 * this.i1e20 + this.t1y1 * this.i1e21 + this.t1z1 * this.i1e22;
  96208. this.a2x1 = this.t2x1 * this.i2e00 + this.t2y1 * this.i2e01 + this.t2z1 * this.i2e02;
  96209. this.a2y1 = this.t2x1 * this.i2e10 + this.t2y1 * this.i2e11 + this.t2z1 * this.i2e12;
  96210. this.a2z1 = this.t2x1 * this.i2e20 + this.t2y1 * this.i2e21 + this.t2z1 * this.i2e22;
  96211. this.t1x2 = this.r1y * this.az2 - this.r1z * this.ay2;
  96212. this.t1y2 = this.r1z * this.ax2 - this.r1x * this.az2;
  96213. this.t1z2 = this.r1x * this.ay2 - this.r1y * this.ax2;
  96214. this.t2x2 = this.r2y * this.az2 - this.r2z * this.ay2;
  96215. this.t2y2 = this.r2z * this.ax2 - this.r2x * this.az2;
  96216. this.t2z2 = this.r2x * this.ay2 - this.r2y * this.ax2;
  96217. this.l1x2 = this.ax2 * this.m1;
  96218. this.l1y2 = this.ay2 * this.m1;
  96219. this.l1z2 = this.az2 * this.m1;
  96220. this.l2x2 = this.ax2 * this.m2;
  96221. this.l2y2 = this.ay2 * this.m2;
  96222. this.l2z2 = this.az2 * this.m2;
  96223. this.a1x2 = this.t1x2 * this.i1e00 + this.t1y2 * this.i1e01 + this.t1z2 * this.i1e02;
  96224. this.a1y2 = this.t1x2 * this.i1e10 + this.t1y2 * this.i1e11 + this.t1z2 * this.i1e12;
  96225. this.a1z2 = this.t1x2 * this.i1e20 + this.t1y2 * this.i1e21 + this.t1z2 * this.i1e22;
  96226. this.a2x2 = this.t2x2 * this.i2e00 + this.t2y2 * this.i2e01 + this.t2z2 * this.i2e02;
  96227. this.a2y2 = this.t2x2 * this.i2e10 + this.t2y2 * this.i2e11 + this.t2z2 * this.i2e12;
  96228. this.a2z2 = this.t2x2 * this.i2e20 + this.t2y2 * this.i2e21 + this.t2z2 * this.i2e22;
  96229. this.t1x3 = this.r1y * this.az3 - this.r1z * this.ay3;
  96230. this.t1y3 = this.r1z * this.ax3 - this.r1x * this.az3;
  96231. this.t1z3 = this.r1x * this.ay3 - this.r1y * this.ax3;
  96232. this.t2x3 = this.r2y * this.az3 - this.r2z * this.ay3;
  96233. this.t2y3 = this.r2z * this.ax3 - this.r2x * this.az3;
  96234. this.t2z3 = this.r2x * this.ay3 - this.r2y * this.ax3;
  96235. this.l1x3 = this.ax3 * this.m1;
  96236. this.l1y3 = this.ay3 * this.m1;
  96237. this.l1z3 = this.az3 * this.m1;
  96238. this.l2x3 = this.ax3 * this.m2;
  96239. this.l2y3 = this.ay3 * this.m2;
  96240. this.l2z3 = this.az3 * this.m2;
  96241. this.a1x3 = this.t1x3 * this.i1e00 + this.t1y3 * this.i1e01 + this.t1z3 * this.i1e02;
  96242. this.a1y3 = this.t1x3 * this.i1e10 + this.t1y3 * this.i1e11 + this.t1z3 * this.i1e12;
  96243. this.a1z3 = this.t1x3 * this.i1e20 + this.t1y3 * this.i1e21 + this.t1z3 * this.i1e22;
  96244. this.a2x3 = this.t2x3 * this.i2e00 + this.t2y3 * this.i2e01 + this.t2z3 * this.i2e02;
  96245. this.a2y3 = this.t2x3 * this.i2e10 + this.t2y3 * this.i2e11 + this.t2z3 * this.i2e12;
  96246. this.a2z3 = this.t2x3 * this.i2e20 + this.t2y3 * this.i2e21 + this.t2z3 * this.i2e22;
  96247. // build an impulse matrix
  96248. var m12 = this.m1 + this.m2;
  96249. this.k00 = (this.ax1 * this.ax1 + this.ay1 * this.ay1 + this.az1 * this.az1) * m12;
  96250. this.k01 = (this.ax1 * this.ax2 + this.ay1 * this.ay2 + this.az1 * this.az2) * m12;
  96251. this.k02 = (this.ax1 * this.ax3 + this.ay1 * this.ay3 + this.az1 * this.az3) * m12;
  96252. this.k10 = (this.ax2 * this.ax1 + this.ay2 * this.ay1 + this.az2 * this.az1) * m12;
  96253. this.k11 = (this.ax2 * this.ax2 + this.ay2 * this.ay2 + this.az2 * this.az2) * m12;
  96254. this.k12 = (this.ax2 * this.ax3 + this.ay2 * this.ay3 + this.az2 * this.az3) * m12;
  96255. this.k20 = (this.ax3 * this.ax1 + this.ay3 * this.ay1 + this.az3 * this.az1) * m12;
  96256. this.k21 = (this.ax3 * this.ax2 + this.ay3 * this.ay2 + this.az3 * this.az2) * m12;
  96257. this.k22 = (this.ax3 * this.ax3 + this.ay3 * this.ay3 + this.az3 * this.az3) * m12;
  96258. this.k00 += this.t1x1 * this.a1x1 + this.t1y1 * this.a1y1 + this.t1z1 * this.a1z1;
  96259. this.k01 += this.t1x1 * this.a1x2 + this.t1y1 * this.a1y2 + this.t1z1 * this.a1z2;
  96260. this.k02 += this.t1x1 * this.a1x3 + this.t1y1 * this.a1y3 + this.t1z1 * this.a1z3;
  96261. this.k10 += this.t1x2 * this.a1x1 + this.t1y2 * this.a1y1 + this.t1z2 * this.a1z1;
  96262. this.k11 += this.t1x2 * this.a1x2 + this.t1y2 * this.a1y2 + this.t1z2 * this.a1z2;
  96263. this.k12 += this.t1x2 * this.a1x3 + this.t1y2 * this.a1y3 + this.t1z2 * this.a1z3;
  96264. this.k20 += this.t1x3 * this.a1x1 + this.t1y3 * this.a1y1 + this.t1z3 * this.a1z1;
  96265. this.k21 += this.t1x3 * this.a1x2 + this.t1y3 * this.a1y2 + this.t1z3 * this.a1z2;
  96266. this.k22 += this.t1x3 * this.a1x3 + this.t1y3 * this.a1y3 + this.t1z3 * this.a1z3;
  96267. this.k00 += this.t2x1 * this.a2x1 + this.t2y1 * this.a2y1 + this.t2z1 * this.a2z1;
  96268. this.k01 += this.t2x1 * this.a2x2 + this.t2y1 * this.a2y2 + this.t2z1 * this.a2z2;
  96269. this.k02 += this.t2x1 * this.a2x3 + this.t2y1 * this.a2y3 + this.t2z1 * this.a2z3;
  96270. this.k10 += this.t2x2 * this.a2x1 + this.t2y2 * this.a2y1 + this.t2z2 * this.a2z1;
  96271. this.k11 += this.t2x2 * this.a2x2 + this.t2y2 * this.a2y2 + this.t2z2 * this.a2z2;
  96272. this.k12 += this.t2x2 * this.a2x3 + this.t2y2 * this.a2y3 + this.t2z2 * this.a2z3;
  96273. this.k20 += this.t2x3 * this.a2x1 + this.t2y3 * this.a2y1 + this.t2z3 * this.a2z1;
  96274. this.k21 += this.t2x3 * this.a2x2 + this.t2y3 * this.a2y2 + this.t2z3 * this.a2z2;
  96275. this.k22 += this.t2x3 * this.a2x3 + this.t2y3 * this.a2y3 + this.t2z3 * this.a2z3;
  96276. this.kv00 = this.k00;
  96277. this.kv11 = this.k11;
  96278. this.kv22 = this.k22;
  96279. this.dv00 = 1 / this.kv00;
  96280. this.dv11 = 1 / this.kv11;
  96281. this.dv22 = 1 / this.kv22;
  96282. if (enableSpring1 && this.limitState1 != 2) {
  96283. var omega = 6.2831853 * frequency1;
  96284. var k = omega * omega * timeStep;
  96285. var dmp = invTimeStep / (k + 2 * this.limitMotor1.dampingRatio * omega);
  96286. this.cfm1 = this.kv00 * dmp;
  96287. this.limitVelocity1 *= k * dmp;
  96288. } else {
  96289. this.cfm1 = 0;
  96290. this.limitVelocity1 *= invTimeStep * 0.05;
  96291. }
  96292. if (enableSpring2 && this.limitState2 != 2) {
  96293. omega = 6.2831853 * frequency2;
  96294. k = omega * omega * timeStep;
  96295. dmp = invTimeStep / (k + 2 * this.limitMotor2.dampingRatio * omega);
  96296. this.cfm2 = this.kv11 * dmp;
  96297. this.limitVelocity2 *= k * dmp;
  96298. } else {
  96299. this.cfm2 = 0;
  96300. this.limitVelocity2 *= invTimeStep * 0.05;
  96301. }
  96302. if (enableSpring3 && this.limitState3 != 2) {
  96303. omega = 6.2831853 * frequency3;
  96304. k = omega * omega * timeStep;
  96305. dmp = invTimeStep / (k + 2 * this.limitMotor3.dampingRatio * omega);
  96306. this.cfm3 = this.kv22 * dmp;
  96307. this.limitVelocity3 *= k * dmp;
  96308. } else {
  96309. this.cfm3 = 0;
  96310. this.limitVelocity3 *= invTimeStep * 0.05;
  96311. }
  96312. this.k00 += this.cfm1;
  96313. this.k11 += this.cfm2;
  96314. this.k22 += this.cfm3;
  96315. var inv = 1 / (
  96316. this.k00 * (this.k11 * this.k22 - this.k21 * this.k12) +
  96317. this.k10 * (this.k21 * this.k02 - this.k01 * this.k22) +
  96318. this.k20 * (this.k01 * this.k12 - this.k11 * this.k02)
  96319. );
  96320. this.d00 = (this.k11 * this.k22 - this.k12 * this.k21) * inv;
  96321. this.d01 = (this.k02 * this.k21 - this.k01 * this.k22) * inv;
  96322. this.d02 = (this.k01 * this.k12 - this.k02 * this.k11) * inv;
  96323. this.d10 = (this.k12 * this.k20 - this.k10 * this.k22) * inv;
  96324. this.d11 = (this.k00 * this.k22 - this.k02 * this.k20) * inv;
  96325. this.d12 = (this.k02 * this.k10 - this.k00 * this.k12) * inv;
  96326. this.d20 = (this.k10 * this.k21 - this.k11 * this.k20) * inv;
  96327. this.d21 = (this.k01 * this.k20 - this.k00 * this.k21) * inv;
  96328. this.d22 = (this.k00 * this.k11 - this.k01 * this.k10) * inv;
  96329. // warm starting
  96330. var totalImpulse1 = this.limitImpulse1 + this.motorImpulse1;
  96331. var totalImpulse2 = this.limitImpulse2 + this.motorImpulse2;
  96332. var totalImpulse3 = this.limitImpulse3 + this.motorImpulse3;
  96333. this.l1.x += totalImpulse1 * this.l1x1 + totalImpulse2 * this.l1x2 + totalImpulse3 * this.l1x3;
  96334. this.l1.y += totalImpulse1 * this.l1y1 + totalImpulse2 * this.l1y2 + totalImpulse3 * this.l1y3;
  96335. this.l1.z += totalImpulse1 * this.l1z1 + totalImpulse2 * this.l1z2 + totalImpulse3 * this.l1z3;
  96336. this.a1.x += totalImpulse1 * this.a1x1 + totalImpulse2 * this.a1x2 + totalImpulse3 * this.a1x3;
  96337. this.a1.y += totalImpulse1 * this.a1y1 + totalImpulse2 * this.a1y2 + totalImpulse3 * this.a1y3;
  96338. this.a1.z += totalImpulse1 * this.a1z1 + totalImpulse2 * this.a1z2 + totalImpulse3 * this.a1z3;
  96339. this.l2.x -= totalImpulse1 * this.l2x1 + totalImpulse2 * this.l2x2 + totalImpulse3 * this.l2x3;
  96340. this.l2.y -= totalImpulse1 * this.l2y1 + totalImpulse2 * this.l2y2 + totalImpulse3 * this.l2y3;
  96341. this.l2.z -= totalImpulse1 * this.l2z1 + totalImpulse2 * this.l2z2 + totalImpulse3 * this.l2z3;
  96342. this.a2.x -= totalImpulse1 * this.a2x1 + totalImpulse2 * this.a2x2 + totalImpulse3 * this.a2x3;
  96343. this.a2.y -= totalImpulse1 * this.a2y1 + totalImpulse2 * this.a2y2 + totalImpulse3 * this.a2y3;
  96344. this.a2.z -= totalImpulse1 * this.a2z1 + totalImpulse2 * this.a2z2 + totalImpulse3 * this.a2z3;
  96345. },
  96346. solve: function () {
  96347. 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;
  96348. 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;
  96349. 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;
  96350. var rvn1 = rvx * this.ax1 + rvy * this.ay1 + rvz * this.az1;
  96351. var rvn2 = rvx * this.ax2 + rvy * this.ay2 + rvz * this.az2;
  96352. var rvn3 = rvx * this.ax3 + rvy * this.ay3 + rvz * this.az3;
  96353. var oldMotorImpulse1 = this.motorImpulse1;
  96354. var oldMotorImpulse2 = this.motorImpulse2;
  96355. var oldMotorImpulse3 = this.motorImpulse3;
  96356. var dMotorImpulse1 = 0;
  96357. var dMotorImpulse2 = 0;
  96358. var dMotorImpulse3 = 0;
  96359. if (this.enableMotor1) {
  96360. dMotorImpulse1 = (rvn1 - this.motorSpeed1) * this.dv00;
  96361. this.motorImpulse1 += dMotorImpulse1;
  96362. if (this.motorImpulse1 > this.maxMotorImpulse1) { // clamp motor impulse
  96363. this.motorImpulse1 = this.maxMotorImpulse1;
  96364. } else if (this.motorImpulse1 < -this.maxMotorImpulse1) {
  96365. this.motorImpulse1 = -this.maxMotorImpulse1;
  96366. }
  96367. dMotorImpulse1 = this.motorImpulse1 - oldMotorImpulse1;
  96368. }
  96369. if (this.enableMotor2) {
  96370. dMotorImpulse2 = (rvn2 - this.motorSpeed2) * this.dv11;
  96371. this.motorImpulse2 += dMotorImpulse2;
  96372. if (this.motorImpulse2 > this.maxMotorImpulse2) { // clamp motor impulse
  96373. this.motorImpulse2 = this.maxMotorImpulse2;
  96374. } else if (this.motorImpulse2 < -this.maxMotorImpulse2) {
  96375. this.motorImpulse2 = -this.maxMotorImpulse2;
  96376. }
  96377. dMotorImpulse2 = this.motorImpulse2 - oldMotorImpulse2;
  96378. }
  96379. if (this.enableMotor3) {
  96380. dMotorImpulse3 = (rvn3 - this.motorSpeed3) * this.dv22;
  96381. this.motorImpulse3 += dMotorImpulse3;
  96382. if (this.motorImpulse3 > this.maxMotorImpulse3) { // clamp motor impulse
  96383. this.motorImpulse3 = this.maxMotorImpulse3;
  96384. } else if (this.motorImpulse3 < -this.maxMotorImpulse3) {
  96385. this.motorImpulse3 = -this.maxMotorImpulse3;
  96386. }
  96387. dMotorImpulse3 = this.motorImpulse3 - oldMotorImpulse3;
  96388. }
  96389. // apply motor impulse to relative velocity
  96390. rvn1 += dMotorImpulse1 * this.kv00 + dMotorImpulse2 * this.k01 + dMotorImpulse3 * this.k02;
  96391. rvn2 += dMotorImpulse1 * this.k10 + dMotorImpulse2 * this.kv11 + dMotorImpulse3 * this.k12;
  96392. rvn3 += dMotorImpulse1 * this.k20 + dMotorImpulse2 * this.k21 + dMotorImpulse3 * this.kv22;
  96393. // subtract target velocity and applied impulse
  96394. rvn1 -= this.limitVelocity1 + this.limitImpulse1 * this.cfm1;
  96395. rvn2 -= this.limitVelocity2 + this.limitImpulse2 * this.cfm2;
  96396. rvn3 -= this.limitVelocity3 + this.limitImpulse3 * this.cfm3;
  96397. var oldLimitImpulse1 = this.limitImpulse1;
  96398. var oldLimitImpulse2 = this.limitImpulse2;
  96399. var oldLimitImpulse3 = this.limitImpulse3;
  96400. var dLimitImpulse1 = rvn1 * this.d00 + rvn2 * this.d01 + rvn3 * this.d02;
  96401. var dLimitImpulse2 = rvn1 * this.d10 + rvn2 * this.d11 + rvn3 * this.d12;
  96402. var dLimitImpulse3 = rvn1 * this.d20 + rvn2 * this.d21 + rvn3 * this.d22;
  96403. this.limitImpulse1 += dLimitImpulse1;
  96404. this.limitImpulse2 += dLimitImpulse2;
  96405. this.limitImpulse3 += dLimitImpulse3;
  96406. // clamp
  96407. var clampState = 0;
  96408. if (this.limitState1 == 2 || this.limitImpulse1 * this.limitState1 < 0) {
  96409. dLimitImpulse1 = -oldLimitImpulse1;
  96410. rvn2 += dLimitImpulse1 * this.k10;
  96411. rvn3 += dLimitImpulse1 * this.k20;
  96412. clampState |= 1;
  96413. }
  96414. if (this.limitState2 == 2 || this.limitImpulse2 * this.limitState2 < 0) {
  96415. dLimitImpulse2 = -oldLimitImpulse2;
  96416. rvn1 += dLimitImpulse2 * this.k01;
  96417. rvn3 += dLimitImpulse2 * this.k21;
  96418. clampState |= 2;
  96419. }
  96420. if (this.limitState3 == 2 || this.limitImpulse3 * this.limitState3 < 0) {
  96421. dLimitImpulse3 = -oldLimitImpulse3;
  96422. rvn1 += dLimitImpulse3 * this.k02;
  96423. rvn2 += dLimitImpulse3 * this.k12;
  96424. clampState |= 4;
  96425. }
  96426. // update un-clamped impulse
  96427. // TODO: isolate division
  96428. var det;
  96429. switch (clampState) {
  96430. case 1:// update 2 3
  96431. det = 1 / (this.k11 * this.k22 - this.k12 * this.k21);
  96432. dLimitImpulse2 = (this.k22 * rvn2 + -this.k12 * rvn3) * det;
  96433. dLimitImpulse3 = (-this.k21 * rvn2 + this.k11 * rvn3) * det;
  96434. break;
  96435. case 2:// update 1 3
  96436. det = 1 / (this.k00 * this.k22 - this.k02 * this.k20);
  96437. dLimitImpulse1 = (this.k22 * rvn1 + -this.k02 * rvn3) * det;
  96438. dLimitImpulse3 = (-this.k20 * rvn1 + this.k00 * rvn3) * det;
  96439. break;
  96440. case 3:// update 3
  96441. dLimitImpulse3 = rvn3 / this.k22;
  96442. break;
  96443. case 4:// update 1 2
  96444. det = 1 / (this.k00 * this.k11 - this.k01 * this.k10);
  96445. dLimitImpulse1 = (this.k11 * rvn1 + -this.k01 * rvn2) * det;
  96446. dLimitImpulse2 = (-this.k10 * rvn1 + this.k00 * rvn2) * det;
  96447. break;
  96448. case 5:// update 2
  96449. dLimitImpulse2 = rvn2 / this.k11;
  96450. break;
  96451. case 6:// update 1
  96452. dLimitImpulse1 = rvn1 / this.k00;
  96453. break;
  96454. }
  96455. this.limitImpulse1 = oldLimitImpulse1 + dLimitImpulse1;
  96456. this.limitImpulse2 = oldLimitImpulse2 + dLimitImpulse2;
  96457. this.limitImpulse3 = oldLimitImpulse3 + dLimitImpulse3;
  96458. var dImpulse1 = dMotorImpulse1 + dLimitImpulse1;
  96459. var dImpulse2 = dMotorImpulse2 + dLimitImpulse2;
  96460. var dImpulse3 = dMotorImpulse3 + dLimitImpulse3;
  96461. // apply impulse
  96462. this.l1.x += dImpulse1 * this.l1x1 + dImpulse2 * this.l1x2 + dImpulse3 * this.l1x3;
  96463. this.l1.y += dImpulse1 * this.l1y1 + dImpulse2 * this.l1y2 + dImpulse3 * this.l1y3;
  96464. this.l1.z += dImpulse1 * this.l1z1 + dImpulse2 * this.l1z2 + dImpulse3 * this.l1z3;
  96465. this.a1.x += dImpulse1 * this.a1x1 + dImpulse2 * this.a1x2 + dImpulse3 * this.a1x3;
  96466. this.a1.y += dImpulse1 * this.a1y1 + dImpulse2 * this.a1y2 + dImpulse3 * this.a1y3;
  96467. this.a1.z += dImpulse1 * this.a1z1 + dImpulse2 * this.a1z2 + dImpulse3 * this.a1z3;
  96468. this.l2.x -= dImpulse1 * this.l2x1 + dImpulse2 * this.l2x2 + dImpulse3 * this.l2x3;
  96469. this.l2.y -= dImpulse1 * this.l2y1 + dImpulse2 * this.l2y2 + dImpulse3 * this.l2y3;
  96470. this.l2.z -= dImpulse1 * this.l2z1 + dImpulse2 * this.l2z2 + dImpulse3 * this.l2z3;
  96471. this.a2.x -= dImpulse1 * this.a2x1 + dImpulse2 * this.a2x2 + dImpulse3 * this.a2x3;
  96472. this.a2.y -= dImpulse1 * this.a2y1 + dImpulse2 * this.a2y2 + dImpulse3 * this.a2y3;
  96473. this.a2.z -= dImpulse1 * this.a2z1 + dImpulse2 * this.a2z2 + dImpulse3 * this.a2z3;
  96474. }
  96475. }
  96476. /**
  96477. * A translational constraint for various joints.
  96478. * @author saharan
  96479. */
  96480. OIMO.TranslationalConstraint = function (joint, limitMotor) {
  96481. this.cfm = NaN;
  96482. this.m1 = NaN;
  96483. this.m2 = NaN;
  96484. this.i1e00 = NaN;
  96485. this.i1e01 = NaN;
  96486. this.i1e02 = NaN;
  96487. this.i1e10 = NaN;
  96488. this.i1e11 = NaN;
  96489. this.i1e12 = NaN;
  96490. this.i1e20 = NaN;
  96491. this.i1e21 = NaN;
  96492. this.i1e22 = NaN;
  96493. this.i2e00 = NaN;
  96494. this.i2e01 = NaN;
  96495. this.i2e02 = NaN;
  96496. this.i2e10 = NaN;
  96497. this.i2e11 = NaN;
  96498. this.i2e12 = NaN;
  96499. this.i2e20 = NaN;
  96500. this.i2e21 = NaN;
  96501. this.i2e22 = NaN;
  96502. this.motorDenom = NaN;
  96503. this.invMotorDenom = NaN;
  96504. this.invDenom = NaN;
  96505. this.ax = NaN;
  96506. this.ay = NaN;
  96507. this.az = NaN;
  96508. this.r1x = NaN;
  96509. this.r1y = NaN;
  96510. this.r1z = NaN;
  96511. this.r2x = NaN;
  96512. this.r2y = NaN;
  96513. this.r2z = NaN;
  96514. this.t1x = NaN;
  96515. this.t1y = NaN;
  96516. this.t1z = NaN;
  96517. this.t2x = NaN;
  96518. this.t2y = NaN;
  96519. this.t2z = NaN;
  96520. this.l1x = NaN;
  96521. this.l1y = NaN;
  96522. this.l1z = NaN;
  96523. this.l2x = NaN;
  96524. this.l2y = NaN;
  96525. this.l2z = NaN;
  96526. this.a1x = NaN;
  96527. this.a1y = NaN;
  96528. this.a1z = NaN;
  96529. this.a2x = NaN;
  96530. this.a2y = NaN;
  96531. this.a2z = NaN;
  96532. this.lowerLimit = NaN;
  96533. this.upperLimit = NaN;
  96534. this.limitVelocity = NaN;
  96535. this.limitState = 0; // -1: at lower, 0: locked, 1: at upper, 2: free
  96536. this.enableMotor = false;
  96537. this.motorSpeed = NaN;
  96538. this.maxMotorForce = NaN;
  96539. this.maxMotorImpulse = NaN;
  96540. this.limitMotor = limitMotor;
  96541. this.b1 = joint.body1;
  96542. this.b2 = joint.body2;
  96543. this.p1 = joint.anchorPoint1;
  96544. this.p2 = joint.anchorPoint2;
  96545. this.r1 = joint.relativeAnchorPoint1;
  96546. this.r2 = joint.relativeAnchorPoint2;
  96547. this.l1 = this.b1.linearVelocity;
  96548. this.l2 = this.b2.linearVelocity;
  96549. this.a1 = this.b1.angularVelocity;
  96550. this.a2 = this.b2.angularVelocity;
  96551. this.i1 = this.b1.inverseInertia;
  96552. this.i2 = this.b2.inverseInertia;
  96553. this.limitImpulse = 0;
  96554. this.motorImpulse = 0;
  96555. }
  96556. OIMO.TranslationalConstraint.prototype = {
  96557. constructor: OIMO.TranslationalConstraint,
  96558. preSolve: function (timeStep, invTimeStep) {
  96559. this.ax = this.limitMotor.axis.x;
  96560. this.ay = this.limitMotor.axis.y;
  96561. this.az = this.limitMotor.axis.z;
  96562. this.lowerLimit = this.limitMotor.lowerLimit;
  96563. this.upperLimit = this.limitMotor.upperLimit;
  96564. this.motorSpeed = this.limitMotor.motorSpeed;
  96565. this.maxMotorForce = this.limitMotor.maxMotorForce;
  96566. this.enableMotor = this.maxMotorForce > 0;
  96567. this.m1 = this.b1.inverseMass;
  96568. this.m2 = this.b2.inverseMass;
  96569. var ti1 = this.i1.elements;
  96570. var ti2 = this.i2.elements;
  96571. this.i1e00 = ti1[0];
  96572. this.i1e01 = ti1[1];
  96573. this.i1e02 = ti1[2];
  96574. this.i1e10 = ti1[3];
  96575. this.i1e11 = ti1[4];
  96576. this.i1e12 = ti1[5];
  96577. this.i1e20 = ti1[6];
  96578. this.i1e21 = ti1[7];
  96579. this.i1e22 = ti1[8];
  96580. this.i2e00 = ti2[0];
  96581. this.i2e01 = ti2[1];
  96582. this.i2e02 = ti2[2];
  96583. this.i2e10 = ti2[3];
  96584. this.i2e11 = ti2[4];
  96585. this.i2e12 = ti2[5];
  96586. this.i2e20 = ti2[6];
  96587. this.i2e21 = ti2[7];
  96588. this.i2e22 = ti2[8];
  96589. var dx = this.p2.x - this.p1.x;
  96590. var dy = this.p2.y - this.p1.y;
  96591. var dz = this.p2.z - this.p1.z;
  96592. var d = dx * this.ax + dy * this.ay + dz * this.az;
  96593. var frequency = this.limitMotor.frequency;
  96594. var enableSpring = frequency > 0;
  96595. var enableLimit = this.lowerLimit <= this.upperLimit;
  96596. if (enableSpring && d > 20 || d < -20) {
  96597. enableSpring = false;
  96598. }
  96599. if (enableLimit) {
  96600. if (this.lowerLimit == this.upperLimit) {
  96601. if (this.limitState != 0) {
  96602. this.limitState = 0;
  96603. this.limitImpulse = 0;
  96604. }
  96605. this.limitVelocity = this.lowerLimit - d;
  96606. if (!enableSpring) d = this.lowerLimit;
  96607. } else if (d < this.lowerLimit) {
  96608. if (this.limitState != -1) {
  96609. this.limitState = -1;
  96610. this.limitImpulse = 0;
  96611. }
  96612. this.limitVelocity = this.lowerLimit - d;
  96613. if (!enableSpring) d = this.lowerLimit;
  96614. } else if (d > this.upperLimit) {
  96615. if (this.limitState != 1) {
  96616. this.limitState = 1;
  96617. this.limitImpulse = 0;
  96618. }
  96619. this.limitVelocity = this.upperLimit - d;
  96620. if (!enableSpring) d = this.upperLimit;
  96621. } else {
  96622. this.limitState = 2;
  96623. this.limitImpulse = 0;
  96624. this.limitVelocity = 0;
  96625. }
  96626. if (!enableSpring) {
  96627. if (this.limitVelocity > 0.005) this.limitVelocity -= 0.005;
  96628. else if (this.limitVelocity < -0.005) this.limitVelocity += 0.005;
  96629. else this.limitVelocity = 0;
  96630. }
  96631. } else {
  96632. this.limitState = 2;
  96633. this.limitImpulse = 0;
  96634. }
  96635. if (this.enableMotor && (this.limitState != 0 || enableSpring)) {
  96636. this.maxMotorImpulse = this.maxMotorForce * timeStep;
  96637. } else {
  96638. this.motorImpulse = 0;
  96639. this.maxMotorImpulse = 0;
  96640. }
  96641. var rdx = d * this.ax;
  96642. var rdy = d * this.ay;
  96643. var rdz = d * this.az;
  96644. var w1 = this.m1 / (this.m1 + this.m2);
  96645. var w2 = 1 - w1;
  96646. this.r1x = this.r1.x + rdx * w1;
  96647. this.r1y = this.r1.y + rdy * w1;
  96648. this.r1z = this.r1.z + rdz * w1;
  96649. this.r2x = this.r2.x - rdx * w2;
  96650. this.r2y = this.r2.y - rdy * w2;
  96651. this.r2z = this.r2.z - rdz * w2;
  96652. this.t1x = this.r1y * this.az - this.r1z * this.ay;
  96653. this.t1y = this.r1z * this.ax - this.r1x * this.az;
  96654. this.t1z = this.r1x * this.ay - this.r1y * this.ax;
  96655. this.t2x = this.r2y * this.az - this.r2z * this.ay;
  96656. this.t2y = this.r2z * this.ax - this.r2x * this.az;
  96657. this.t2z = this.r2x * this.ay - this.r2y * this.ax;
  96658. this.l1x = this.ax * this.m1;
  96659. this.l1y = this.ay * this.m1;
  96660. this.l1z = this.az * this.m1;
  96661. this.l2x = this.ax * this.m2;
  96662. this.l2y = this.ay * this.m2;
  96663. this.l2z = this.az * this.m2;
  96664. this.a1x = this.t1x * this.i1e00 + this.t1y * this.i1e01 + this.t1z * this.i1e02;
  96665. this.a1y = this.t1x * this.i1e10 + this.t1y * this.i1e11 + this.t1z * this.i1e12;
  96666. this.a1z = this.t1x * this.i1e20 + this.t1y * this.i1e21 + this.t1z * this.i1e22;
  96667. this.a2x = this.t2x * this.i2e00 + this.t2y * this.i2e01 + this.t2z * this.i2e02;
  96668. this.a2y = this.t2x * this.i2e10 + this.t2y * this.i2e11 + this.t2z * this.i2e12;
  96669. this.a2z = this.t2x * this.i2e20 + this.t2y * this.i2e21 + this.t2z * this.i2e22;
  96670. this.motorDenom =
  96671. this.m1 + this.m2 +
  96672. this.ax * (this.a1y * this.r1z - this.a1z * this.r1y + this.a2y * this.r2z - this.a2z * this.r2y) +
  96673. this.ay * (this.a1z * this.r1x - this.a1x * this.r1z + this.a2z * this.r2x - this.a2x * this.r2z) +
  96674. this.az * (this.a1x * this.r1y - this.a1y * this.r1x + this.a2x * this.r2y - this.a2y * this.r2x);
  96675. this.invMotorDenom = 1 / this.motorDenom;
  96676. if (enableSpring && this.limitState != 2) {
  96677. var omega = 6.2831853 * frequency;
  96678. var k = omega * omega * timeStep;
  96679. var dmp = invTimeStep / (k + 2 * this.limitMotor.dampingRatio * omega);
  96680. this.cfm = this.motorDenom * dmp;
  96681. this.limitVelocity *= k * dmp;
  96682. } else {
  96683. this.cfm = 0;
  96684. this.limitVelocity *= invTimeStep * 0.05;
  96685. }
  96686. this.invDenom = 1 / (this.motorDenom + this.cfm);
  96687. var totalImpulse = this.limitImpulse + this.motorImpulse;
  96688. this.l1.x += totalImpulse * this.l1x;
  96689. this.l1.y += totalImpulse * this.l1y;
  96690. this.l1.z += totalImpulse * this.l1z;
  96691. this.a1.x += totalImpulse * this.a1x;
  96692. this.a1.y += totalImpulse * this.a1y;
  96693. this.a1.z += totalImpulse * this.a1z;
  96694. this.l2.x -= totalImpulse * this.l2x;
  96695. this.l2.y -= totalImpulse * this.l2y;
  96696. this.l2.z -= totalImpulse * this.l2z;
  96697. this.a2.x -= totalImpulse * this.a2x;
  96698. this.a2.y -= totalImpulse * this.a2y;
  96699. this.a2.z -= totalImpulse * this.a2z;
  96700. },
  96701. solve: function () {
  96702. var rvn =
  96703. this.ax * (this.l2.x - this.l1.x) + this.ay * (this.l2.y - this.l1.y) + this.az * (this.l2.z - this.l1.z) +
  96704. 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;
  96705. // motor part
  96706. var newMotorImpulse;
  96707. if (this.enableMotor) {
  96708. newMotorImpulse = (rvn - this.motorSpeed) * this.invMotorDenom;
  96709. var oldMotorImpulse = this.motorImpulse;
  96710. this.motorImpulse += newMotorImpulse;
  96711. if (this.motorImpulse > this.maxMotorImpulse) this.motorImpulse = this.maxMotorImpulse;
  96712. else if (this.motorImpulse < -this.maxMotorImpulse) this.motorImpulse = -this.maxMotorImpulse;
  96713. newMotorImpulse = this.motorImpulse - oldMotorImpulse;
  96714. rvn -= newMotorImpulse * this.motorDenom;
  96715. } else newMotorImpulse = 0;
  96716. // limit part
  96717. var newLimitImpulse;
  96718. if (this.limitState != 2) {
  96719. newLimitImpulse = (rvn - this.limitVelocity - this.limitImpulse * this.cfm) * this.invDenom;
  96720. var oldLimitImpulse = this.limitImpulse;
  96721. this.limitImpulse += newLimitImpulse;
  96722. if (this.limitImpulse * this.limitState < 0) this.limitImpulse = 0;
  96723. newLimitImpulse = this.limitImpulse - oldLimitImpulse;
  96724. } else newLimitImpulse = 0;
  96725. var totalImpulse = newLimitImpulse + newMotorImpulse;
  96726. this.l1.x += totalImpulse * this.l1x;
  96727. this.l1.y += totalImpulse * this.l1y;
  96728. this.l1.z += totalImpulse * this.l1z;
  96729. this.a1.x += totalImpulse * this.a1x;
  96730. this.a1.y += totalImpulse * this.a1y;
  96731. this.a1.z += totalImpulse * this.a1z;
  96732. this.l2.x -= totalImpulse * this.l2x;
  96733. this.l2.y -= totalImpulse * this.l2y;
  96734. this.l2.z -= totalImpulse * this.l2z;
  96735. this.a2.x -= totalImpulse * this.a2x;
  96736. this.a2.y -= totalImpulse * this.a2y;
  96737. this.a2.z -= totalImpulse * this.a2z;
  96738. }
  96739. }
  96740. /**
  96741. * A contact is a pair of shapes whose axis-aligned bounding boxes are overlapping.
  96742. * @author saharan
  96743. */
  96744. OIMO.Contact = function () {
  96745. // The first shape.
  96746. this.shape1 = null;
  96747. // The second shape.
  96748. this.shape2 = null;
  96749. // The first rigid body.
  96750. this.body1 = null;
  96751. // The second rigid body.
  96752. this.body2 = null;
  96753. // The previous contact in the world.
  96754. this.prev = null;
  96755. // The next contact in the world.
  96756. this.next = null;
  96757. // Internal
  96758. this.persisting = false;
  96759. // Whether both the rigid bodies are sleeping or not.
  96760. this.sleeping = false;
  96761. // The collision detector between two shapes.
  96762. this.detector = null;
  96763. // The contact constraint of the contact.
  96764. this.constraint = null;
  96765. // Whether the shapes are touching or not.
  96766. this.touching = false;
  96767. this.b1Link = new OIMO.ContactLink(this);
  96768. this.b2Link = new OIMO.ContactLink(this);
  96769. this.s1Link = new OIMO.ContactLink(this);
  96770. this.s2Link = new OIMO.ContactLink(this);
  96771. // The contact manifold of the contact.
  96772. this.manifold = new OIMO.ContactManifold();
  96773. this.buffer = [];// vector 4
  96774. this.buffer.length = 4;
  96775. this.buffer[0] = new OIMO.ImpulseDataBuffer();
  96776. this.buffer[1] = new OIMO.ImpulseDataBuffer();
  96777. this.buffer[2] = new OIMO.ImpulseDataBuffer();
  96778. this.buffer[3] = new OIMO.ImpulseDataBuffer();
  96779. this.points = this.manifold.points;
  96780. this.constraint = new OIMO.ContactConstraint(this.manifold);
  96781. }
  96782. OIMO.Contact.prototype = {
  96783. constructor: OIMO.Contact,
  96784. mixRestitution: function (restitution1, restitution2) {
  96785. return OIMO.sqrt(restitution1 * restitution2);
  96786. },
  96787. mixFriction: function (friction1, friction2) {
  96788. return OIMO.sqrt(friction1 * friction2);
  96789. },
  96790. /**
  96791. * Update the contact manifold.
  96792. */
  96793. updateManifold: function () {
  96794. this.constraint.restitution = this.mixRestitution(this.shape1.restitution, this.shape2.restitution);
  96795. this.constraint.friction = this.mixFriction(this.shape1.friction, this.shape2.friction);
  96796. var numBuffers = this.manifold.numPoints;
  96797. var i = numBuffers;
  96798. while (i--) {
  96799. //for(var i=0;i<numBuffers;i++){
  96800. var b = this.buffer[i];
  96801. var p = this.points[i];
  96802. b.lp1X = p.localPoint1.x;
  96803. b.lp1Y = p.localPoint1.y;
  96804. b.lp1Z = p.localPoint1.z;
  96805. b.lp2X = p.localPoint2.x;
  96806. b.lp2Y = p.localPoint2.y;
  96807. b.lp2Z = p.localPoint2.z;
  96808. b.impulse = p.normalImpulse;
  96809. }
  96810. this.manifold.numPoints = 0;
  96811. this.detector.detectCollision(this.shape1, this.shape2, this.manifold);
  96812. var num = this.manifold.numPoints;
  96813. if (num == 0) {
  96814. this.touching = false;
  96815. return;
  96816. }
  96817. this.touching = true;
  96818. i = num;
  96819. while (i--) {
  96820. //for(i=0; i<num; i++){
  96821. p = this.points[i];
  96822. var lp1x = p.localPoint1.x;
  96823. var lp1y = p.localPoint1.y;
  96824. var lp1z = p.localPoint1.z;
  96825. var lp2x = p.localPoint2.x;
  96826. var lp2y = p.localPoint2.y;
  96827. var lp2z = p.localPoint2.z;
  96828. var index = -1;
  96829. var minDistance = 0.0004;
  96830. var j = numBuffers;
  96831. while (j--) {
  96832. //for(var j=0;j<numBuffers;j++){
  96833. b = this.buffer[j];
  96834. var dx = b.lp1X - lp1x;
  96835. var dy = b.lp1Y - lp1y;
  96836. var dz = b.lp1Z - lp1z;
  96837. var distance1 = dx * dx + dy * dy + dz * dz;
  96838. dx = b.lp2X - lp2x;
  96839. dy = b.lp2Y - lp2y;
  96840. dz = b.lp2Z - lp2z;
  96841. var distance2 = dx * dx + dy * dy + dz * dz;
  96842. if (distance1 < distance2) {
  96843. if (distance1 < minDistance) {
  96844. minDistance = distance1;
  96845. index = j;
  96846. }
  96847. } else {
  96848. if (distance2 < minDistance) {
  96849. minDistance = distance2;
  96850. index = j;
  96851. }
  96852. }
  96853. }
  96854. if (index != -1) {
  96855. var tmp = this.buffer[index];
  96856. this.buffer[index] = this.buffer[--numBuffers];
  96857. this.buffer[numBuffers] = tmp;
  96858. p.normalImpulse = tmp.impulse;
  96859. p.warmStarted = true;
  96860. } else {
  96861. p.normalImpulse = 0;
  96862. p.warmStarted = false;
  96863. }
  96864. }
  96865. },
  96866. /**
  96867. * Attach the contact to the shapes.
  96868. * @param shape1
  96869. * @param shape2
  96870. */
  96871. attach: function (shape1, shape2) {
  96872. this.shape1 = shape1;
  96873. this.shape2 = shape2;
  96874. this.body1 = shape1.parent;
  96875. this.body2 = shape2.parent;
  96876. this.manifold.body1 = this.body1;
  96877. this.manifold.body2 = this.body2;
  96878. this.constraint.body1 = this.body1;
  96879. this.constraint.body2 = this.body2;
  96880. this.constraint.attach();
  96881. this.s1Link.shape = shape2;
  96882. this.s1Link.body = this.body2;
  96883. this.s2Link.shape = shape1;
  96884. this.s2Link.body = this.body1;
  96885. if (shape1.contactLink != null) (this.s1Link.next = shape1.contactLink).prev = this.s1Link;
  96886. else this.s1Link.next = null;
  96887. shape1.contactLink = this.s1Link;
  96888. shape1.numContacts++;
  96889. if (shape2.contactLink != null) (this.s2Link.next = shape2.contactLink).prev = this.s2Link;
  96890. else this.s2Link.next = null;
  96891. shape2.contactLink = this.s2Link;
  96892. shape2.numContacts++;
  96893. this.b1Link.shape = shape2;
  96894. this.b1Link.body = this.body2;
  96895. this.b2Link.shape = shape1;
  96896. this.b2Link.body = this.body1;
  96897. if (this.body1.contactLink != null) (this.b1Link.next = this.body1.contactLink).prev = this.b1Link;
  96898. else this.b1Link.next = null;
  96899. this.body1.contactLink = this.b1Link;
  96900. this.body1.numContacts++;
  96901. if (this.body2.contactLink != null) (this.b2Link.next = this.body2.contactLink).prev = this.b2Link;
  96902. else this.b2Link.next = null;
  96903. this.body2.contactLink = this.b2Link;
  96904. this.body2.numContacts++;
  96905. this.prev = null;
  96906. this.next = null;
  96907. this.persisting = true;
  96908. this.sleeping = this.body1.sleeping && this.body2.sleeping;
  96909. this.manifold.numPoints = 0;
  96910. },
  96911. /**
  96912. * Detach the contact from the shapes.
  96913. */
  96914. detach: function () {
  96915. var prev = this.s1Link.prev;
  96916. var next = this.s1Link.next;
  96917. if (prev !== null) prev.next = next;
  96918. if (next !== null) next.prev = prev;
  96919. if (this.shape1.contactLink == this.s1Link) this.shape1.contactLink = next;
  96920. this.s1Link.prev = null;
  96921. this.s1Link.next = null;
  96922. this.s1Link.shape = null;
  96923. this.s1Link.body = null;
  96924. this.shape1.numContacts--;
  96925. prev = this.s2Link.prev;
  96926. next = this.s2Link.next;
  96927. if (prev !== null) prev.next = next;
  96928. if (next !== null) next.prev = prev;
  96929. if (this.shape2.contactLink == this.s2Link) this.shape2.contactLink = next;
  96930. this.s2Link.prev = null;
  96931. this.s2Link.next = null;
  96932. this.s2Link.shape = null;
  96933. this.s2Link.body = null;
  96934. this.shape2.numContacts--;
  96935. prev = this.b1Link.prev;
  96936. next = this.b1Link.next;
  96937. if (prev !== null) prev.next = next;
  96938. if (next !== null) next.prev = prev;
  96939. if (this.body1.contactLink == this.b1Link) this.body1.contactLink = next;
  96940. this.b1Link.prev = null;
  96941. this.b1Link.next = null;
  96942. this.b1Link.shape = null;
  96943. this.b1Link.body = null;
  96944. this.body1.numContacts--;
  96945. prev = this.b2Link.prev;
  96946. next = this.b2Link.next;
  96947. if (prev !== null) prev.next = next;
  96948. if (next !== null) next.prev = prev;
  96949. if (this.body2.contactLink == this.b2Link) this.body2.contactLink = next;
  96950. this.b2Link.prev = null;
  96951. this.b2Link.next = null;
  96952. this.b2Link.shape = null;
  96953. this.b2Link.body = null;
  96954. this.body2.numContacts--;
  96955. this.manifold.body1 = null;
  96956. this.manifold.body2 = null;
  96957. this.constraint.body1 = null;
  96958. this.constraint.body2 = null;
  96959. this.constraint.detach();
  96960. this.shape1 = null;
  96961. this.shape2 = null;
  96962. this.body1 = null;
  96963. this.body2 = null;
  96964. }
  96965. }
  96966. /**
  96967. * ...
  96968. * @author saharan
  96969. */
  96970. OIMO.ContactConstraint = function (manifold) {
  96971. OIMO.Constraint.call(this);
  96972. // The contact manifold of the constraint.
  96973. this.manifold = manifold;
  96974. // The coefficient of restitution of the constraint.
  96975. this.restitution = NaN;
  96976. // The coefficient of friction of the constraint.
  96977. this.friction = NaN;
  96978. this.p1 = null;
  96979. this.p2 = null;
  96980. this.lv1 = null;
  96981. this.lv2 = null;
  96982. this.av1 = null;
  96983. this.av2 = null;
  96984. this.i1 = null;
  96985. this.i2 = null;
  96986. this.ii1 = null;
  96987. this.ii2 = null;
  96988. this.m1 = NaN;
  96989. this.m2 = NaN;
  96990. this.num = 0;
  96991. this.ps = manifold.points;
  96992. this.cs = new OIMO.ContactPointDataBuffer();
  96993. this.cs.next = new OIMO.ContactPointDataBuffer();
  96994. this.cs.next.next = new OIMO.ContactPointDataBuffer();
  96995. this.cs.next.next.next = new OIMO.ContactPointDataBuffer();
  96996. }
  96997. OIMO.ContactConstraint.prototype = Object.create(OIMO.Constraint.prototype);
  96998. /**
  96999. * Attach the constraint to the bodies.
  97000. */
  97001. OIMO.ContactConstraint.prototype.attach = function () {
  97002. this.p1 = this.body1.position;
  97003. this.p2 = this.body2.position;
  97004. this.lv1 = this.body1.linearVelocity;
  97005. this.av1 = this.body1.angularVelocity;
  97006. this.lv2 = this.body2.linearVelocity;
  97007. this.av2 = this.body2.angularVelocity;
  97008. this.i1 = this.body1.inverseInertia;
  97009. this.i2 = this.body2.inverseInertia;
  97010. }
  97011. /**
  97012. * Detach the constraint from the bodies.
  97013. */
  97014. OIMO.ContactConstraint.prototype.detach = function () {
  97015. this.p1 = null;
  97016. this.p2 = null;
  97017. this.lv1 = null;
  97018. this.lv2 = null;
  97019. this.av1 = null;
  97020. this.av2 = null;
  97021. this.i1 = null;
  97022. this.i2 = null;
  97023. }
  97024. OIMO.ContactConstraint.prototype.preSolve = function (timeStep, invTimeStep) {
  97025. this.m1 = this.body1.inverseMass;
  97026. this.m2 = this.body2.inverseMass;
  97027. this.ii1 = this.i1.clone();
  97028. this.ii2 = this.i2.clone();
  97029. var ii1 = this.ii1.elements;
  97030. var ii2 = this.ii2.elements;
  97031. var p1x = this.p1.x;
  97032. var p1y = this.p1.y;
  97033. var p1z = this.p1.z;
  97034. var p2x = this.p2.x;
  97035. var p2y = this.p2.y;
  97036. var p2z = this.p2.z;
  97037. var m1m2 = this.m1 + this.m2;
  97038. this.num = this.manifold.numPoints;
  97039. var c = this.cs;
  97040. for (var i = 0; i < this.num; i++) {
  97041. var p = this.ps[i];
  97042. var tmp1X;
  97043. var tmp1Y;
  97044. var tmp1Z;
  97045. var tmp2X;
  97046. var tmp2Y;
  97047. var tmp2Z;
  97048. tmp1X = p.position.x;
  97049. tmp1Y = p.position.y;
  97050. tmp1Z = p.position.z;
  97051. var rp1X = tmp1X - p1x;
  97052. var rp1Y = tmp1Y - p1y;
  97053. var rp1Z = tmp1Z - p1z;
  97054. var rp2X = tmp1X - p2x;
  97055. var rp2Y = tmp1Y - p2y;
  97056. var rp2Z = tmp1Z - p2z;
  97057. c.rp1X = rp1X;
  97058. c.rp1Y = rp1Y;
  97059. c.rp1Z = rp1Z;
  97060. c.rp2X = rp2X;
  97061. c.rp2Y = rp2Y;
  97062. c.rp2Z = rp2Z;
  97063. c.norImp = p.normalImpulse;
  97064. c.tanImp = p.tangentImpulse;
  97065. c.binImp = p.binormalImpulse;
  97066. var norX = p.normal.x;
  97067. var norY = p.normal.y;
  97068. var norZ = p.normal.z;
  97069. var rvX = (this.lv2.x + this.av2.y * rp2Z - this.av2.z * rp2Y) - (this.lv1.x + this.av1.y * rp1Z - this.av1.z * rp1Y);
  97070. var rvY = (this.lv2.y + this.av2.z * rp2X - this.av2.x * rp2Z) - (this.lv1.y + this.av1.z * rp1X - this.av1.x * rp1Z);
  97071. var rvZ = (this.lv2.z + this.av2.x * rp2Y - this.av2.y * rp2X) - (this.lv1.z + this.av1.x * rp1Y - this.av1.y * rp1X);
  97072. var rvn = norX * rvX + norY * rvY + norZ * rvZ;
  97073. var tanX = rvX - rvn * norX;
  97074. var tanY = rvY - rvn * norY;
  97075. var tanZ = rvZ - rvn * norZ;
  97076. var len = tanX * tanX + tanY * tanY + tanZ * tanZ;
  97077. if (len > 0.04) {
  97078. len = 1 / OIMO.sqrt(len);
  97079. } else {
  97080. tanX = norY * norX - norZ * norZ;
  97081. tanY = -norZ * norY - norX * norX;
  97082. tanZ = norX * norZ + norY * norY;
  97083. len = 1 / OIMO.sqrt(tanX * tanX + tanY * tanY + tanZ * tanZ);
  97084. }
  97085. tanX *= len;
  97086. tanY *= len;
  97087. tanZ *= len;
  97088. var binX = norY * tanZ - norZ * tanY;
  97089. var binY = norZ * tanX - norX * tanZ;
  97090. var binZ = norX * tanY - norY * tanX;
  97091. c.norX = norX;
  97092. c.norY = norY;
  97093. c.norZ = norZ;
  97094. c.tanX = tanX;
  97095. c.tanY = tanY;
  97096. c.tanZ = tanZ;
  97097. c.binX = binX;
  97098. c.binY = binY;
  97099. c.binZ = binZ;
  97100. c.norU1X = norX * this.m1;
  97101. c.norU1Y = norY * this.m1;
  97102. c.norU1Z = norZ * this.m1;
  97103. c.norU2X = norX * this.m2;
  97104. c.norU2Y = norY * this.m2;
  97105. c.norU2Z = norZ * this.m2;
  97106. c.tanU1X = tanX * this.m1;
  97107. c.tanU1Y = tanY * this.m1;
  97108. c.tanU1Z = tanZ * this.m1;
  97109. c.tanU2X = tanX * this.m2;
  97110. c.tanU2Y = tanY * this.m2;
  97111. c.tanU2Z = tanZ * this.m2;
  97112. c.binU1X = binX * this.m1;
  97113. c.binU1Y = binY * this.m1;
  97114. c.binU1Z = binZ * this.m1;
  97115. c.binU2X = binX * this.m2;
  97116. c.binU2Y = binY * this.m2;
  97117. c.binU2Z = binZ * this.m2;
  97118. var norT1X = rp1Y * norZ - rp1Z * norY;
  97119. var norT1Y = rp1Z * norX - rp1X * norZ;
  97120. var norT1Z = rp1X * norY - rp1Y * norX;
  97121. var norT2X = rp2Y * norZ - rp2Z * norY;
  97122. var norT2Y = rp2Z * norX - rp2X * norZ;
  97123. var norT2Z = rp2X * norY - rp2Y * norX;
  97124. var tanT1X = rp1Y * tanZ - rp1Z * tanY;
  97125. var tanT1Y = rp1Z * tanX - rp1X * tanZ;
  97126. var tanT1Z = rp1X * tanY - rp1Y * tanX;
  97127. var tanT2X = rp2Y * tanZ - rp2Z * tanY;
  97128. var tanT2Y = rp2Z * tanX - rp2X * tanZ;
  97129. var tanT2Z = rp2X * tanY - rp2Y * tanX;
  97130. var binT1X = rp1Y * binZ - rp1Z * binY;
  97131. var binT1Y = rp1Z * binX - rp1X * binZ;
  97132. var binT1Z = rp1X * binY - rp1Y * binX;
  97133. var binT2X = rp2Y * binZ - rp2Z * binY;
  97134. var binT2Y = rp2Z * binX - rp2X * binZ;
  97135. var binT2Z = rp2X * binY - rp2Y * binX;
  97136. var norTU1X = norT1X * ii1[0] + norT1Y * ii1[1] + norT1Z * ii1[2];
  97137. var norTU1Y = norT1X * ii1[3] + norT1Y * ii1[4] + norT1Z * ii1[5];
  97138. var norTU1Z = norT1X * ii1[6] + norT1Y * ii1[7] + norT1Z * ii1[8];
  97139. var norTU2X = norT2X * ii2[0] + norT2Y * ii2[1] + norT2Z * ii2[2];
  97140. var norTU2Y = norT2X * ii2[3] + norT2Y * ii2[4] + norT2Z * ii2[5];
  97141. var norTU2Z = norT2X * ii2[6] + norT2Y * ii2[7] + norT2Z * ii2[8];
  97142. var tanTU1X = tanT1X * ii1[0] + tanT1Y * ii1[1] + tanT1Z * ii1[2];
  97143. var tanTU1Y = tanT1X * ii1[3] + tanT1Y * ii1[4] + tanT1Z * ii1[5];
  97144. var tanTU1Z = tanT1X * ii1[6] + tanT1Y * ii1[7] + tanT1Z * ii1[8];
  97145. var tanTU2X = tanT2X * ii2[0] + tanT2Y * ii2[1] + tanT2Z * ii2[2];
  97146. var tanTU2Y = tanT2X * ii2[3] + tanT2Y * ii2[4] + tanT2Z * ii2[5];
  97147. var tanTU2Z = tanT2X * ii2[6] + tanT2Y * ii2[7] + tanT2Z * ii2[8];
  97148. var binTU1X = binT1X * ii1[0] + binT1Y * ii1[1] + binT1Z * ii1[2];
  97149. var binTU1Y = binT1X * ii1[3] + binT1Y * ii1[4] + binT1Z * ii1[5];
  97150. var binTU1Z = binT1X * ii1[6] + binT1Y * ii1[7] + binT1Z * ii1[8];
  97151. var binTU2X = binT2X * ii2[0] + binT2Y * ii2[1] + binT2Z * ii2[2];
  97152. var binTU2Y = binT2X * ii2[3] + binT2Y * ii2[4] + binT2Z * ii2[5];
  97153. var binTU2Z = binT2X * ii2[6] + binT2Y * ii2[7] + binT2Z * ii2[8];
  97154. c.norT1X = norT1X;
  97155. c.norT1Y = norT1Y;
  97156. c.norT1Z = norT1Z;
  97157. c.tanT1X = tanT1X;
  97158. c.tanT1Y = tanT1Y;
  97159. c.tanT1Z = tanT1Z;
  97160. c.binT1X = binT1X;
  97161. c.binT1Y = binT1Y;
  97162. c.binT1Z = binT1Z;
  97163. c.norT2X = norT2X;
  97164. c.norT2Y = norT2Y;
  97165. c.norT2Z = norT2Z;
  97166. c.tanT2X = tanT2X;
  97167. c.tanT2Y = tanT2Y;
  97168. c.tanT2Z = tanT2Z;
  97169. c.binT2X = binT2X;
  97170. c.binT2Y = binT2Y;
  97171. c.binT2Z = binT2Z;
  97172. c.norTU1X = norTU1X;
  97173. c.norTU1Y = norTU1Y;
  97174. c.norTU1Z = norTU1Z;
  97175. c.tanTU1X = tanTU1X;
  97176. c.tanTU1Y = tanTU1Y;
  97177. c.tanTU1Z = tanTU1Z;
  97178. c.binTU1X = binTU1X;
  97179. c.binTU1Y = binTU1Y;
  97180. c.binTU1Z = binTU1Z;
  97181. c.norTU2X = norTU2X;
  97182. c.norTU2Y = norTU2Y;
  97183. c.norTU2Z = norTU2Z;
  97184. c.tanTU2X = tanTU2X;
  97185. c.tanTU2Y = tanTU2Y;
  97186. c.tanTU2Z = tanTU2Z;
  97187. c.binTU2X = binTU2X;
  97188. c.binTU2Y = binTU2Y;
  97189. c.binTU2Z = binTU2Z;
  97190. tmp1X = norT1X * ii1[0] + norT1Y * ii1[1] + norT1Z * ii1[2];
  97191. tmp1Y = norT1X * ii1[3] + norT1Y * ii1[4] + norT1Z * ii1[5];
  97192. tmp1Z = norT1X * ii1[6] + norT1Y * ii1[7] + norT1Z * ii1[8];
  97193. tmp2X = tmp1Y * rp1Z - tmp1Z * rp1Y;
  97194. tmp2Y = tmp1Z * rp1X - tmp1X * rp1Z;
  97195. tmp2Z = tmp1X * rp1Y - tmp1Y * rp1X;
  97196. tmp1X = norT2X * ii2[0] + norT2Y * ii2[1] + norT2Z * ii2[2];
  97197. tmp1Y = norT2X * ii2[3] + norT2Y * ii2[4] + norT2Z * ii2[5];
  97198. tmp1Z = norT2X * ii2[6] + norT2Y * ii2[7] + norT2Z * ii2[8];
  97199. tmp2X += tmp1Y * rp2Z - tmp1Z * rp2Y;
  97200. tmp2Y += tmp1Z * rp2X - tmp1X * rp2Z;
  97201. tmp2Z += tmp1X * rp2Y - tmp1Y * rp2X;
  97202. var norDen = 1 / (m1m2 + norX * tmp2X + norY * tmp2Y + norZ * tmp2Z);
  97203. tmp1X = tanT1X * ii1[0] + tanT1Y * ii1[1] + tanT1Z * ii1[2];
  97204. tmp1Y = tanT1X * ii1[3] + tanT1Y * ii1[4] + tanT1Z * ii1[5];
  97205. tmp1Z = tanT1X * ii1[6] + tanT1Y * ii1[7] + tanT1Z * ii1[8];
  97206. tmp2X = tmp1Y * rp1Z - tmp1Z * rp1Y;
  97207. tmp2Y = tmp1Z * rp1X - tmp1X * rp1Z;
  97208. tmp2Z = tmp1X * rp1Y - tmp1Y * rp1X;
  97209. tmp1X = tanT2X * ii2[0] + tanT2Y * ii2[1] + tanT2Z * ii2[2];
  97210. tmp1Y = tanT2X * ii2[3] + tanT2Y * ii2[4] + tanT2Z * ii2[5];
  97211. tmp1Z = tanT2X * ii2[6] + tanT2Y * ii2[7] + tanT2Z * ii2[8];
  97212. tmp2X += tmp1Y * rp2Z - tmp1Z * rp2Y;
  97213. tmp2Y += tmp1Z * rp2X - tmp1X * rp2Z;
  97214. tmp2Z += tmp1X * rp2Y - tmp1Y * rp2X;
  97215. var tanDen = 1 / (m1m2 + tanX * tmp2X + tanY * tmp2Y + tanZ * tmp2Z);
  97216. tmp1X = binT1X * ii1[0] + binT1Y * ii1[1] + binT1Z * ii1[2];
  97217. tmp1Y = binT1X * ii1[3] + binT1Y * ii1[4] + binT1Z * ii1[5];
  97218. tmp1Z = binT1X * ii1[6] + binT1Y * ii1[7] + binT1Z * ii1[8];
  97219. tmp2X = tmp1Y * rp1Z - tmp1Z * rp1Y;
  97220. tmp2Y = tmp1Z * rp1X - tmp1X * rp1Z;
  97221. tmp2Z = tmp1X * rp1Y - tmp1Y * rp1X;
  97222. tmp1X = binT2X * ii2[0] + binT2Y * ii2[1] + binT2Z * ii2[2];
  97223. tmp1Y = binT2X * ii2[3] + binT2Y * ii2[4] + binT2Z * ii2[5];
  97224. tmp1Z = binT2X * ii2[6] + binT2Y * ii2[7] + binT2Z * ii2[8];
  97225. tmp2X += tmp1Y * rp2Z - tmp1Z * rp2Y;
  97226. tmp2Y += tmp1Z * rp2X - tmp1X * rp2Z;
  97227. tmp2Z += tmp1X * rp2Y - tmp1Y * rp2X;
  97228. var binDen = 1 / (m1m2 + binX * tmp2X + binY * tmp2Y + binZ * tmp2Z);
  97229. c.norDen = norDen;
  97230. c.tanDen = tanDen;
  97231. c.binDen = binDen;
  97232. if (p.warmStarted) {
  97233. var norImp = p.normalImpulse;
  97234. this.lv1.x += c.norU1X * norImp;
  97235. this.lv1.y += c.norU1Y * norImp;
  97236. this.lv1.z += c.norU1Z * norImp;
  97237. this.av1.x += norTU1X * norImp;
  97238. this.av1.y += norTU1Y * norImp;
  97239. this.av1.z += norTU1Z * norImp;
  97240. this.lv2.x -= c.norU2X * norImp;
  97241. this.lv2.y -= c.norU2Y * norImp;
  97242. this.lv2.z -= c.norU2Z * norImp;
  97243. this.av2.x -= norTU2X * norImp;
  97244. this.av2.y -= norTU2Y * norImp;
  97245. this.av2.z -= norTU2Z * norImp;
  97246. c.norImp = norImp;
  97247. c.tanImp = 0;
  97248. c.binImp = 0;
  97249. rvn = 0; // disable bouncing
  97250. } else {
  97251. c.norImp = 0;
  97252. c.tanImp = 0;
  97253. c.binImp = 0;
  97254. }
  97255. if (rvn > -1) {
  97256. rvn = 0; // disable bouncing
  97257. }
  97258. var norTar = this.restitution * -rvn;
  97259. var sepV = -(p.penetration + 0.005) * invTimeStep * 0.05; // allow 0.5cm error
  97260. if (norTar < sepV) norTar = sepV;
  97261. c.norTar = norTar;
  97262. c.last = i == this.num - 1;
  97263. c = c.next;
  97264. }
  97265. }
  97266. OIMO.ContactConstraint.prototype.solve = function () {
  97267. var lv1x = this.lv1.x;
  97268. var lv1y = this.lv1.y;
  97269. var lv1z = this.lv1.z;
  97270. var lv2x = this.lv2.x;
  97271. var lv2y = this.lv2.y;
  97272. var lv2z = this.lv2.z;
  97273. var av1x = this.av1.x;
  97274. var av1y = this.av1.y;
  97275. var av1z = this.av1.z;
  97276. var av2x = this.av2.x;
  97277. var av2y = this.av2.y;
  97278. var av2z = this.av2.z;
  97279. var c = this.cs;
  97280. while (true) {
  97281. var oldImp1;
  97282. var newImp1;
  97283. var oldImp2;
  97284. var newImp2;
  97285. var rvn;
  97286. var norImp = c.norImp;
  97287. var tanImp = c.tanImp;
  97288. var binImp = c.binImp;
  97289. var max = -norImp * this.friction;
  97290. var rvX = lv2x - lv1x;
  97291. var rvY = lv2y - lv1y;
  97292. var rvZ = lv2z - lv1z;
  97293. rvn =
  97294. rvX * c.tanX + rvY * c.tanY + rvZ * c.tanZ +
  97295. av2x * c.tanT2X + av2y * c.tanT2Y + av2z * c.tanT2Z -
  97296. av1x * c.tanT1X - av1y * c.tanT1Y - av1z * c.tanT1Z
  97297. ;
  97298. oldImp1 = tanImp;
  97299. newImp1 = rvn * c.tanDen;
  97300. tanImp += newImp1;
  97301. rvn =
  97302. rvX * c.binX + rvY * c.binY + rvZ * c.binZ +
  97303. av2x * c.binT2X + av2y * c.binT2Y + av2z * c.binT2Z -
  97304. av1x * c.binT1X - av1y * c.binT1Y - av1z * c.binT1Z
  97305. ;
  97306. oldImp2 = binImp;
  97307. newImp2 = rvn * c.binDen;
  97308. binImp += newImp2;
  97309. // cone friction clamp
  97310. var len = tanImp * tanImp + binImp * binImp;
  97311. if (len > max * max) {
  97312. len = max / OIMO.sqrt(len);
  97313. tanImp *= len;
  97314. binImp *= len;
  97315. }
  97316. newImp1 = tanImp - oldImp1;
  97317. newImp2 = binImp - oldImp2;
  97318. lv1x += c.tanU1X * newImp1 + c.binU1X * newImp2;
  97319. lv1y += c.tanU1Y * newImp1 + c.binU1Y * newImp2;
  97320. lv1z += c.tanU1Z * newImp1 + c.binU1Z * newImp2;
  97321. av1x += c.tanTU1X * newImp1 + c.binTU1X * newImp2;
  97322. av1y += c.tanTU1Y * newImp1 + c.binTU1Y * newImp2;
  97323. av1z += c.tanTU1Z * newImp1 + c.binTU1Z * newImp2;
  97324. lv2x -= c.tanU2X * newImp1 + c.binU2X * newImp2;
  97325. lv2y -= c.tanU2Y * newImp1 + c.binU2Y * newImp2;
  97326. lv2z -= c.tanU2Z * newImp1 + c.binU2Z * newImp2;
  97327. av2x -= c.tanTU2X * newImp1 + c.binTU2X * newImp2;
  97328. av2y -= c.tanTU2Y * newImp1 + c.binTU2Y * newImp2;
  97329. av2z -= c.tanTU2Z * newImp1 + c.binTU2Z * newImp2;
  97330. // restitution part
  97331. rvn =
  97332. (lv2x - lv1x) * c.norX + (lv2y - lv1y) * c.norY + (lv2z - lv1z) * c.norZ +
  97333. av2x * c.norT2X + av2y * c.norT2Y + av2z * c.norT2Z -
  97334. av1x * c.norT1X - av1y * c.norT1Y - av1z * c.norT1Z;
  97335. oldImp1 = norImp;
  97336. newImp1 = (rvn - c.norTar) * c.norDen;
  97337. norImp += newImp1;
  97338. if (norImp > 0) norImp = 0;
  97339. newImp1 = norImp - oldImp1;
  97340. lv1x += c.norU1X * newImp1;
  97341. lv1y += c.norU1Y * newImp1;
  97342. lv1z += c.norU1Z * newImp1;
  97343. av1x += c.norTU1X * newImp1;
  97344. av1y += c.norTU1Y * newImp1;
  97345. av1z += c.norTU1Z * newImp1;
  97346. lv2x -= c.norU2X * newImp1;
  97347. lv2y -= c.norU2Y * newImp1;
  97348. lv2z -= c.norU2Z * newImp1;
  97349. av2x -= c.norTU2X * newImp1;
  97350. av2y -= c.norTU2Y * newImp1;
  97351. av2z -= c.norTU2Z * newImp1;
  97352. c.norImp = norImp;
  97353. c.tanImp = tanImp;
  97354. c.binImp = binImp;
  97355. if (c.last) break;
  97356. c = c.next;
  97357. }
  97358. this.lv1.x = lv1x;
  97359. this.lv1.y = lv1y;
  97360. this.lv1.z = lv1z;
  97361. this.lv2.x = lv2x;
  97362. this.lv2.y = lv2y;
  97363. this.lv2.z = lv2z;
  97364. this.av1.x = av1x;
  97365. this.av1.y = av1y;
  97366. this.av1.z = av1z;
  97367. this.av2.x = av2x;
  97368. this.av2.y = av2y;
  97369. this.av2.z = av2z;
  97370. }
  97371. OIMO.ContactConstraint.prototype.postSolve = function () {
  97372. var c = this.cs;
  97373. var i = this.num;
  97374. while (i--) {
  97375. //for(var i=0;i<this.num;i++){
  97376. var p = this.ps[i];
  97377. p.normal.x = c.norX;
  97378. p.normal.y = c.norY;
  97379. p.normal.z = c.norZ;
  97380. p.tangent.x = c.tanX;
  97381. p.tangent.y = c.tanY;
  97382. p.tangent.z = c.tanZ;
  97383. p.binormal.x = c.binX;
  97384. p.binormal.y = c.binY;
  97385. p.binormal.z = c.binZ;
  97386. p.normalImpulse = c.norImp;
  97387. p.tangentImpulse = c.tanImp;
  97388. p.binormalImpulse = c.binImp;
  97389. p.normalDenominator = c.norDen;
  97390. p.tangentDenominator = c.tanDen;
  97391. p.binormalDenominator = c.binDen;
  97392. c = c.next;
  97393. }
  97394. }
  97395. /**
  97396. * A link list of contacts.
  97397. * @author saharan
  97398. */
  97399. OIMO.ContactLink = function (contact) {
  97400. // The previous contact link.
  97401. this.prev = null;
  97402. // The next contact link.
  97403. this.next = null;
  97404. // The shape of the contact.
  97405. this.shape = null;
  97406. // The other rigid body.
  97407. this.body = null;
  97408. // The contact of the link.
  97409. this.contact = contact;
  97410. }
  97411. /**
  97412. * A contact manifold between two shapes.
  97413. * @author saharan
  97414. */
  97415. OIMO.ContactManifold = function () {
  97416. // The first rigid body.
  97417. this.body1 = null;
  97418. // The second rigid body.
  97419. this.body2 = null;
  97420. // The number of manifold points.
  97421. this.numPoints = 0;
  97422. // The manifold points.
  97423. this.points = [];
  97424. this.points.length = 4;
  97425. this.points[0] = new OIMO.ManifoldPoint();
  97426. this.points[1] = new OIMO.ManifoldPoint();
  97427. this.points[2] = new OIMO.ManifoldPoint();
  97428. this.points[3] = new OIMO.ManifoldPoint();
  97429. }
  97430. OIMO.ContactManifold.prototype = {
  97431. constructor: OIMO.ContactManifold,
  97432. /**
  97433. * Reset the manifold.
  97434. * @param shape1
  97435. * @param shape2
  97436. */
  97437. reset: function (shape1, shape2) {
  97438. this.body1 = shape1.parent;
  97439. this.body2 = shape2.parent;
  97440. this.numPoints = 0;
  97441. },
  97442. /**
  97443. * Add a point into this manifold.
  97444. * @param x
  97445. * @param y
  97446. * @param z
  97447. * @param normalX
  97448. * @param normalY
  97449. * @param normalZ
  97450. * @param penetration
  97451. * @param flip
  97452. */
  97453. addPoint: function (x, y, z, normalX, normalY, normalZ, penetration, flip) {
  97454. var p = this.points[this.numPoints++];
  97455. p.position.x = x;
  97456. p.position.y = y;
  97457. p.position.z = z;
  97458. var r = this.body1.rotation;
  97459. var rx = x - this.body1.position.x;
  97460. var ry = y - this.body1.position.y;
  97461. var rz = z - this.body1.position.z;
  97462. var tr = r.elements;
  97463. p.localPoint1.x = rx * tr[0] + ry * tr[3] + rz * tr[6];
  97464. p.localPoint1.y = rx * tr[1] + ry * tr[4] + rz * tr[7];
  97465. p.localPoint1.z = rx * tr[2] + ry * tr[5] + rz * tr[8];
  97466. r = this.body2.rotation;
  97467. rx = x - this.body2.position.x;
  97468. ry = y - this.body2.position.y;
  97469. rz = z - this.body2.position.z;
  97470. p.localPoint2.x = rx * tr[0] + ry * tr[3] + rz * tr[6];
  97471. p.localPoint2.y = rx * tr[1] + ry * tr[4] + rz * tr[7];
  97472. p.localPoint2.z = rx * tr[2] + ry * tr[5] + rz * tr[8];
  97473. p.normalImpulse = 0;
  97474. if (flip) {
  97475. p.normal.x = -normalX;
  97476. p.normal.y = -normalY;
  97477. p.normal.z = -normalZ;
  97478. } else {
  97479. p.normal.x = normalX;
  97480. p.normal.y = normalY;
  97481. p.normal.z = normalZ;
  97482. }
  97483. p.penetration = penetration;
  97484. p.warmStarted = false;
  97485. }
  97486. }
  97487. OIMO.ContactPointDataBuffer = function () {
  97488. this.norX = NaN;
  97489. this.norY = NaN;
  97490. this.norZ = NaN;
  97491. this.tanX = NaN;
  97492. this.tanY = NaN;
  97493. this.tanZ = NaN;
  97494. this.binX = NaN;
  97495. this.binY = NaN;
  97496. this.binZ = NaN;
  97497. this.rp1X = NaN;
  97498. this.rp1Y = NaN;
  97499. this.rp1Z = NaN;
  97500. this.rp2X = NaN;
  97501. this.rp2Y = NaN;
  97502. this.rp2Z = NaN;
  97503. this.norU1X = NaN;
  97504. this.norU1Y = NaN;
  97505. this.norU1Z = NaN;
  97506. this.norU2X = NaN;
  97507. this.norU2Y = NaN;
  97508. this.norU2Z = NaN;
  97509. this.tanU1X = NaN;
  97510. this.tanU1Y = NaN;
  97511. this.tanU1Z = NaN;
  97512. this.tanU2X = NaN;
  97513. this.tanU2Y = NaN;
  97514. this.tanU2Z = NaN;
  97515. this.binU1X = NaN;
  97516. this.binU1Y = NaN;
  97517. this.binU1Z = NaN;
  97518. this.binU2X = NaN;
  97519. this.binU2Y = NaN;
  97520. this.binU2Z = NaN;
  97521. this.norT1X = NaN;
  97522. this.norT1Y = NaN;
  97523. this.norT1Z = NaN;
  97524. this.norT2X = NaN;
  97525. this.norT2Y = NaN;
  97526. this.norT2Z = NaN;
  97527. this.tanT1X = NaN;
  97528. this.tanT1Y = NaN;
  97529. this.tanT1Z = NaN;
  97530. this.tanT2X = NaN;
  97531. this.tanT2Y = NaN;
  97532. this.tanT2Z = NaN;
  97533. this.binT1X = NaN;
  97534. this.binT1Y = NaN;
  97535. this.binT1Z = NaN;
  97536. this.binT2X = NaN;
  97537. this.binT2Y = NaN;
  97538. this.binT2Z = NaN;
  97539. this.norTU1X = NaN;
  97540. this.norTU1Y = NaN;
  97541. this.norTU1Z = NaN;
  97542. this.norTU2X = NaN;
  97543. this.norTU2Y = NaN;
  97544. this.norTU2Z = NaN;
  97545. this.tanTU1X = NaN;
  97546. this.tanTU1Y = NaN;
  97547. this.tanTU1Z = NaN;
  97548. this.tanTU2X = NaN;
  97549. this.tanTU2Y = NaN;
  97550. this.tanTU2Z = NaN;
  97551. this.binTU1X = NaN;
  97552. this.binTU1Y = NaN;
  97553. this.binTU1Z = NaN;
  97554. this.binTU2X = NaN;
  97555. this.binTU2Y = NaN;
  97556. this.binTU2Z = NaN;
  97557. this.norImp = NaN;
  97558. this.tanImp = NaN;
  97559. this.binImp = NaN;
  97560. this.norDen = NaN;
  97561. this.tanDen = NaN;
  97562. this.binDen = NaN;
  97563. this.norTar = NaN;
  97564. this.next = null;
  97565. this.last = false;
  97566. }
  97567. OIMO.ImpulseDataBuffer = function () {
  97568. this.lp1X = NaN;
  97569. this.lp1Y = NaN;
  97570. this.lp1Z = NaN;
  97571. this.lp2X = NaN;
  97572. this.lp2Y = NaN;
  97573. this.lp2Z = NaN;
  97574. this.impulse = NaN;
  97575. }
  97576. /**
  97577. * The class holds details of the contact point.
  97578. * @author saharan
  97579. */
  97580. OIMO.ManifoldPoint = function () {
  97581. // Whether this manifold point is persisting or not.
  97582. this.warmStarted = false;
  97583. // The position of this manifold point.
  97584. this.position = new OIMO.Vec3();
  97585. // The position in the first shape's coordinate.
  97586. this.localPoint1 = new OIMO.Vec3();
  97587. // The position in the second shape's coordinate.
  97588. this.localPoint2 = new OIMO.Vec3();
  97589. // The normal vector of this manifold point.
  97590. this.normal = new OIMO.Vec3();
  97591. // The tangent vector of this manifold point.
  97592. this.tangent = new OIMO.Vec3();
  97593. // The binormal vector of this manifold point.
  97594. this.binormal = new OIMO.Vec3();
  97595. // The impulse in normal direction.
  97596. this.normalImpulse = 0;
  97597. // The impulse in tangent direction.
  97598. this.tangentImpulse = 0;
  97599. // The impulse in binormal direction.
  97600. this.binormalImpulse = 0;
  97601. // The denominator in normal direction.
  97602. this.normalDenominator = 0;
  97603. // The denominator in tangent direction.
  97604. this.tangentDenominator = 0;
  97605. // The denominator in binormal direction.
  97606. this.binormalDenominator = 0;
  97607. // The depth of penetration.
  97608. this.penetration = 0;
  97609. }
  97610. /**
  97611. * This class holds mass information of a shape.
  97612. * @author saharan
  97613. */
  97614. OIMO.MassInfo = function () {
  97615. // Mass of the shape.
  97616. this.mass = 0;
  97617. // The moment inertia of the shape.
  97618. this.inertia = new OIMO.Mat33();
  97619. };
  97620. /**
  97621. * A shape is used to detect collisions of rigid bodies.
  97622. * @author saharan
  97623. * @author lo-th
  97624. */
  97625. OIMO.Shape = function (config) {
  97626. this.type = OIMO.SHAPE_NULL;
  97627. // The global identification of the shape should be unique to the shape.
  97628. this.id = OIMO.nextID++;
  97629. // The previous shape in parent rigid body.
  97630. this.prev = null;
  97631. // The next shape in parent rigid body.
  97632. this.next = null;
  97633. // The proxy of the shape used for broad-phase collision detection.
  97634. this.proxy = null;
  97635. // The parent rigid body of the shape.
  97636. this.parent = null;
  97637. // The linked list of the contacts with the shape.
  97638. this.contactLink = null;
  97639. // The number of the contacts with the shape.
  97640. this.numContacts = 0;
  97641. // The center of gravity of the shape in world coordinate system.
  97642. this.position = new OIMO.Vec3();
  97643. // The rotation matrix of the shape in world coordinate system
  97644. this.rotation = new OIMO.Mat33();
  97645. // The position of the shape in parent's coordinate system.
  97646. this.relativePosition = new OIMO.Vec3().copy(config.relativePosition);
  97647. // The rotation matrix of the shape in parent's coordinate system.
  97648. this.relativeRotation = new OIMO.Mat33().copy(config.relativeRotation);
  97649. // The axis-aligned bounding box of the shape.
  97650. this.aabb = new OIMO.AABB();
  97651. // The density of the shape.
  97652. this.density = config.density;
  97653. // The coefficient of friction of the shape.
  97654. this.friction = config.friction;
  97655. // The coefficient of restitution of the shape.
  97656. this.restitution = config.restitution;
  97657. // The bits of the collision groups to which the shape belongs.
  97658. this.belongsTo = config.belongsTo;
  97659. // The bits of the collision groups with which the shape collides.
  97660. this.collidesWith = config.collidesWith;
  97661. };
  97662. OIMO.Shape.prototype = {
  97663. constructor: OIMO.Shape,
  97664. // Calculate the mass information of the shape.
  97665. calculateMassInfo: function (out) {
  97666. OIMO.Error("Shape", "Inheritance error.");
  97667. },
  97668. // Update the proxy of the shape.
  97669. updateProxy: function () {
  97670. OIMO.Error("Shape", "Inheritance error.");
  97671. }
  97672. };
  97673. /**
  97674. * A shape configuration holds common configuration data for constructing a shape.
  97675. * Shape configurations can be reused safely.
  97676. * @author saharan
  97677. */
  97678. OIMO.ShapeConfig = function () {
  97679. // The position of the shape in parent's coordinate system.
  97680. this.relativePosition = new OIMO.Vec3();
  97681. // The rotation matrix of the shape in parent's coordinate system.
  97682. this.relativeRotation = new OIMO.Mat33();
  97683. // The coefficient of friction of the shape.
  97684. this.friction = 0.4;
  97685. // The coefficient of restitution of the shape.
  97686. this.restitution = 0.2;
  97687. // The density of the shape.
  97688. this.density = 1;
  97689. // The bits of the collision groups to which the shape belongs.
  97690. this.belongsTo = 1;
  97691. // The bits of the collision groups with which the shape collides.
  97692. this.collidesWith = 0xffffffff;
  97693. };
  97694. /**
  97695. * A box shape.
  97696. * @author saharan
  97697. * @author lo-th
  97698. */
  97699. OIMO.BoxShape = function (config, Width, Height, Depth) {
  97700. OIMO.Shape.call(this, config);
  97701. this.type = OIMO.SHAPE_BOX;
  97702. // The width of the box.
  97703. this.width = Width;
  97704. // The height of the box.
  97705. this.height = Height;
  97706. // The depth of the box.
  97707. this.depth = Depth;
  97708. // The half-width of the box.
  97709. this.halfWidth = Width * 0.5;
  97710. // The half-height of the box.
  97711. this.halfHeight = Height * 0.5;
  97712. // The half-depth of the box.
  97713. this.halfDepth = Depth * 0.5;
  97714. this.dimentions = new OIMO_ARRAY_TYPE(18);
  97715. this.elements = new OIMO_ARRAY_TYPE(24);
  97716. };
  97717. OIMO.BoxShape.prototype = Object.create(OIMO.Shape.prototype);
  97718. OIMO.BoxShape.prototype.constructor = OIMO.BoxShape;
  97719. OIMO.BoxShape.prototype.calculateMassInfo = function (out) {
  97720. var mass = this.width * this.height * this.depth * this.density;
  97721. var divid = 1 / 12;
  97722. out.mass = mass;
  97723. out.inertia.set(
  97724. mass * (this.height * this.height + this.depth * this.depth) * divid, 0, 0,
  97725. 0, mass * (this.width * this.width + this.depth * this.depth) * divid, 0,
  97726. 0, 0, mass * (this.width * this.width + this.height * this.height) * divid
  97727. );
  97728. };
  97729. OIMO.BoxShape.prototype.updateProxy = function () {
  97730. var te = this.rotation.elements;
  97731. var di = this.dimentions;
  97732. // Width
  97733. di[0] = te[0];
  97734. di[1] = te[3];
  97735. di[2] = te[6];
  97736. // Height
  97737. di[3] = te[1];
  97738. di[4] = te[4];
  97739. di[5] = te[7];
  97740. // Depth
  97741. di[6] = te[2];
  97742. di[7] = te[5];
  97743. di[8] = te[8];
  97744. // halp Width
  97745. di[9] = te[0] * this.halfWidth;
  97746. di[10] = te[3] * this.halfWidth;
  97747. di[11] = te[6] * this.halfWidth;
  97748. // halp Height
  97749. di[12] = te[1] * this.halfHeight;
  97750. di[13] = te[4] * this.halfHeight;
  97751. di[14] = te[7] * this.halfHeight;
  97752. // halp Depth
  97753. di[15] = te[2] * this.halfDepth;
  97754. di[16] = te[5] * this.halfDepth;
  97755. di[17] = te[8] * this.halfDepth;
  97756. var wx = di[9];
  97757. var wy = di[10];
  97758. var wz = di[11];
  97759. var hx = di[12];
  97760. var hy = di[13];
  97761. var hz = di[14];
  97762. var dx = di[15];
  97763. var dy = di[16];
  97764. var dz = di[17];
  97765. var x = this.position.x;
  97766. var y = this.position.y;
  97767. var z = this.position.z;
  97768. var v = this.elements;
  97769. //v1
  97770. v[0] = x + wx + hx + dx;
  97771. v[1] = y + wy + hy + dy;
  97772. v[2] = z + wz + hz + dz;
  97773. //v2
  97774. v[3] = x + wx + hx - dx;
  97775. v[4] = y + wy + hy - dy;
  97776. v[5] = z + wz + hz - dz;
  97777. //v3
  97778. v[6] = x + wx - hx + dx;
  97779. v[7] = y + wy - hy + dy;
  97780. v[8] = z + wz - hz + dz;
  97781. //v4
  97782. v[9] = x + wx - hx - dx;
  97783. v[10] = y + wy - hy - dy;
  97784. v[11] = z + wz - hz - dz;
  97785. //v5
  97786. v[12] = x - wx + hx + dx;
  97787. v[13] = y - wy + hy + dy;
  97788. v[14] = z - wz + hz + dz;
  97789. //v6
  97790. v[15] = x - wx + hx - dx;
  97791. v[16] = y - wy + hy - dy;
  97792. v[17] = z - wz + hz - dz;
  97793. //v7
  97794. v[18] = x - wx - hx + dx;
  97795. v[19] = y - wy - hy + dy;
  97796. v[20] = z - wz - hz + dz;
  97797. //v8
  97798. v[21] = x - wx - hx - dx;
  97799. v[22] = y - wy - hy - dy;
  97800. v[23] = z - wz - hz - dz;
  97801. var w = di[9] < 0 ? -di[9] : di[9];
  97802. var h = di[10] < 0 ? -di[10] : di[10];
  97803. var d = di[11] < 0 ? -di[11] : di[11];
  97804. w = di[12] < 0 ? w - di[12] : w + di[12];
  97805. h = di[13] < 0 ? h - di[13] : h + di[13];
  97806. d = di[14] < 0 ? d - di[14] : d + di[14];
  97807. w = di[15] < 0 ? w - di[15] : w + di[15];
  97808. h = di[16] < 0 ? h - di[16] : h + di[16];
  97809. d = di[17] < 0 ? d - di[17] : d + di[17];
  97810. var p = OIMO.AABB_PROX;
  97811. this.aabb.set(
  97812. this.position.x - w - p, this.position.x + w + p,
  97813. this.position.y - h - p, this.position.y + h + p,
  97814. this.position.z - d - p, this.position.z + d + p
  97815. );
  97816. if (this.proxy != null) this.proxy.update();
  97817. };
  97818. /**
  97819. * A sphere shape.
  97820. * @author saharan
  97821. * @author lo-th
  97822. */
  97823. OIMO.SphereShape = function (config, radius) {
  97824. OIMO.Shape.call(this, config);
  97825. this.type = OIMO.SHAPE_SPHERE;
  97826. // The radius of the shape.
  97827. this.radius = radius;
  97828. };
  97829. OIMO.SphereShape.prototype = Object.create(OIMO.Shape.prototype);
  97830. OIMO.SphereShape.prototype.constructor = OIMO.SphereShape;
  97831. OIMO.SphereShape.prototype.calculateMassInfo = function (out) {
  97832. var mass = 1.333 * OIMO.PI * this.radius * this.radius * this.radius * this.density;
  97833. out.mass = mass;
  97834. var inertia = mass * this.radius * this.radius * 0.4;
  97835. out.inertia.set(inertia, 0, 0, 0, inertia, 0, 0, 0, inertia);
  97836. };
  97837. OIMO.SphereShape.prototype.updateProxy = function () {
  97838. var p = OIMO.AABB_PROX;
  97839. this.aabb.set(
  97840. this.position.x - this.radius - p, this.position.x + this.radius + p,
  97841. this.position.y - this.radius - p, this.position.y + this.radius + p,
  97842. this.position.z - this.radius - p, this.position.z + this.radius + p
  97843. );
  97844. if (this.proxy != null) this.proxy.update();
  97845. };
  97846. /**
  97847. * A cylinder shap.
  97848. * @author saharan
  97849. * @author lo-th
  97850. */
  97851. OIMO.CylinderShape = function (config, radius, height) {
  97852. OIMO.Shape.call(this, config);
  97853. this.type = OIMO.SHAPE_CYLINDER;
  97854. this.radius = radius;
  97855. this.height = height;
  97856. this.halfHeight = height * 0.5;
  97857. this.normalDirection = new OIMO.Vec3();
  97858. this.halfDirection = new OIMO.Vec3();
  97859. };
  97860. OIMO.CylinderShape.prototype = Object.create(OIMO.Shape.prototype);
  97861. OIMO.CylinderShape.prototype.constructor = OIMO.CylinderShape;
  97862. OIMO.CylinderShape.prototype.calculateMassInfo = function (out) {
  97863. var rsq = this.radius * this.radius;
  97864. var mass = OIMO.PI * rsq * this.height * this.density;
  97865. var inertiaXZ = ((0.25 * rsq) + (0.0833 * this.height * this.height)) * mass;
  97866. var inertiaY = 0.5 * rsq;
  97867. out.mass = mass;
  97868. out.inertia.set(inertiaXZ, 0, 0, 0, inertiaY, 0, 0, 0, inertiaXZ);
  97869. };
  97870. OIMO.CylinderShape.prototype.updateProxy = function () {
  97871. var te = this.rotation.elements;
  97872. var len, wx, hy, dz, xx, yy, zz, w, h, d, p;
  97873. xx = te[1] * te[1];
  97874. yy = te[4] * te[4];
  97875. zz = te[7] * te[7];
  97876. this.normalDirection.set(te[1], te[4], te[7]);
  97877. this.halfDirection.scale(this.normalDirection, this.halfHeight);
  97878. wx = 1 - xx;
  97879. len = OIMO.sqrt(wx * wx + xx * yy + xx * zz);
  97880. if (len > 0) len = this.radius / len;
  97881. wx *= len;
  97882. hy = 1 - yy;
  97883. len = OIMO.sqrt(yy * xx + hy * hy + yy * zz);
  97884. if (len > 0) len = this.radius / len;
  97885. hy *= len;
  97886. dz = 1 - zz;
  97887. len = OIMO.sqrt(zz * xx + zz * yy + dz * dz);
  97888. if (len > 0) len = this.radius / len;
  97889. dz *= len;
  97890. w = this.halfDirection.x < 0 ? -this.halfDirection.x : this.halfDirection.x;
  97891. h = this.halfDirection.y < 0 ? -this.halfDirection.y : this.halfDirection.y;
  97892. d = this.halfDirection.z < 0 ? -this.halfDirection.z : this.halfDirection.z;
  97893. w = wx < 0 ? w - wx : w + wx;
  97894. h = hy < 0 ? h - hy : h + hy;
  97895. d = dz < 0 ? d - dz : d + dz;
  97896. p = OIMO.AABB_PROX;
  97897. this.aabb.set(
  97898. this.position.x - w - p, this.position.x + w + p,
  97899. this.position.y - h - p, this.position.y + h + p,
  97900. this.position.z - d - p, this.position.z + d + p
  97901. );
  97902. if (this.proxy != null) this.proxy.update();
  97903. };
  97904. /**
  97905. * A tetra shape.
  97906. * @author xprogram
  97907. */
  97908. OIMO.TetraShape = function (config, p1, p2, p3, p4) {
  97909. OIMO.Shape.call(this, config);
  97910. this.type = OIMO.SHAPE_TETRA;
  97911. // Vertices and faces of tetra
  97912. this.verts = [p1, p2, p3, p4];
  97913. this.faces = [
  97914. mtri(0, 1, 2),
  97915. mtri(1, 2, 3),
  97916. mtri(2, 3, 4),
  97917. mtri(4, 0, 1),
  97918. ];
  97919. };
  97920. OIMO.TetraShape.prototype = Object.create(OIMO.Shape.prototype);
  97921. OIMO.TetraShape.prototype.constructor = OIMO.TetraShape;
  97922. OIMO.TetraShape.prototype.calculateMassInfo = function () {
  97923. // I guess you could calculate box mass and split it
  97924. // in half for the tetra...
  97925. };
  97926. OIMO.TetraShape.prototype.updateProxy = function () {
  97927. this.aabb.setFromPoints(this.verts);
  97928. if (this.proxy !== null)
  97929. this.proxy.update();
  97930. };
  97931. function mtri(a, b, c) {
  97932. return { a: a, b: b, c: c };
  97933. }
  97934. OIMO.CollisionDetector = function () {
  97935. this.flip = false;
  97936. };
  97937. OIMO.CollisionDetector.prototype = {
  97938. constructor: OIMO.CollisionDetector,
  97939. detectCollision: function (shape1, shape2, manifold) {
  97940. OIMO.Error("CollisionDetector", "Inheritance error.");
  97941. }
  97942. };
  97943. /**
  97944. * A collision detector which detects collisions between two boxes.
  97945. * @author saharan
  97946. */
  97947. OIMO.BoxBoxCollisionDetector = function () {
  97948. OIMO.CollisionDetector.call(this);
  97949. this.clipVertices1 = new OIMO_ARRAY_TYPE(24); // 8 vertices x,y,z
  97950. this.clipVertices2 = new OIMO_ARRAY_TYPE(24);
  97951. this.used = new OIMO_ARRAY_TYPE(8);
  97952. this.INF = 1 / 0;
  97953. };
  97954. OIMO.BoxBoxCollisionDetector.prototype = Object.create(OIMO.CollisionDetector.prototype);
  97955. OIMO.BoxBoxCollisionDetector.prototype.constructor = OIMO.BoxBoxCollisionDetector;
  97956. OIMO.BoxBoxCollisionDetector.prototype.detectCollision = function (shape1, shape2, manifold) {
  97957. // What you are doing
  97958. // · I to prepare a separate axis of the fifteen
  97959. //-Six in each of three normal vectors of the xyz direction of the box both
  97960. // · Remaining nine 3x3 a vector perpendicular to the side of the box 2 and the side of the box 1
  97961. // · Calculate the depth to the separation axis
  97962. // Calculates the distance using the inner product and put the amount of embedment
  97963. // · However a vertical separation axis and side to weight a little to avoid vibration
  97964. // And end when there is a separate axis that is remote even one
  97965. // · I look for separation axis with little to dent most
  97966. // Men and if separation axis of the first six - end collision
  97967. // Heng If it separate axis of nine other - side collision
  97968. // Heng - case of a side collision
  97969. // · Find points of two sides on which you made ​​the separation axis
  97970. // Calculates the point of closest approach of a straight line consisting of separate axis points obtained, and the collision point
  97971. //-Surface - the case of the plane crash
  97972. //-Box A, box B and the other a box of better made ​​a separate axis
  97973. // • 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
  97974. // When viewed from the front surface A, and the cut part exceeding the area of the surface A is a surface B
  97975. //-Plane B becomes the 3-8 triangle, I a candidate for the collision point the vertex of surface B
  97976. // • If more than one candidate 5 exists, scraping up to four
  97977. // For potential collision points of all, to examine the distance between the surface A
  97978. // • If you were on the inside surface of A, and the collision point
  97979. var b1;
  97980. var b2;
  97981. if (shape1.id < shape2.id) {
  97982. b1 = (shape1);
  97983. b2 = (shape2);
  97984. } else {
  97985. b1 = (shape2);
  97986. b2 = (shape1);
  97987. }
  97988. var V1 = b1.elements;
  97989. var V2 = b2.elements;
  97990. var D1 = b1.dimentions;
  97991. var D2 = b2.dimentions;
  97992. var p1 = b1.position;
  97993. var p2 = b2.position;
  97994. var p1x = p1.x;
  97995. var p1y = p1.y;
  97996. var p1z = p1.z;
  97997. var p2x = p2.x;
  97998. var p2y = p2.y;
  97999. var p2z = p2.z;
  98000. // diff
  98001. var dx = p2x - p1x;
  98002. var dy = p2y - p1y;
  98003. var dz = p2z - p1z;
  98004. // distance
  98005. var w1 = b1.halfWidth;
  98006. var h1 = b1.halfHeight;
  98007. var d1 = b1.halfDepth;
  98008. var w2 = b2.halfWidth;
  98009. var h2 = b2.halfHeight;
  98010. var d2 = b2.halfDepth;
  98011. // direction
  98012. // ----------------------------
  98013. // 15 separating axes
  98014. // 1~6: face
  98015. // 7~f: edge
  98016. // http://marupeke296.com/COL_3D_No13_OBBvsOBB.html
  98017. // ----------------------------
  98018. var a1x = D1[0];
  98019. var a1y = D1[1];
  98020. var a1z = D1[2];
  98021. var a2x = D1[3];
  98022. var a2y = D1[4];
  98023. var a2z = D1[5];
  98024. var a3x = D1[6];
  98025. var a3y = D1[7];
  98026. var a3z = D1[8];
  98027. var d1x = D1[9];
  98028. var d1y = D1[10];
  98029. var d1z = D1[11];
  98030. var d2x = D1[12];
  98031. var d2y = D1[13];
  98032. var d2z = D1[14];
  98033. var d3x = D1[15];
  98034. var d3y = D1[16];
  98035. var d3z = D1[17];
  98036. var a4x = D2[0];
  98037. var a4y = D2[1];
  98038. var a4z = D2[2];
  98039. var a5x = D2[3];
  98040. var a5y = D2[4];
  98041. var a5z = D2[5];
  98042. var a6x = D2[6];
  98043. var a6y = D2[7];
  98044. var a6z = D2[8];
  98045. var d4x = D2[9];
  98046. var d4y = D2[10];
  98047. var d4z = D2[11];
  98048. var d5x = D2[12];
  98049. var d5y = D2[13];
  98050. var d5z = D2[14];
  98051. var d6x = D2[15];
  98052. var d6y = D2[16];
  98053. var d6z = D2[17];
  98054. var a7x = a1y * a4z - a1z * a4y;
  98055. var a7y = a1z * a4x - a1x * a4z;
  98056. var a7z = a1x * a4y - a1y * a4x;
  98057. var a8x = a1y * a5z - a1z * a5y;
  98058. var a8y = a1z * a5x - a1x * a5z;
  98059. var a8z = a1x * a5y - a1y * a5x;
  98060. var a9x = a1y * a6z - a1z * a6y;
  98061. var a9y = a1z * a6x - a1x * a6z;
  98062. var a9z = a1x * a6y - a1y * a6x;
  98063. var aax = a2y * a4z - a2z * a4y;
  98064. var aay = a2z * a4x - a2x * a4z;
  98065. var aaz = a2x * a4y - a2y * a4x;
  98066. var abx = a2y * a5z - a2z * a5y;
  98067. var aby = a2z * a5x - a2x * a5z;
  98068. var abz = a2x * a5y - a2y * a5x;
  98069. var acx = a2y * a6z - a2z * a6y;
  98070. var acy = a2z * a6x - a2x * a6z;
  98071. var acz = a2x * a6y - a2y * a6x;
  98072. var adx = a3y * a4z - a3z * a4y;
  98073. var ady = a3z * a4x - a3x * a4z;
  98074. var adz = a3x * a4y - a3y * a4x;
  98075. var aex = a3y * a5z - a3z * a5y;
  98076. var aey = a3z * a5x - a3x * a5z;
  98077. var aez = a3x * a5y - a3y * a5x;
  98078. var afx = a3y * a6z - a3z * a6y;
  98079. var afy = a3z * a6x - a3x * a6z;
  98080. var afz = a3x * a6y - a3y * a6x;
  98081. // right or left flags
  98082. var right1;
  98083. var right2;
  98084. var right3;
  98085. var right4;
  98086. var right5;
  98087. var right6;
  98088. var right7;
  98089. var right8;
  98090. var right9;
  98091. var righta;
  98092. var rightb;
  98093. var rightc;
  98094. var rightd;
  98095. var righte;
  98096. var rightf;
  98097. // overlapping distances
  98098. var overlap1;
  98099. var overlap2;
  98100. var overlap3;
  98101. var overlap4;
  98102. var overlap5;
  98103. var overlap6;
  98104. var overlap7;
  98105. var overlap8;
  98106. var overlap9;
  98107. var overlapa;
  98108. var overlapb;
  98109. var overlapc;
  98110. var overlapd;
  98111. var overlape;
  98112. var overlapf;
  98113. // invalid flags
  98114. var invalid7 = false;
  98115. var invalid8 = false;
  98116. var invalid9 = false;
  98117. var invalida = false;
  98118. var invalidb = false;
  98119. var invalidc = false;
  98120. var invalidd = false;
  98121. var invalide = false;
  98122. var invalidf = false;
  98123. // temporary variables
  98124. var len;
  98125. var len1;
  98126. var len2;
  98127. var dot1;
  98128. var dot2;
  98129. var dot3;
  98130. // try axis 1
  98131. len = a1x * dx + a1y * dy + a1z * dz;
  98132. right1 = len > 0;
  98133. if (!right1) len = -len;
  98134. len1 = w1;
  98135. dot1 = a1x * a4x + a1y * a4y + a1z * a4z;
  98136. dot2 = a1x * a5x + a1y * a5y + a1z * a5z;
  98137. dot3 = a1x * a6x + a1y * a6y + a1z * a6z;
  98138. if (dot1 < 0) dot1 = -dot1;
  98139. if (dot2 < 0) dot2 = -dot2;
  98140. if (dot3 < 0) dot3 = -dot3;
  98141. len2 = dot1 * w2 + dot2 * h2 + dot3 * d2;
  98142. overlap1 = len - len1 - len2;
  98143. if (overlap1 > 0) return;
  98144. // try axis 2
  98145. len = a2x * dx + a2y * dy + a2z * dz;
  98146. right2 = len > 0;
  98147. if (!right2) len = -len;
  98148. len1 = h1;
  98149. dot1 = a2x * a4x + a2y * a4y + a2z * a4z;
  98150. dot2 = a2x * a5x + a2y * a5y + a2z * a5z;
  98151. dot3 = a2x * a6x + a2y * a6y + a2z * a6z;
  98152. if (dot1 < 0) dot1 = -dot1;
  98153. if (dot2 < 0) dot2 = -dot2;
  98154. if (dot3 < 0) dot3 = -dot3;
  98155. len2 = dot1 * w2 + dot2 * h2 + dot3 * d2;
  98156. overlap2 = len - len1 - len2;
  98157. if (overlap2 > 0) return;
  98158. // try axis 3
  98159. len = a3x * dx + a3y * dy + a3z * dz;
  98160. right3 = len > 0;
  98161. if (!right3) len = -len;
  98162. len1 = d1;
  98163. dot1 = a3x * a4x + a3y * a4y + a3z * a4z;
  98164. dot2 = a3x * a5x + a3y * a5y + a3z * a5z;
  98165. dot3 = a3x * a6x + a3y * a6y + a3z * a6z;
  98166. if (dot1 < 0) dot1 = -dot1;
  98167. if (dot2 < 0) dot2 = -dot2;
  98168. if (dot3 < 0) dot3 = -dot3;
  98169. len2 = dot1 * w2 + dot2 * h2 + dot3 * d2;
  98170. overlap3 = len - len1 - len2;
  98171. if (overlap3 > 0) return;
  98172. // try axis 4
  98173. len = a4x * dx + a4y * dy + a4z * dz;
  98174. right4 = len > 0;
  98175. if (!right4) len = -len;
  98176. dot1 = a4x * a1x + a4y * a1y + a4z * a1z;
  98177. dot2 = a4x * a2x + a4y * a2y + a4z * a2z;
  98178. dot3 = a4x * a3x + a4y * a3y + a4z * a3z;
  98179. if (dot1 < 0) dot1 = -dot1;
  98180. if (dot2 < 0) dot2 = -dot2;
  98181. if (dot3 < 0) dot3 = -dot3;
  98182. len1 = dot1 * w1 + dot2 * h1 + dot3 * d1;
  98183. len2 = w2;
  98184. overlap4 = (len - len1 - len2) * 1.0;
  98185. if (overlap4 > 0) return;
  98186. // try axis 5
  98187. len = a5x * dx + a5y * dy + a5z * dz;
  98188. right5 = len > 0;
  98189. if (!right5) len = -len;
  98190. dot1 = a5x * a1x + a5y * a1y + a5z * a1z;
  98191. dot2 = a5x * a2x + a5y * a2y + a5z * a2z;
  98192. dot3 = a5x * a3x + a5y * a3y + a5z * a3z;
  98193. if (dot1 < 0) dot1 = -dot1;
  98194. if (dot2 < 0) dot2 = -dot2;
  98195. if (dot3 < 0) dot3 = -dot3;
  98196. len1 = dot1 * w1 + dot2 * h1 + dot3 * d1;
  98197. len2 = h2;
  98198. overlap5 = (len - len1 - len2) * 1.0;
  98199. if (overlap5 > 0) return;
  98200. // try axis 6
  98201. len = a6x * dx + a6y * dy + a6z * dz;
  98202. right6 = len > 0;
  98203. if (!right6) len = -len;
  98204. dot1 = a6x * a1x + a6y * a1y + a6z * a1z;
  98205. dot2 = a6x * a2x + a6y * a2y + a6z * a2z;
  98206. dot3 = a6x * a3x + a6y * a3y + a6z * a3z;
  98207. if (dot1 < 0) dot1 = -dot1;
  98208. if (dot2 < 0) dot2 = -dot2;
  98209. if (dot3 < 0) dot3 = -dot3;
  98210. len1 = dot1 * w1 + dot2 * h1 + dot3 * d1;
  98211. len2 = d2;
  98212. overlap6 = (len - len1 - len2) * 1.0;
  98213. if (overlap6 > 0) return;
  98214. // try axis 7
  98215. len = a7x * a7x + a7y * a7y + a7z * a7z;
  98216. if (len > 1e-5) {
  98217. len = 1 / OIMO.sqrt(len);
  98218. a7x *= len;
  98219. a7y *= len;
  98220. a7z *= len;
  98221. len = a7x * dx + a7y * dy + a7z * dz;
  98222. right7 = len > 0;
  98223. if (!right7) len = -len;
  98224. dot1 = a7x * a2x + a7y * a2y + a7z * a2z;
  98225. dot2 = a7x * a3x + a7y * a3y + a7z * a3z;
  98226. if (dot1 < 0) dot1 = -dot1;
  98227. if (dot2 < 0) dot2 = -dot2;
  98228. len1 = dot1 * h1 + dot2 * d1;
  98229. dot1 = a7x * a5x + a7y * a5y + a7z * a5z;
  98230. dot2 = a7x * a6x + a7y * a6y + a7z * a6z;
  98231. if (dot1 < 0) dot1 = -dot1;
  98232. if (dot2 < 0) dot2 = -dot2;
  98233. len2 = dot1 * h2 + dot2 * d2;
  98234. overlap7 = len - len1 - len2;
  98235. if (overlap7 > 0) return;
  98236. } else {
  98237. right7 = false;
  98238. overlap7 = 0;
  98239. invalid7 = true;
  98240. }
  98241. // try axis 8
  98242. len = a8x * a8x + a8y * a8y + a8z * a8z;
  98243. if (len > 1e-5) {
  98244. len = 1 / OIMO.sqrt(len);
  98245. a8x *= len;
  98246. a8y *= len;
  98247. a8z *= len;
  98248. len = a8x * dx + a8y * dy + a8z * dz;
  98249. right8 = len > 0;
  98250. if (!right8) len = -len;
  98251. dot1 = a8x * a2x + a8y * a2y + a8z * a2z;
  98252. dot2 = a8x * a3x + a8y * a3y + a8z * a3z;
  98253. if (dot1 < 0) dot1 = -dot1;
  98254. if (dot2 < 0) dot2 = -dot2;
  98255. len1 = dot1 * h1 + dot2 * d1;
  98256. dot1 = a8x * a4x + a8y * a4y + a8z * a4z;
  98257. dot2 = a8x * a6x + a8y * a6y + a8z * a6z;
  98258. if (dot1 < 0) dot1 = -dot1;
  98259. if (dot2 < 0) dot2 = -dot2;
  98260. len2 = dot1 * w2 + dot2 * d2;
  98261. overlap8 = len - len1 - len2;
  98262. if (overlap8 > 0) return;
  98263. } else {
  98264. right8 = false;
  98265. overlap8 = 0;
  98266. invalid8 = true;
  98267. }
  98268. // try axis 9
  98269. len = a9x * a9x + a9y * a9y + a9z * a9z;
  98270. if (len > 1e-5) {
  98271. len = 1 / OIMO.sqrt(len);
  98272. a9x *= len;
  98273. a9y *= len;
  98274. a9z *= len;
  98275. len = a9x * dx + a9y * dy + a9z * dz;
  98276. right9 = len > 0;
  98277. if (!right9) len = -len;
  98278. dot1 = a9x * a2x + a9y * a2y + a9z * a2z;
  98279. dot2 = a9x * a3x + a9y * a3y + a9z * a3z;
  98280. if (dot1 < 0) dot1 = -dot1;
  98281. if (dot2 < 0) dot2 = -dot2;
  98282. len1 = dot1 * h1 + dot2 * d1;
  98283. dot1 = a9x * a4x + a9y * a4y + a9z * a4z;
  98284. dot2 = a9x * a5x + a9y * a5y + a9z * a5z;
  98285. if (dot1 < 0) dot1 = -dot1;
  98286. if (dot2 < 0) dot2 = -dot2;
  98287. len2 = dot1 * w2 + dot2 * h2;
  98288. overlap9 = len - len1 - len2;
  98289. if (overlap9 > 0) return;
  98290. } else {
  98291. right9 = false;
  98292. overlap9 = 0;
  98293. invalid9 = true;
  98294. }
  98295. // try axis 10
  98296. len = aax * aax + aay * aay + aaz * aaz;
  98297. if (len > 1e-5) {
  98298. len = 1 / OIMO.sqrt(len);
  98299. aax *= len;
  98300. aay *= len;
  98301. aaz *= len;
  98302. len = aax * dx + aay * dy + aaz * dz;
  98303. righta = len > 0;
  98304. if (!righta) len = -len;
  98305. dot1 = aax * a1x + aay * a1y + aaz * a1z;
  98306. dot2 = aax * a3x + aay * a3y + aaz * a3z;
  98307. if (dot1 < 0) dot1 = -dot1;
  98308. if (dot2 < 0) dot2 = -dot2;
  98309. len1 = dot1 * w1 + dot2 * d1;
  98310. dot1 = aax * a5x + aay * a5y + aaz * a5z;
  98311. dot2 = aax * a6x + aay * a6y + aaz * a6z;
  98312. if (dot1 < 0) dot1 = -dot1;
  98313. if (dot2 < 0) dot2 = -dot2;
  98314. len2 = dot1 * h2 + dot2 * d2;
  98315. overlapa = len - len1 - len2;
  98316. if (overlapa > 0) return;
  98317. } else {
  98318. righta = false;
  98319. overlapa = 0;
  98320. invalida = true;
  98321. }
  98322. // try axis 11
  98323. len = abx * abx + aby * aby + abz * abz;
  98324. if (len > 1e-5) {
  98325. len = 1 / OIMO.sqrt(len);
  98326. abx *= len;
  98327. aby *= len;
  98328. abz *= len;
  98329. len = abx * dx + aby * dy + abz * dz;
  98330. rightb = len > 0;
  98331. if (!rightb) len = -len;
  98332. dot1 = abx * a1x + aby * a1y + abz * a1z;
  98333. dot2 = abx * a3x + aby * a3y + abz * a3z;
  98334. if (dot1 < 0) dot1 = -dot1;
  98335. if (dot2 < 0) dot2 = -dot2;
  98336. len1 = dot1 * w1 + dot2 * d1;
  98337. dot1 = abx * a4x + aby * a4y + abz * a4z;
  98338. dot2 = abx * a6x + aby * a6y + abz * a6z;
  98339. if (dot1 < 0) dot1 = -dot1;
  98340. if (dot2 < 0) dot2 = -dot2;
  98341. len2 = dot1 * w2 + dot2 * d2;
  98342. overlapb = len - len1 - len2;
  98343. if (overlapb > 0) return;
  98344. } else {
  98345. rightb = false;
  98346. overlapb = 0;
  98347. invalidb = true;
  98348. }
  98349. // try axis 12
  98350. len = acx * acx + acy * acy + acz * acz;
  98351. if (len > 1e-5) {
  98352. len = 1 / OIMO.sqrt(len);
  98353. acx *= len;
  98354. acy *= len;
  98355. acz *= len;
  98356. len = acx * dx + acy * dy + acz * dz;
  98357. rightc = len > 0;
  98358. if (!rightc) len = -len;
  98359. dot1 = acx * a1x + acy * a1y + acz * a1z;
  98360. dot2 = acx * a3x + acy * a3y + acz * a3z;
  98361. if (dot1 < 0) dot1 = -dot1;
  98362. if (dot2 < 0) dot2 = -dot2;
  98363. len1 = dot1 * w1 + dot2 * d1;
  98364. dot1 = acx * a4x + acy * a4y + acz * a4z;
  98365. dot2 = acx * a5x + acy * a5y + acz * a5z;
  98366. if (dot1 < 0) dot1 = -dot1;
  98367. if (dot2 < 0) dot2 = -dot2;
  98368. len2 = dot1 * w2 + dot2 * h2;
  98369. overlapc = len - len1 - len2;
  98370. if (overlapc > 0) return;
  98371. } else {
  98372. rightc = false;
  98373. overlapc = 0;
  98374. invalidc = true;
  98375. }
  98376. // try axis 13
  98377. len = adx * adx + ady * ady + adz * adz;
  98378. if (len > 1e-5) {
  98379. len = 1 / OIMO.sqrt(len);
  98380. adx *= len;
  98381. ady *= len;
  98382. adz *= len;
  98383. len = adx * dx + ady * dy + adz * dz;
  98384. rightd = len > 0;
  98385. if (!rightd) len = -len;
  98386. dot1 = adx * a1x + ady * a1y + adz * a1z;
  98387. dot2 = adx * a2x + ady * a2y + adz * a2z;
  98388. if (dot1 < 0) dot1 = -dot1;
  98389. if (dot2 < 0) dot2 = -dot2;
  98390. len1 = dot1 * w1 + dot2 * h1;
  98391. dot1 = adx * a5x + ady * a5y + adz * a5z;
  98392. dot2 = adx * a6x + ady * a6y + adz * a6z;
  98393. if (dot1 < 0) dot1 = -dot1;
  98394. if (dot2 < 0) dot2 = -dot2;
  98395. len2 = dot1 * h2 + dot2 * d2;
  98396. overlapd = len - len1 - len2;
  98397. if (overlapd > 0) return;
  98398. } else {
  98399. rightd = false;
  98400. overlapd = 0;
  98401. invalidd = true;
  98402. }
  98403. // try axis 14
  98404. len = aex * aex + aey * aey + aez * aez;
  98405. if (len > 1e-5) {
  98406. len = 1 / OIMO.sqrt(len);
  98407. aex *= len;
  98408. aey *= len;
  98409. aez *= len;
  98410. len = aex * dx + aey * dy + aez * dz;
  98411. righte = len > 0;
  98412. if (!righte) len = -len;
  98413. dot1 = aex * a1x + aey * a1y + aez * a1z;
  98414. dot2 = aex * a2x + aey * a2y + aez * a2z;
  98415. if (dot1 < 0) dot1 = -dot1;
  98416. if (dot2 < 0) dot2 = -dot2;
  98417. len1 = dot1 * w1 + dot2 * h1;
  98418. dot1 = aex * a4x + aey * a4y + aez * a4z;
  98419. dot2 = aex * a6x + aey * a6y + aez * a6z;
  98420. if (dot1 < 0) dot1 = -dot1;
  98421. if (dot2 < 0) dot2 = -dot2;
  98422. len2 = dot1 * w2 + dot2 * d2;
  98423. overlape = len - len1 - len2;
  98424. if (overlape > 0) return;
  98425. } else {
  98426. righte = false;
  98427. overlape = 0;
  98428. invalide = true;
  98429. }
  98430. // try axis 15
  98431. len = afx * afx + afy * afy + afz * afz;
  98432. if (len > 1e-5) {
  98433. len = 1 / OIMO.sqrt(len);
  98434. afx *= len;
  98435. afy *= len;
  98436. afz *= len;
  98437. len = afx * dx + afy * dy + afz * dz;
  98438. rightf = len > 0;
  98439. if (!rightf) len = -len;
  98440. dot1 = afx * a1x + afy * a1y + afz * a1z;
  98441. dot2 = afx * a2x + afy * a2y + afz * a2z;
  98442. if (dot1 < 0) dot1 = -dot1;
  98443. if (dot2 < 0) dot2 = -dot2;
  98444. len1 = dot1 * w1 + dot2 * h1;
  98445. dot1 = afx * a4x + afy * a4y + afz * a4z;
  98446. dot2 = afx * a5x + afy * a5y + afz * a5z;
  98447. if (dot1 < 0) dot1 = -dot1;
  98448. if (dot2 < 0) dot2 = -dot2;
  98449. len2 = dot1 * w2 + dot2 * h2;
  98450. overlapf = len - len1 - len2;
  98451. if (overlapf > 0) return;
  98452. } else {
  98453. rightf = false;
  98454. overlapf = 0;
  98455. invalidf = true;
  98456. }
  98457. // boxes are overlapping
  98458. var depth = overlap1;
  98459. var depth2 = overlap1;
  98460. var minIndex = 0;
  98461. var right = right1;
  98462. if (overlap2 > depth2) {
  98463. depth = overlap2;
  98464. depth2 = overlap2;
  98465. minIndex = 1;
  98466. right = right2;
  98467. }
  98468. if (overlap3 > depth2) {
  98469. depth = overlap3;
  98470. depth2 = overlap3;
  98471. minIndex = 2;
  98472. right = right3;
  98473. }
  98474. if (overlap4 > depth2) {
  98475. depth = overlap4;
  98476. depth2 = overlap4;
  98477. minIndex = 3;
  98478. right = right4;
  98479. }
  98480. if (overlap5 > depth2) {
  98481. depth = overlap5;
  98482. depth2 = overlap5;
  98483. minIndex = 4;
  98484. right = right5;
  98485. }
  98486. if (overlap6 > depth2) {
  98487. depth = overlap6;
  98488. depth2 = overlap6;
  98489. minIndex = 5;
  98490. right = right6;
  98491. }
  98492. if (overlap7 - 0.01 > depth2 && !invalid7) {
  98493. depth = overlap7;
  98494. depth2 = overlap7 - 0.01;
  98495. minIndex = 6;
  98496. right = right7;
  98497. }
  98498. if (overlap8 - 0.01 > depth2 && !invalid8) {
  98499. depth = overlap8;
  98500. depth2 = overlap8 - 0.01;
  98501. minIndex = 7;
  98502. right = right8;
  98503. }
  98504. if (overlap9 - 0.01 > depth2 && !invalid9) {
  98505. depth = overlap9;
  98506. depth2 = overlap9 - 0.01;
  98507. minIndex = 8;
  98508. right = right9;
  98509. }
  98510. if (overlapa - 0.01 > depth2 && !invalida) {
  98511. depth = overlapa;
  98512. depth2 = overlapa - 0.01;
  98513. minIndex = 9;
  98514. right = righta;
  98515. }
  98516. if (overlapb - 0.01 > depth2 && !invalidb) {
  98517. depth = overlapb;
  98518. depth2 = overlapb - 0.01;
  98519. minIndex = 10;
  98520. right = rightb;
  98521. }
  98522. if (overlapc - 0.01 > depth2 && !invalidc) {
  98523. depth = overlapc;
  98524. depth2 = overlapc - 0.01;
  98525. minIndex = 11;
  98526. right = rightc;
  98527. }
  98528. if (overlapd - 0.01 > depth2 && !invalidd) {
  98529. depth = overlapd;
  98530. depth2 = overlapd - 0.01;
  98531. minIndex = 12;
  98532. right = rightd;
  98533. }
  98534. if (overlape - 0.01 > depth2 && !invalide) {
  98535. depth = overlape;
  98536. depth2 = overlape - 0.01;
  98537. minIndex = 13;
  98538. right = righte;
  98539. }
  98540. if (overlapf - 0.01 > depth2 && !invalidf) {
  98541. depth = overlapf;
  98542. minIndex = 14;
  98543. right = rightf;
  98544. }
  98545. // normal
  98546. var nx = 0;
  98547. var ny = 0;
  98548. var nz = 0;
  98549. // edge line or face side normal
  98550. var n1x = 0;
  98551. var n1y = 0;
  98552. var n1z = 0;
  98553. var n2x = 0;
  98554. var n2y = 0;
  98555. var n2z = 0;
  98556. // center of current face
  98557. var cx = 0;
  98558. var cy = 0;
  98559. var cz = 0;
  98560. // face side
  98561. var s1x = 0;
  98562. var s1y = 0;
  98563. var s1z = 0;
  98564. var s2x = 0;
  98565. var s2y = 0;
  98566. var s2z = 0;
  98567. // swap b1 b2
  98568. var swap = false;
  98569. //_______________________________________
  98570. if (minIndex == 0) {// b1.x * b2
  98571. if (right) {
  98572. cx = p1x + d1x; cy = p1y + d1y; cz = p1z + d1z;
  98573. nx = a1x; ny = a1y; nz = a1z;
  98574. } else {
  98575. cx = p1x - d1x; cy = p1y - d1y; cz = p1z - d1z;
  98576. nx = -a1x; ny = -a1y; nz = -a1z;
  98577. }
  98578. s1x = d2x; s1y = d2y; s1z = d2z;
  98579. n1x = -a2x; n1y = -a2y; n1z = -a2z;
  98580. s2x = d3x; s2y = d3y; s2z = d3z;
  98581. n2x = -a3x; n2y = -a3y; n2z = -a3z;
  98582. }
  98583. else if (minIndex == 1) {// b1.y * b2
  98584. if (right) {
  98585. cx = p1x + d2x; cy = p1y + d2y; cz = p1z + d2z;
  98586. nx = a2x; ny = a2y; nz = a2z;
  98587. } else {
  98588. cx = p1x - d2x; cy = p1y - d2y; cz = p1z - d2z;
  98589. nx = -a2x; ny = -a2y; nz = -a2z;
  98590. }
  98591. s1x = d1x; s1y = d1y; s1z = d1z;
  98592. n1x = -a1x; n1y = -a1y; n1z = -a1z;
  98593. s2x = d3x; s2y = d3y; s2z = d3z;
  98594. n2x = -a3x; n2y = -a3y; n2z = -a3z;
  98595. }
  98596. else if (minIndex == 2) {// b1.z * b2
  98597. if (right) {
  98598. cx = p1x + d3x; cy = p1y + d3y; cz = p1z + d3z;
  98599. nx = a3x; ny = a3y; nz = a3z;
  98600. } else {
  98601. cx = p1x - d3x; cy = p1y - d3y; cz = p1z - d3z;
  98602. nx = -a3x; ny = -a3y; nz = -a3z;
  98603. }
  98604. s1x = d1x; s1y = d1y; s1z = d1z;
  98605. n1x = -a1x; n1y = -a1y; n1z = -a1z;
  98606. s2x = d2x; s2y = d2y; s2z = d2z;
  98607. n2x = -a2x; n2y = -a2y; n2z = -a2z;
  98608. }
  98609. else if (minIndex == 3) {// b2.x * b1
  98610. swap = true;
  98611. if (!right) {
  98612. cx = p2x + d4x; cy = p2y + d4y; cz = p2z + d4z;
  98613. nx = a4x; ny = a4y; nz = a4z;
  98614. } else {
  98615. cx = p2x - d4x; cy = p2y - d4y; cz = p2z - d4z;
  98616. nx = -a4x; ny = -a4y; nz = -a4z;
  98617. }
  98618. s1x = d5x; s1y = d5y; s1z = d5z;
  98619. n1x = -a5x; n1y = -a5y; n1z = -a5z;
  98620. s2x = d6x; s2y = d6y; s2z = d6z;
  98621. n2x = -a6x; n2y = -a6y; n2z = -a6z;
  98622. }
  98623. else if (minIndex == 4) {// b2.y * b1
  98624. swap = true;
  98625. if (!right) {
  98626. cx = p2x + d5x; cy = p2y + d5y; cz = p2z + d5z;
  98627. nx = a5x; ny = a5y; nz = a5z;
  98628. } else {
  98629. cx = p2x - d5x; cy = p2y - d5y; cz = p2z - d5z;
  98630. nx = -a5x; ny = -a5y; nz = -a5z;
  98631. }
  98632. s1x = d4x; s1y = d4y; s1z = d4z;
  98633. n1x = -a4x; n1y = -a4y; n1z = -a4z;
  98634. s2x = d6x; s2y = d6y; s2z = d6z;
  98635. n2x = -a6x; n2y = -a6y; n2z = -a6z;
  98636. }
  98637. else if (minIndex == 5) {// b2.z * b1
  98638. swap = true;
  98639. if (!right) {
  98640. cx = p2x + d6x; cy = p2y + d6y; cz = p2z + d6z;
  98641. nx = a6x; ny = a6y; nz = a6z;
  98642. } else {
  98643. cx = p2x - d6x; cy = p2y - d6y; cz = p2z - d6z;
  98644. nx = -a6x; ny = -a6y; nz = -a6z;
  98645. }
  98646. s1x = d4x; s1y = d4y; s1z = d4z;
  98647. n1x = -a4x; n1y = -a4y; n1z = -a4z;
  98648. s2x = d5x; s2y = d5y; s2z = d5z;
  98649. n2x = -a5x; n2y = -a5y; n2z = -a5z;
  98650. }
  98651. else if (minIndex == 6) {// b1.x * b2.x
  98652. nx = a7x; ny = a7y; nz = a7z;
  98653. n1x = a1x; n1y = a1y; n1z = a1z;
  98654. n2x = a4x; n2y = a4y; n2z = a4z;
  98655. }
  98656. else if (minIndex == 7) {// b1.x * b2.y
  98657. nx = a8x; ny = a8y; nz = a8z;
  98658. n1x = a1x; n1y = a1y; n1z = a1z;
  98659. n2x = a5x; n2y = a5y; n2z = a5z;
  98660. }
  98661. else if (minIndex == 8) {// b1.x * b2.z
  98662. nx = a9x; ny = a9y; nz = a9z;
  98663. n1x = a1x; n1y = a1y; n1z = a1z;
  98664. n2x = a6x; n2y = a6y; n2z = a6z;
  98665. }
  98666. else if (minIndex == 9) {// b1.y * b2.x
  98667. nx = aax; ny = aay; nz = aaz;
  98668. n1x = a2x; n1y = a2y; n1z = a2z;
  98669. n2x = a4x; n2y = a4y; n2z = a4z
  98670. }
  98671. else if (minIndex == 10) {// b1.y * b2.y
  98672. nx = abx; ny = aby; nz = abz;
  98673. n1x = a2x; n1y = a2y; n1z = a2z;
  98674. n2x = a5x; n2y = a5y; n2z = a5z;
  98675. }
  98676. else if (minIndex == 11) {// b1.y * b2.z
  98677. nx = acx; ny = acy; nz = acz;
  98678. n1x = a2x; n1y = a2y; n1z = a2z;
  98679. n2x = a6x; n2y = a6y; n2z = a6z;
  98680. }
  98681. else if (minIndex == 12) {// b1.z * b2.x
  98682. nx = adx; ny = ady; nz = adz;
  98683. n1x = a3x; n1y = a3y; n1z = a3z;
  98684. n2x = a4x; n2y = a4y; n2z = a4z;
  98685. }
  98686. else if (minIndex == 13) {// b1.z * b2.y
  98687. nx = aex; ny = aey; nz = aez;
  98688. n1x = a3x; n1y = a3y; n1z = a3z;
  98689. n2x = a5x; n2y = a5y; n2z = a5z;
  98690. }
  98691. else if (minIndex == 14) {// b1.z * b2.z
  98692. nx = afx; ny = afy; nz = afz;
  98693. n1x = a3x; n1y = a3y; n1z = a3z;
  98694. n2x = a6x; n2y = a6y; n2z = a6z;
  98695. }
  98696. //__________________________________________
  98697. var v;
  98698. if (minIndex > 5) {
  98699. if (!right) {
  98700. nx = -nx; ny = -ny; nz = -nz;
  98701. }
  98702. var distance;
  98703. var maxDistance;
  98704. var vx;
  98705. var vy;
  98706. var vz;
  98707. var v1x;
  98708. var v1y;
  98709. var v1z;
  98710. var v2x;
  98711. var v2y;
  98712. var v2z;
  98713. //vertex1;
  98714. v1x = V1[0]; v1y = V1[1]; v1z = V1[2];
  98715. maxDistance = nx * v1x + ny * v1y + nz * v1z;
  98716. //vertex2;
  98717. vx = V1[3]; vy = V1[4]; vz = V1[5];
  98718. distance = nx * vx + ny * vy + nz * vz;
  98719. if (distance > maxDistance) {
  98720. maxDistance = distance;
  98721. v1x = vx; v1y = vy; v1z = vz;
  98722. }
  98723. //vertex3;
  98724. vx = V1[6]; vy = V1[7]; vz = V1[8];
  98725. distance = nx * vx + ny * vy + nz * vz;
  98726. if (distance > maxDistance) {
  98727. maxDistance = distance;
  98728. v1x = vx; v1y = vy; v1z = vz;
  98729. }
  98730. //vertex4;
  98731. vx = V1[9]; vy = V1[10]; vz = V1[11];
  98732. distance = nx * vx + ny * vy + nz * vz;
  98733. if (distance > maxDistance) {
  98734. maxDistance = distance;
  98735. v1x = vx; v1y = vy; v1z = vz;
  98736. }
  98737. //vertex5;
  98738. vx = V1[12]; vy = V1[13]; vz = V1[14];
  98739. distance = nx * vx + ny * vy + nz * vz;
  98740. if (distance > maxDistance) {
  98741. maxDistance = distance;
  98742. v1x = vx; v1y = vy; v1z = vz;
  98743. }
  98744. //vertex6;
  98745. vx = V1[15]; vy = V1[16]; vz = V1[17];
  98746. distance = nx * vx + ny * vy + nz * vz;
  98747. if (distance > maxDistance) {
  98748. maxDistance = distance;
  98749. v1x = vx; v1y = vy; v1z = vz;
  98750. }
  98751. //vertex7;
  98752. vx = V1[18]; vy = V1[19]; vz = V1[20];
  98753. distance = nx * vx + ny * vy + nz * vz;
  98754. if (distance > maxDistance) {
  98755. maxDistance = distance;
  98756. v1x = vx; v1y = vy; v1z = vz;
  98757. }
  98758. //vertex8;
  98759. vx = V1[21]; vy = V1[22]; vz = V1[23];
  98760. distance = nx * vx + ny * vy + nz * vz;
  98761. if (distance > maxDistance) {
  98762. maxDistance = distance;
  98763. v1x = vx; v1y = vy; v1z = vz;
  98764. }
  98765. //vertex1;
  98766. v2x = V2[0]; v2y = V2[1]; v2z = V2[2];
  98767. maxDistance = nx * v2x + ny * v2y + nz * v2z;
  98768. //vertex2;
  98769. vx = V2[3]; vy = V2[4]; vz = V2[5];
  98770. distance = nx * vx + ny * vy + nz * vz;
  98771. if (distance < maxDistance) {
  98772. maxDistance = distance;
  98773. v2x = vx; v2y = vy; v2z = vz;
  98774. }
  98775. //vertex3;
  98776. vx = V2[6]; vy = V2[7]; vz = V2[8];
  98777. distance = nx * vx + ny * vy + nz * vz;
  98778. if (distance < maxDistance) {
  98779. maxDistance = distance;
  98780. v2x = vx; v2y = vy; v2z = vz;
  98781. }
  98782. //vertex4;
  98783. vx = V2[9]; vy = V2[10]; vz = V2[11];
  98784. distance = nx * vx + ny * vy + nz * vz;
  98785. if (distance < maxDistance) {
  98786. maxDistance = distance;
  98787. v2x = vx; v2y = vy; v2z = vz;
  98788. }
  98789. //vertex5;
  98790. vx = V2[12]; vy = V2[13]; vz = V2[14];
  98791. distance = nx * vx + ny * vy + nz * vz;
  98792. if (distance < maxDistance) {
  98793. maxDistance = distance;
  98794. v2x = vx; v2y = vy; v2z = vz;
  98795. }
  98796. //vertex6;
  98797. vx = V2[15]; vy = V2[16]; vz = V2[17];
  98798. distance = nx * vx + ny * vy + nz * vz;
  98799. if (distance < maxDistance) {
  98800. maxDistance = distance;
  98801. v2x = vx; v2y = vy; v2z = vz;
  98802. }
  98803. //vertex7;
  98804. vx = V2[18]; vy = V2[19]; vz = V2[20];
  98805. distance = nx * vx + ny * vy + nz * vz;
  98806. if (distance < maxDistance) {
  98807. maxDistance = distance;
  98808. v2x = vx; v2y = vy; v2z = vz;
  98809. }
  98810. //vertex8;
  98811. vx = V2[21]; vy = V2[22]; vz = V2[23];
  98812. distance = nx * vx + ny * vy + nz * vz;
  98813. if (distance < maxDistance) {
  98814. maxDistance = distance;
  98815. v2x = vx; v2y = vy; v2z = vz;
  98816. }
  98817. vx = v2x - v1x; vy = v2y - v1y; vz = v2z - v1z;
  98818. dot1 = n1x * n2x + n1y * n2y + n1z * n2z;
  98819. var t = (vx * (n1x - n2x * dot1) + vy * (n1y - n2y * dot1) + vz * (n1z - n2z * dot1)) / (1 - dot1 * dot1);
  98820. 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);
  98821. return;
  98822. }
  98823. // now detect face-face collision...
  98824. // target quad
  98825. var q1x;
  98826. var q1y;
  98827. var q1z;
  98828. var q2x;
  98829. var q2y;
  98830. var q2z;
  98831. var q3x;
  98832. var q3y;
  98833. var q3z;
  98834. var q4x;
  98835. var q4y;
  98836. var q4z;
  98837. // search support face and vertex
  98838. var minDot = 1;
  98839. var dot = 0;
  98840. var minDotIndex = 0;
  98841. if (swap) {
  98842. dot = a1x * nx + a1y * ny + a1z * nz;
  98843. if (dot < minDot) {
  98844. minDot = dot;
  98845. minDotIndex = 0;
  98846. }
  98847. if (-dot < minDot) {
  98848. minDot = -dot;
  98849. minDotIndex = 1;
  98850. }
  98851. dot = a2x * nx + a2y * ny + a2z * nz;
  98852. if (dot < minDot) {
  98853. minDot = dot;
  98854. minDotIndex = 2;
  98855. }
  98856. if (-dot < minDot) {
  98857. minDot = -dot;
  98858. minDotIndex = 3;
  98859. }
  98860. dot = a3x * nx + a3y * ny + a3z * nz;
  98861. if (dot < minDot) {
  98862. minDot = dot;
  98863. minDotIndex = 4;
  98864. }
  98865. if (-dot < minDot) {
  98866. minDot = -dot;
  98867. minDotIndex = 5;
  98868. }
  98869. if (minDotIndex == 0) {// x+ face
  98870. q1x = V1[0]; q1y = V1[1]; q1z = V1[2];//vertex1
  98871. q2x = V1[6]; q2y = V1[7]; q2z = V1[8];//vertex3
  98872. q3x = V1[9]; q3y = V1[10]; q3z = V1[11];//vertex4
  98873. q4x = V1[3]; q4y = V1[4]; q4z = V1[5];//vertex2
  98874. }
  98875. else if (minDotIndex == 1) {// x- face
  98876. q1x = V1[15]; q1y = V1[16]; q1z = V1[17];//vertex6
  98877. q2x = V1[21]; q2y = V1[22]; q2z = V1[23];//vertex8
  98878. q3x = V1[18]; q3y = V1[19]; q3z = V1[20];//vertex7
  98879. q4x = V1[12]; q4y = V1[13]; q4z = V1[14];//vertex5
  98880. }
  98881. else if (minDotIndex == 2) {// y+ face
  98882. q1x = V1[12]; q1y = V1[13]; q1z = V1[14];//vertex5
  98883. q2x = V1[0]; q2y = V1[1]; q2z = V1[2];//vertex1
  98884. q3x = V1[3]; q3y = V1[4]; q3z = V1[5];//vertex2
  98885. q4x = V1[15]; q4y = V1[16]; q4z = V1[17];//vertex6
  98886. }
  98887. else if (minDotIndex == 3) {// y- face
  98888. q1x = V1[21]; q1y = V1[22]; q1z = V1[23];//vertex8
  98889. q2x = V1[9]; q2y = V1[10]; q2z = V1[11];//vertex4
  98890. q3x = V1[6]; q3y = V1[7]; q3z = V1[8];//vertex3
  98891. q4x = V1[18]; q4y = V1[19]; q4z = V1[20];//vertex7
  98892. }
  98893. else if (minDotIndex == 4) {// z+ face
  98894. q1x = V1[12]; q1y = V1[13]; q1z = V1[14];//vertex5
  98895. q2x = V1[18]; q2y = V1[19]; q2z = V1[20];//vertex7
  98896. q3x = V1[6]; q3y = V1[7]; q3z = V1[8];//vertex3
  98897. q4x = V1[0]; q4y = V1[1]; q4z = V1[2];//vertex1
  98898. }
  98899. else if (minDotIndex == 5) {// z- face
  98900. q1x = V1[3]; q1y = V1[4]; q1z = V1[5];//vertex2
  98901. q2x = V1[6]; q2y = V1[7]; q2z = V1[8];//vertex4
  98902. q3x = V1[21]; q3y = V1[22]; q3z = V1[23];//vertex8
  98903. q4x = V1[15]; q4y = V1[16]; q4z = V1[17];//vertex6
  98904. }
  98905. } else {
  98906. dot = a4x * nx + a4y * ny + a4z * nz;
  98907. if (dot < minDot) {
  98908. minDot = dot;
  98909. minDotIndex = 0;
  98910. }
  98911. if (-dot < minDot) {
  98912. minDot = -dot;
  98913. minDotIndex = 1;
  98914. }
  98915. dot = a5x * nx + a5y * ny + a5z * nz;
  98916. if (dot < minDot) {
  98917. minDot = dot;
  98918. minDotIndex = 2;
  98919. }
  98920. if (-dot < minDot) {
  98921. minDot = -dot;
  98922. minDotIndex = 3;
  98923. }
  98924. dot = a6x * nx + a6y * ny + a6z * nz;
  98925. if (dot < minDot) {
  98926. minDot = dot;
  98927. minDotIndex = 4;
  98928. }
  98929. if (-dot < minDot) {
  98930. minDot = -dot;
  98931. minDotIndex = 5;
  98932. }
  98933. //______________________________________________________
  98934. if (minDotIndex == 0) {// x+ face
  98935. q1x = V2[0]; q1y = V2[1]; q1z = V2[2];//vertex1
  98936. q2x = V2[6]; q2y = V2[7]; q2z = V2[8];//vertex3
  98937. q3x = V2[9]; q3y = V2[10]; q3z = V2[11];//vertex4
  98938. q4x = V2[3]; q4y = V2[4]; q4z = V2[5];//vertex2
  98939. }
  98940. else if (minDotIndex == 1) {// x- face
  98941. q1x = V2[15]; q1y = V2[16]; q1z = V2[17];//vertex6
  98942. q2x = V2[21]; q2y = V2[22]; q2z = V2[23]; //vertex8
  98943. q3x = V2[18]; q3y = V2[19]; q3z = V2[20];//vertex7
  98944. q4x = V2[12]; q4y = V2[13]; q4z = V2[14];//vertex5
  98945. }
  98946. else if (minDotIndex == 2) {// y+ face
  98947. q1x = V2[12]; q1y = V2[13]; q1z = V2[14];//vertex5
  98948. q2x = V2[0]; q2y = V2[1]; q2z = V2[2];//vertex1
  98949. q3x = V2[3]; q3y = V2[4]; q3z = V2[5];//vertex2
  98950. q4x = V2[15]; q4y = V2[16]; q4z = V2[17];//vertex6
  98951. }
  98952. else if (minDotIndex == 3) {// y- face
  98953. q1x = V2[21]; q1y = V2[22]; q1z = V2[23];//vertex8
  98954. q2x = V2[9]; q2y = V2[10]; q2z = V2[11];//vertex4
  98955. q3x = V2[6]; q3y = V2[7]; q3z = V2[8];//vertex3
  98956. q4x = V2[18]; q4y = V2[19]; q4z = V2[20];//vertex7
  98957. }
  98958. else if (minDotIndex == 4) {// z+ face
  98959. q1x = V2[12]; q1y = V2[13]; q1z = V2[14];//vertex5
  98960. q2x = V2[18]; q2y = V2[19]; q2z = V2[20];//vertex7
  98961. q3x = V2[6]; q3y = V2[7]; q3z = V2[8];//vertex3
  98962. q4x = V2[0]; q4y = V2[1]; q4z = V2[2];//vertex1
  98963. }
  98964. else if (minDotIndex == 5) {// z- face
  98965. q1x = V2[3]; q1y = V2[4]; q1z = V2[5];//vertex2
  98966. q2x = V2[9]; q2y = V2[10]; q2z = V2[11];//vertex4
  98967. q3x = V2[21]; q3y = V2[22]; q3z = V2[23];//vertex8
  98968. q4x = V2[15]; q4y = V2[16]; q4z = V2[17];//vertex6
  98969. }
  98970. }
  98971. // clip vertices
  98972. var numClipVertices;
  98973. var numAddedClipVertices;
  98974. var index;
  98975. var x1;
  98976. var y1;
  98977. var z1;
  98978. var x2;
  98979. var y2;
  98980. var z2;
  98981. this.clipVertices1[0] = q1x;
  98982. this.clipVertices1[1] = q1y;
  98983. this.clipVertices1[2] = q1z;
  98984. this.clipVertices1[3] = q2x;
  98985. this.clipVertices1[4] = q2y;
  98986. this.clipVertices1[5] = q2z;
  98987. this.clipVertices1[6] = q3x;
  98988. this.clipVertices1[7] = q3y;
  98989. this.clipVertices1[8] = q3z;
  98990. this.clipVertices1[9] = q4x;
  98991. this.clipVertices1[10] = q4y;
  98992. this.clipVertices1[11] = q4z;
  98993. numAddedClipVertices = 0;
  98994. x1 = this.clipVertices1[9];
  98995. y1 = this.clipVertices1[10];
  98996. z1 = this.clipVertices1[11];
  98997. dot1 = (x1 - cx - s1x) * n1x + (y1 - cy - s1y) * n1y + (z1 - cz - s1z) * n1z;
  98998. //var i = 4;
  98999. //while(i--){
  99000. for (var i = 0; i < 4; i++) {
  99001. index = i * 3;
  99002. x2 = this.clipVertices1[index];
  99003. y2 = this.clipVertices1[index + 1];
  99004. z2 = this.clipVertices1[index + 2];
  99005. dot2 = (x2 - cx - s1x) * n1x + (y2 - cy - s1y) * n1y + (z2 - cz - s1z) * n1z;
  99006. if (dot1 > 0) {
  99007. if (dot2 > 0) {
  99008. index = numAddedClipVertices * 3;
  99009. numAddedClipVertices++;
  99010. this.clipVertices2[index] = x2;
  99011. this.clipVertices2[index + 1] = y2;
  99012. this.clipVertices2[index + 2] = z2;
  99013. } else {
  99014. index = numAddedClipVertices * 3;
  99015. numAddedClipVertices++;
  99016. t = dot1 / (dot1 - dot2);
  99017. this.clipVertices2[index] = x1 + (x2 - x1) * t;
  99018. this.clipVertices2[index + 1] = y1 + (y2 - y1) * t;
  99019. this.clipVertices2[index + 2] = z1 + (z2 - z1) * t;
  99020. }
  99021. } else {
  99022. if (dot2 > 0) {
  99023. index = numAddedClipVertices * 3;
  99024. numAddedClipVertices++;
  99025. t = dot1 / (dot1 - dot2);
  99026. this.clipVertices2[index] = x1 + (x2 - x1) * t;
  99027. this.clipVertices2[index + 1] = y1 + (y2 - y1) * t;
  99028. this.clipVertices2[index + 2] = z1 + (z2 - z1) * t;
  99029. index = numAddedClipVertices * 3;
  99030. numAddedClipVertices++;
  99031. this.clipVertices2[index] = x2;
  99032. this.clipVertices2[index + 1] = y2;
  99033. this.clipVertices2[index + 2] = z2;
  99034. }
  99035. }
  99036. x1 = x2;
  99037. y1 = y2;
  99038. z1 = z2;
  99039. dot1 = dot2;
  99040. }
  99041. numClipVertices = numAddedClipVertices;
  99042. if (numClipVertices == 0) return;
  99043. numAddedClipVertices = 0;
  99044. index = (numClipVertices - 1) * 3;
  99045. x1 = this.clipVertices2[index];
  99046. y1 = this.clipVertices2[index + 1];
  99047. z1 = this.clipVertices2[index + 2];
  99048. dot1 = (x1 - cx - s2x) * n2x + (y1 - cy - s2y) * n2y + (z1 - cz - s2z) * n2z;
  99049. //i = numClipVertices;
  99050. //while(i--){
  99051. for (i = 0; i < numClipVertices; i++) {
  99052. index = i * 3;
  99053. x2 = this.clipVertices2[index];
  99054. y2 = this.clipVertices2[index + 1];
  99055. z2 = this.clipVertices2[index + 2];
  99056. dot2 = (x2 - cx - s2x) * n2x + (y2 - cy - s2y) * n2y + (z2 - cz - s2z) * n2z;
  99057. if (dot1 > 0) {
  99058. if (dot2 > 0) {
  99059. index = numAddedClipVertices * 3;
  99060. numAddedClipVertices++;
  99061. this.clipVertices1[index] = x2;
  99062. this.clipVertices1[index + 1] = y2;
  99063. this.clipVertices1[index + 2] = z2;
  99064. } else {
  99065. index = numAddedClipVertices * 3;
  99066. numAddedClipVertices++;
  99067. t = dot1 / (dot1 - dot2);
  99068. this.clipVertices1[index] = x1 + (x2 - x1) * t;
  99069. this.clipVertices1[index + 1] = y1 + (y2 - y1) * t;
  99070. this.clipVertices1[index + 2] = z1 + (z2 - z1) * t;
  99071. }
  99072. } else {
  99073. if (dot2 > 0) {
  99074. index = numAddedClipVertices * 3;
  99075. numAddedClipVertices++;
  99076. t = dot1 / (dot1 - dot2);
  99077. this.clipVertices1[index] = x1 + (x2 - x1) * t;
  99078. this.clipVertices1[index + 1] = y1 + (y2 - y1) * t;
  99079. this.clipVertices1[index + 2] = z1 + (z2 - z1) * t;
  99080. index = numAddedClipVertices * 3;
  99081. numAddedClipVertices++;
  99082. this.clipVertices1[index] = x2;
  99083. this.clipVertices1[index + 1] = y2;
  99084. this.clipVertices1[index + 2] = z2;
  99085. }
  99086. }
  99087. x1 = x2;
  99088. y1 = y2;
  99089. z1 = z2;
  99090. dot1 = dot2;
  99091. }
  99092. numClipVertices = numAddedClipVertices;
  99093. if (numClipVertices == 0) return;
  99094. numAddedClipVertices = 0;
  99095. index = (numClipVertices - 1) * 3;
  99096. x1 = this.clipVertices1[index];
  99097. y1 = this.clipVertices1[index + 1];
  99098. z1 = this.clipVertices1[index + 2];
  99099. dot1 = (x1 - cx + s1x) * -n1x + (y1 - cy + s1y) * -n1y + (z1 - cz + s1z) * -n1z;
  99100. //i = numClipVertices;
  99101. //while(i--){
  99102. for (i = 0; i < numClipVertices; i++) {
  99103. index = i * 3;
  99104. x2 = this.clipVertices1[index];
  99105. y2 = this.clipVertices1[index + 1];
  99106. z2 = this.clipVertices1[index + 2];
  99107. dot2 = (x2 - cx + s1x) * -n1x + (y2 - cy + s1y) * -n1y + (z2 - cz + s1z) * -n1z;
  99108. if (dot1 > 0) {
  99109. if (dot2 > 0) {
  99110. index = numAddedClipVertices * 3;
  99111. numAddedClipVertices++;
  99112. this.clipVertices2[index] = x2;
  99113. this.clipVertices2[index + 1] = y2;
  99114. this.clipVertices2[index + 2] = z2;
  99115. } else {
  99116. index = numAddedClipVertices * 3;
  99117. numAddedClipVertices++;
  99118. t = dot1 / (dot1 - dot2);
  99119. this.clipVertices2[index] = x1 + (x2 - x1) * t;
  99120. this.clipVertices2[index + 1] = y1 + (y2 - y1) * t;
  99121. this.clipVertices2[index + 2] = z1 + (z2 - z1) * t;
  99122. }
  99123. } else {
  99124. if (dot2 > 0) {
  99125. index = numAddedClipVertices * 3;
  99126. numAddedClipVertices++;
  99127. t = dot1 / (dot1 - dot2);
  99128. this.clipVertices2[index] = x1 + (x2 - x1) * t;
  99129. this.clipVertices2[index + 1] = y1 + (y2 - y1) * t;
  99130. this.clipVertices2[index + 2] = z1 + (z2 - z1) * t;
  99131. index = numAddedClipVertices * 3;
  99132. numAddedClipVertices++;
  99133. this.clipVertices2[index] = x2;
  99134. this.clipVertices2[index + 1] = y2;
  99135. this.clipVertices2[index + 2] = z2;
  99136. }
  99137. }
  99138. x1 = x2;
  99139. y1 = y2;
  99140. z1 = z2;
  99141. dot1 = dot2;
  99142. }
  99143. numClipVertices = numAddedClipVertices;
  99144. if (numClipVertices == 0) return;
  99145. numAddedClipVertices = 0;
  99146. index = (numClipVertices - 1) * 3;
  99147. x1 = this.clipVertices2[index];
  99148. y1 = this.clipVertices2[index + 1];
  99149. z1 = this.clipVertices2[index + 2];
  99150. dot1 = (x1 - cx + s2x) * -n2x + (y1 - cy + s2y) * -n2y + (z1 - cz + s2z) * -n2z;
  99151. //i = numClipVertices;
  99152. //while(i--){
  99153. for (i = 0; i < numClipVertices; i++) {
  99154. index = i * 3;
  99155. x2 = this.clipVertices2[index];
  99156. y2 = this.clipVertices2[index + 1];
  99157. z2 = this.clipVertices2[index + 2];
  99158. dot2 = (x2 - cx + s2x) * -n2x + (y2 - cy + s2y) * -n2y + (z2 - cz + s2z) * -n2z;
  99159. if (dot1 > 0) {
  99160. if (dot2 > 0) {
  99161. index = numAddedClipVertices * 3;
  99162. numAddedClipVertices++;
  99163. this.clipVertices1[index] = x2;
  99164. this.clipVertices1[index + 1] = y2;
  99165. this.clipVertices1[index + 2] = z2;
  99166. } else {
  99167. index = numAddedClipVertices * 3;
  99168. numAddedClipVertices++;
  99169. t = dot1 / (dot1 - dot2);
  99170. this.clipVertices1[index] = x1 + (x2 - x1) * t;
  99171. this.clipVertices1[index + 1] = y1 + (y2 - y1) * t;
  99172. this.clipVertices1[index + 2] = z1 + (z2 - z1) * t;
  99173. }
  99174. } else {
  99175. if (dot2 > 0) {
  99176. index = numAddedClipVertices * 3;
  99177. numAddedClipVertices++;
  99178. t = dot1 / (dot1 - dot2);
  99179. this.clipVertices1[index] = x1 + (x2 - x1) * t;
  99180. this.clipVertices1[index + 1] = y1 + (y2 - y1) * t;
  99181. this.clipVertices1[index + 2] = z1 + (z2 - z1) * t;
  99182. index = numAddedClipVertices * 3;
  99183. numAddedClipVertices++;
  99184. this.clipVertices1[index] = x2;
  99185. this.clipVertices1[index + 1] = y2;
  99186. this.clipVertices1[index + 2] = z2;
  99187. }
  99188. }
  99189. x1 = x2;
  99190. y1 = y2;
  99191. z1 = z2;
  99192. dot1 = dot2;
  99193. }
  99194. numClipVertices = numAddedClipVertices;
  99195. if (swap) {
  99196. var tb = b1;
  99197. b1 = b2;
  99198. b2 = tb;
  99199. }
  99200. if (numClipVertices == 0) return;
  99201. var flipped = b1 != shape1;
  99202. if (numClipVertices > 4) {
  99203. x1 = (q1x + q2x + q3x + q4x) * 0.25;
  99204. y1 = (q1y + q2y + q3y + q4y) * 0.25;
  99205. z1 = (q1z + q2z + q3z + q4z) * 0.25;
  99206. n1x = q1x - x1;
  99207. n1y = q1y - y1;
  99208. n1z = q1z - z1;
  99209. n2x = q2x - x1;
  99210. n2y = q2y - y1;
  99211. n2z = q2z - z1;
  99212. var index1 = 0;
  99213. var index2 = 0;
  99214. var index3 = 0;
  99215. var index4 = 0;
  99216. var maxDot = -this.INF;
  99217. minDot = this.INF;
  99218. //i = numClipVertices;
  99219. //while(i--){
  99220. for (i = 0; i < numClipVertices; i++) {
  99221. this.used[i] = false;
  99222. index = i * 3;
  99223. x1 = this.clipVertices1[index];
  99224. y1 = this.clipVertices1[index + 1];
  99225. z1 = this.clipVertices1[index + 2];
  99226. dot = x1 * n1x + y1 * n1y + z1 * n1z;
  99227. if (dot < minDot) {
  99228. minDot = dot;
  99229. index1 = i;
  99230. }
  99231. if (dot > maxDot) {
  99232. maxDot = dot;
  99233. index3 = i;
  99234. }
  99235. }
  99236. this.used[index1] = true;
  99237. this.used[index3] = true;
  99238. maxDot = -this.INF;
  99239. minDot = this.INF;
  99240. //i = numClipVertices;
  99241. //while(i--){
  99242. for (i = 0; i < numClipVertices; i++) {
  99243. if (this.used[i]) continue;
  99244. index = i * 3;
  99245. x1 = this.clipVertices1[index];
  99246. y1 = this.clipVertices1[index + 1];
  99247. z1 = this.clipVertices1[index + 2];
  99248. dot = x1 * n2x + y1 * n2y + z1 * n2z;
  99249. if (dot < minDot) {
  99250. minDot = dot;
  99251. index2 = i;
  99252. }
  99253. if (dot > maxDot) {
  99254. maxDot = dot;
  99255. index4 = i;
  99256. }
  99257. }
  99258. index = index1 * 3;
  99259. x1 = this.clipVertices1[index];
  99260. y1 = this.clipVertices1[index + 1];
  99261. z1 = this.clipVertices1[index + 2];
  99262. dot = (x1 - cx) * nx + (y1 - cy) * ny + (z1 - cz) * nz;
  99263. if (dot < 0) manifold.addPoint(x1, y1, z1, nx, ny, nz, dot, flipped);
  99264. index = index2 * 3;
  99265. x1 = this.clipVertices1[index];
  99266. y1 = this.clipVertices1[index + 1];
  99267. z1 = this.clipVertices1[index + 2];
  99268. dot = (x1 - cx) * nx + (y1 - cy) * ny + (z1 - cz) * nz;
  99269. if (dot < 0) manifold.addPoint(x1, y1, z1, nx, ny, nz, dot, flipped);
  99270. index = index3 * 3;
  99271. x1 = this.clipVertices1[index];
  99272. y1 = this.clipVertices1[index + 1];
  99273. z1 = this.clipVertices1[index + 2];
  99274. dot = (x1 - cx) * nx + (y1 - cy) * ny + (z1 - cz) * nz;
  99275. if (dot < 0) manifold.addPoint(x1, y1, z1, nx, ny, nz, dot, flipped);
  99276. index = index4 * 3;
  99277. x1 = this.clipVertices1[index];
  99278. y1 = this.clipVertices1[index + 1];
  99279. z1 = this.clipVertices1[index + 2];
  99280. dot = (x1 - cx) * nx + (y1 - cy) * ny + (z1 - cz) * nz;
  99281. if (dot < 0) manifold.addPoint(x1, y1, z1, nx, ny, nz, dot, flipped);
  99282. } else {
  99283. //i = numClipVertices;
  99284. //while(i--){
  99285. for (i = 0; i < numClipVertices; i++) {
  99286. index = i * 3;
  99287. x1 = this.clipVertices1[index];
  99288. y1 = this.clipVertices1[index + 1];
  99289. z1 = this.clipVertices1[index + 2];
  99290. dot = (x1 - cx) * nx + (y1 - cy) * ny + (z1 - cz) * nz;
  99291. if (dot < 0) manifold.addPoint(x1, y1, z1, nx, ny, nz, dot, flipped);
  99292. }
  99293. }
  99294. };
  99295. /**
  99296. * A collision detector which detects collisions between sphere and box.
  99297. * @author saharan
  99298. */
  99299. OIMO.SphereBoxCollisionDetector = function (flip) {
  99300. OIMO.CollisionDetector.call(this);
  99301. this.flip = flip;
  99302. };
  99303. OIMO.SphereBoxCollisionDetector.prototype = Object.create(OIMO.CollisionDetector.prototype);
  99304. OIMO.SphereBoxCollisionDetector.prototype.constructor = OIMO.SphereBoxCollisionDetector;
  99305. OIMO.SphereBoxCollisionDetector.prototype.detectCollision = function (shape1, shape2, manifold) {
  99306. var s;
  99307. var b;
  99308. if (this.flip) {
  99309. s = (shape2);
  99310. b = (shape1);
  99311. } else {
  99312. s = (shape1);
  99313. b = (shape2);
  99314. }
  99315. var D = b.dimentions;
  99316. var ps = s.position;
  99317. var psx = ps.x;
  99318. var psy = ps.y;
  99319. var psz = ps.z;
  99320. var pb = b.position;
  99321. var pbx = pb.x;
  99322. var pby = pb.y;
  99323. var pbz = pb.z;
  99324. var rad = s.radius;
  99325. var hw = b.halfWidth;
  99326. var hh = b.halfHeight;
  99327. var hd = b.halfDepth;
  99328. var dx = psx - pbx;
  99329. var dy = psy - pby;
  99330. var dz = psz - pbz;
  99331. var sx = D[0] * dx + D[1] * dy + D[2] * dz;
  99332. var sy = D[3] * dx + D[4] * dy + D[5] * dz;
  99333. var sz = D[6] * dx + D[7] * dy + D[8] * dz;
  99334. var cx;
  99335. var cy;
  99336. var cz;
  99337. var len;
  99338. var invLen;
  99339. var overlap = 0;
  99340. if (sx > hw) {
  99341. sx = hw;
  99342. } else if (sx < -hw) {
  99343. sx = -hw;
  99344. } else {
  99345. overlap = 1;
  99346. }
  99347. if (sy > hh) {
  99348. sy = hh;
  99349. } else if (sy < -hh) {
  99350. sy = -hh;
  99351. } else {
  99352. overlap |= 2;
  99353. }
  99354. if (sz > hd) {
  99355. sz = hd;
  99356. } else if (sz < -hd) {
  99357. sz = -hd;
  99358. } else {
  99359. overlap |= 4;
  99360. }
  99361. if (overlap == 7) {
  99362. // center of sphere is in the box
  99363. if (sx < 0) {
  99364. dx = hw + sx;
  99365. } else {
  99366. dx = hw - sx;
  99367. }
  99368. if (sy < 0) {
  99369. dy = hh + sy;
  99370. } else {
  99371. dy = hh - sy;
  99372. }
  99373. if (sz < 0) {
  99374. dz = hd + sz;
  99375. } else {
  99376. dz = hd - sz;
  99377. }
  99378. if (dx < dy) {
  99379. if (dx < dz) {
  99380. len = dx - hw;
  99381. if (sx < 0) {
  99382. sx = -hw;
  99383. dx = D[0];
  99384. dy = D[1];
  99385. dz = D[2];
  99386. } else {
  99387. sx = hw;
  99388. dx = -D[0];
  99389. dy = -D[1];
  99390. dz = -D[2];
  99391. }
  99392. } else {
  99393. len = dz - hd;
  99394. if (sz < 0) {
  99395. sz = -hd;
  99396. dx = D[6];
  99397. dy = D[7];
  99398. dz = D[8];
  99399. } else {
  99400. sz = hd;
  99401. dx = -D[6];
  99402. dy = -D[7];
  99403. dz = -D[8];
  99404. }
  99405. }
  99406. } else {
  99407. if (dy < dz) {
  99408. len = dy - hh;
  99409. if (sy < 0) {
  99410. sy = -hh;
  99411. dx = D[3];
  99412. dy = D[4];
  99413. dz = D[5];
  99414. } else {
  99415. sy = hh;
  99416. dx = -D[3];
  99417. dy = -D[4];
  99418. dz = -D[5];
  99419. }
  99420. } else {
  99421. len = dz - hd;
  99422. if (sz < 0) {
  99423. sz = -hd;
  99424. dx = D[6];
  99425. dy = D[7];
  99426. dz = D[8];
  99427. } else {
  99428. sz = hd;
  99429. dx = -D[6];
  99430. dy = -D[7];
  99431. dz = -D[8];
  99432. }
  99433. }
  99434. }
  99435. cx = pbx + sx * D[0] + sy * D[3] + sz * D[6];
  99436. cy = pby + sx * D[1] + sy * D[4] + sz * D[7];
  99437. cz = pbz + sx * D[2] + sy * D[5] + sz * D[8];
  99438. manifold.addPoint(psx + rad * dx, psy + rad * dy, psz + rad * dz, dx, dy, dz, len - rad, this.flip);
  99439. } else {
  99440. cx = pbx + sx * D[0] + sy * D[3] + sz * D[6];
  99441. cy = pby + sx * D[1] + sy * D[4] + sz * D[7];
  99442. cz = pbz + sx * D[2] + sy * D[5] + sz * D[8];
  99443. dx = cx - ps.x;
  99444. dy = cy - ps.y;
  99445. dz = cz - ps.z;
  99446. len = dx * dx + dy * dy + dz * dz;
  99447. if (len > 0 && len < rad * rad) {
  99448. len = OIMO.sqrt(len);
  99449. invLen = 1 / len;
  99450. dx *= invLen;
  99451. dy *= invLen;
  99452. dz *= invLen;
  99453. manifold.addPoint(psx + rad * dx, psy + rad * dy, psz + rad * dz, dx, dy, dz, len - rad, this.flip);
  99454. }
  99455. }
  99456. };
  99457. /**
  99458. * A collision detector which detects collisions between two spheres.
  99459. * @author saharan
  99460. */
  99461. OIMO.SphereSphereCollisionDetector = function () {
  99462. OIMO.CollisionDetector.call(this);
  99463. };
  99464. OIMO.SphereSphereCollisionDetector.prototype = Object.create(OIMO.CollisionDetector.prototype);
  99465. OIMO.SphereSphereCollisionDetector.prototype.constructor = OIMO.SphereSphereCollisionDetector;
  99466. OIMO.SphereSphereCollisionDetector.prototype.detectCollision = function (shape1, shape2, manifold) {
  99467. var s1 = shape1;
  99468. var s2 = shape2;
  99469. var p1 = s1.position;
  99470. var p2 = s2.position;
  99471. var dx = p2.x - p1.x;
  99472. var dy = p2.y - p1.y;
  99473. var dz = p2.z - p1.z;
  99474. var len = dx * dx + dy * dy + dz * dz;
  99475. var r1 = s1.radius;
  99476. var r2 = s2.radius;
  99477. var rad = r1 + r2;
  99478. if (len > 0 && len < rad * rad) {
  99479. len = OIMO.sqrt(len);
  99480. var invLen = 1 / len;
  99481. dx *= invLen;
  99482. dy *= invLen;
  99483. dz *= invLen;
  99484. manifold.addPoint(p1.x + dx * r1, p1.y + dy * r1, p1.z + dz * r1, dx, dy, dz, len - rad, false);
  99485. }
  99486. };
  99487. OIMO.BoxCylinderCollisionDetector = function (flip) {
  99488. OIMO.CollisionDetector.call(this);
  99489. this.flip = flip;
  99490. };
  99491. OIMO.BoxCylinderCollisionDetector.prototype = Object.create(OIMO.CollisionDetector.prototype);
  99492. OIMO.BoxCylinderCollisionDetector.prototype.constructor = OIMO.BoxCylinderCollisionDetector;
  99493. OIMO.BoxCylinderCollisionDetector.prototype.getSep = function (c1, c2, sep, pos, dep) {
  99494. var t1x;
  99495. var t1y;
  99496. var t1z;
  99497. var t2x;
  99498. var t2y;
  99499. var t2z;
  99500. var sup = new OIMO.Vec3();
  99501. var len;
  99502. var p1x;
  99503. var p1y;
  99504. var p1z;
  99505. var p2x;
  99506. var p2y;
  99507. var p2z;
  99508. var v01x = c1.position.x;
  99509. var v01y = c1.position.y;
  99510. var v01z = c1.position.z;
  99511. var v02x = c2.position.x;
  99512. var v02y = c2.position.y;
  99513. var v02z = c2.position.z;
  99514. var v0x = v02x - v01x;
  99515. var v0y = v02y - v01y;
  99516. var v0z = v02z - v01z;
  99517. if (v0x * v0x + v0y * v0y + v0z * v0z == 0) v0y = 0.001;
  99518. var nx = -v0x;
  99519. var ny = -v0y;
  99520. var nz = -v0z;
  99521. this.supportPointB(c1, -nx, -ny, -nz, sup);
  99522. var v11x = sup.x;
  99523. var v11y = sup.y;
  99524. var v11z = sup.z;
  99525. this.supportPointC(c2, nx, ny, nz, sup);
  99526. var v12x = sup.x;
  99527. var v12y = sup.y;
  99528. var v12z = sup.z;
  99529. var v1x = v12x - v11x;
  99530. var v1y = v12y - v11y;
  99531. var v1z = v12z - v11z;
  99532. if (v1x * nx + v1y * ny + v1z * nz <= 0) {
  99533. return false;
  99534. }
  99535. nx = v1y * v0z - v1z * v0y;
  99536. ny = v1z * v0x - v1x * v0z;
  99537. nz = v1x * v0y - v1y * v0x;
  99538. if (nx * nx + ny * ny + nz * nz == 0) {
  99539. sep.init(v1x - v0x, v1y - v0y, v1z - v0z);
  99540. sep.normalize(sep);
  99541. pos.init((v11x + v12x) * 0.5, (v11y + v12y) * 0.5, (v11z + v12z) * 0.5);
  99542. return true;
  99543. }
  99544. this.supportPointB(c1, -nx, -ny, -nz, sup);
  99545. var v21x = sup.x;
  99546. var v21y = sup.y;
  99547. var v21z = sup.z;
  99548. this.supportPointC(c2, nx, ny, nz, sup);
  99549. var v22x = sup.x;
  99550. var v22y = sup.y;
  99551. var v22z = sup.z;
  99552. var v2x = v22x - v21x;
  99553. var v2y = v22y - v21y;
  99554. var v2z = v22z - v21z;
  99555. if (v2x * nx + v2y * ny + v2z * nz <= 0) {
  99556. return false;
  99557. }
  99558. t1x = v1x - v0x;
  99559. t1y = v1y - v0y;
  99560. t1z = v1z - v0z;
  99561. t2x = v2x - v0x;
  99562. t2y = v2y - v0y;
  99563. t2z = v2z - v0z;
  99564. nx = t1y * t2z - t1z * t2y;
  99565. ny = t1z * t2x - t1x * t2z;
  99566. nz = t1x * t2y - t1y * t2x;
  99567. if (nx * v0x + ny * v0y + nz * v0z > 0) {
  99568. t1x = v1x;
  99569. t1y = v1y;
  99570. t1z = v1z;
  99571. v1x = v2x;
  99572. v1y = v2y;
  99573. v1z = v2z;
  99574. v2x = t1x;
  99575. v2y = t1y;
  99576. v2z = t1z;
  99577. t1x = v11x;
  99578. t1y = v11y;
  99579. t1z = v11z;
  99580. v11x = v21x;
  99581. v11y = v21y;
  99582. v11z = v21z;
  99583. v21x = t1x;
  99584. v21y = t1y;
  99585. v21z = t1z;
  99586. t1x = v12x;
  99587. t1y = v12y;
  99588. t1z = v12z;
  99589. v12x = v22x;
  99590. v12y = v22y;
  99591. v12z = v22z;
  99592. v22x = t1x;
  99593. v22y = t1y;
  99594. v22z = t1z;
  99595. nx = -nx;
  99596. ny = -ny;
  99597. nz = -nz;
  99598. }
  99599. var iterations = 0;
  99600. while (true) {
  99601. if (++iterations > 100) {
  99602. return false;
  99603. }
  99604. this.supportPointB(c1, -nx, -ny, -nz, sup);
  99605. var v31x = sup.x;
  99606. var v31y = sup.y;
  99607. var v31z = sup.z;
  99608. this.supportPointC(c2, nx, ny, nz, sup);
  99609. var v32x = sup.x;
  99610. var v32y = sup.y;
  99611. var v32z = sup.z;
  99612. var v3x = v32x - v31x;
  99613. var v3y = v32y - v31y;
  99614. var v3z = v32z - v31z;
  99615. if (v3x * nx + v3y * ny + v3z * nz <= 0) {
  99616. return false;
  99617. }
  99618. if ((v1y * v3z - v1z * v3y) * v0x + (v1z * v3x - v1x * v3z) * v0y + (v1x * v3y - v1y * v3x) * v0z < 0) {
  99619. v2x = v3x;
  99620. v2y = v3y;
  99621. v2z = v3z;
  99622. v21x = v31x;
  99623. v21y = v31y;
  99624. v21z = v31z;
  99625. v22x = v32x;
  99626. v22y = v32y;
  99627. v22z = v32z;
  99628. t1x = v1x - v0x;
  99629. t1y = v1y - v0y;
  99630. t1z = v1z - v0z;
  99631. t2x = v3x - v0x;
  99632. t2y = v3y - v0y;
  99633. t2z = v3z - v0z;
  99634. nx = t1y * t2z - t1z * t2y;
  99635. ny = t1z * t2x - t1x * t2z;
  99636. nz = t1x * t2y - t1y * t2x;
  99637. continue;
  99638. }
  99639. if ((v3y * v2z - v3z * v2y) * v0x + (v3z * v2x - v3x * v2z) * v0y + (v3x * v2y - v3y * v2x) * v0z < 0) {
  99640. v1x = v3x;
  99641. v1y = v3y;
  99642. v1z = v3z;
  99643. v11x = v31x;
  99644. v11y = v31y;
  99645. v11z = v31z;
  99646. v12x = v32x;
  99647. v12y = v32y;
  99648. v12z = v32z;
  99649. t1x = v3x - v0x;
  99650. t1y = v3y - v0y;
  99651. t1z = v3z - v0z;
  99652. t2x = v2x - v0x;
  99653. t2y = v2y - v0y;
  99654. t2z = v2z - v0z;
  99655. nx = t1y * t2z - t1z * t2y;
  99656. ny = t1z * t2x - t1x * t2z;
  99657. nz = t1x * t2y - t1y * t2x;
  99658. continue;
  99659. }
  99660. var hit = false;
  99661. while (true) {
  99662. t1x = v2x - v1x;
  99663. t1y = v2y - v1y;
  99664. t1z = v2z - v1z;
  99665. t2x = v3x - v1x;
  99666. t2y = v3y - v1y;
  99667. t2z = v3z - v1z;
  99668. nx = t1y * t2z - t1z * t2y;
  99669. ny = t1z * t2x - t1x * t2z;
  99670. nz = t1x * t2y - t1y * t2x;
  99671. len = 1 / OIMO.sqrt(nx * nx + ny * ny + nz * nz);
  99672. nx *= len;
  99673. ny *= len;
  99674. nz *= len;
  99675. if (nx * v1x + ny * v1y + nz * v1z >= 0 && !hit) {
  99676. var b0 = (v1y * v2z - v1z * v2y) * v3x + (v1z * v2x - v1x * v2z) * v3y + (v1x * v2y - v1y * v2x) * v3z;
  99677. var b1 = (v3y * v2z - v3z * v2y) * v0x + (v3z * v2x - v3x * v2z) * v0y + (v3x * v2y - v3y * v2x) * v0z;
  99678. var b2 = (v0y * v1z - v0z * v1y) * v3x + (v0z * v1x - v0x * v1z) * v3y + (v0x * v1y - v0y * v1x) * v3z;
  99679. var b3 = (v2y * v1z - v2z * v1y) * v0x + (v2z * v1x - v2x * v1z) * v0y + (v2x * v1y - v2y * v1x) * v0z;
  99680. var sum = b0 + b1 + b2 + b3;
  99681. if (sum <= 0) {
  99682. b0 = 0;
  99683. b1 = (v2y * v3z - v2z * v3y) * nx + (v2z * v3x - v2x * v3z) * ny + (v2x * v3y - v2y * v3x) * nz;
  99684. b2 = (v3y * v2z - v3z * v2y) * nx + (v3z * v2x - v3x * v2z) * ny + (v3x * v2y - v3y * v2x) * nz;
  99685. b3 = (v1y * v2z - v1z * v2y) * nx + (v1z * v2x - v1x * v2z) * ny + (v1x * v2y - v1y * v2x) * nz;
  99686. sum = b1 + b2 + b3;
  99687. }
  99688. var inv = 1 / sum;
  99689. p1x = (v01x * b0 + v11x * b1 + v21x * b2 + v31x * b3) * inv;
  99690. p1y = (v01y * b0 + v11y * b1 + v21y * b2 + v31y * b3) * inv;
  99691. p1z = (v01z * b0 + v11z * b1 + v21z * b2 + v31z * b3) * inv;
  99692. p2x = (v02x * b0 + v12x * b1 + v22x * b2 + v32x * b3) * inv;
  99693. p2y = (v02y * b0 + v12y * b1 + v22y * b2 + v32y * b3) * inv;
  99694. p2z = (v02z * b0 + v12z * b1 + v22z * b2 + v32z * b3) * inv;
  99695. hit = true;
  99696. }
  99697. this.supportPointB(c1, -nx, -ny, -nz, sup);
  99698. var v41x = sup.x;
  99699. var v41y = sup.y;
  99700. var v41z = sup.z;
  99701. this.supportPointC(c2, nx, ny, nz, sup);
  99702. var v42x = sup.x;
  99703. var v42y = sup.y;
  99704. var v42z = sup.z;
  99705. var v4x = v42x - v41x;
  99706. var v4y = v42y - v41y;
  99707. var v4z = v42z - v41z;
  99708. var separation = -(v4x * nx + v4y * ny + v4z * nz);
  99709. if ((v4x - v3x) * nx + (v4y - v3y) * ny + (v4z - v3z) * nz <= 0.01 || separation >= 0) {
  99710. if (hit) {
  99711. sep.init(-nx, -ny, -nz);
  99712. pos.init((p1x + p2x) * 0.5, (p1y + p2y) * 0.5, (p1z + p2z) * 0.5);
  99713. dep.x = separation;
  99714. return true;
  99715. }
  99716. return false;
  99717. }
  99718. if (
  99719. (v4y * v1z - v4z * v1y) * v0x +
  99720. (v4z * v1x - v4x * v1z) * v0y +
  99721. (v4x * v1y - v4y * v1x) * v0z < 0
  99722. ) {
  99723. if (
  99724. (v4y * v2z - v4z * v2y) * v0x +
  99725. (v4z * v2x - v4x * v2z) * v0y +
  99726. (v4x * v2y - v4y * v2x) * v0z < 0
  99727. ) {
  99728. v1x = v4x;
  99729. v1y = v4y;
  99730. v1z = v4z;
  99731. v11x = v41x;
  99732. v11y = v41y;
  99733. v11z = v41z;
  99734. v12x = v42x;
  99735. v12y = v42y;
  99736. v12z = v42z;
  99737. } else {
  99738. v3x = v4x;
  99739. v3y = v4y;
  99740. v3z = v4z;
  99741. v31x = v41x;
  99742. v31y = v41y;
  99743. v31z = v41z;
  99744. v32x = v42x;
  99745. v32y = v42y;
  99746. v32z = v42z;
  99747. }
  99748. } else {
  99749. if (
  99750. (v4y * v3z - v4z * v3y) * v0x +
  99751. (v4z * v3x - v4x * v3z) * v0y +
  99752. (v4x * v3y - v4y * v3x) * v0z < 0
  99753. ) {
  99754. v2x = v4x;
  99755. v2y = v4y;
  99756. v2z = v4z;
  99757. v21x = v41x;
  99758. v21y = v41y;
  99759. v21z = v41z;
  99760. v22x = v42x;
  99761. v22y = v42y;
  99762. v22z = v42z;
  99763. } else {
  99764. v1x = v4x;
  99765. v1y = v4y;
  99766. v1z = v4z;
  99767. v11x = v41x;
  99768. v11y = v41y;
  99769. v11z = v41z;
  99770. v12x = v42x;
  99771. v12y = v42y;
  99772. v12z = v42z;
  99773. }
  99774. }
  99775. }
  99776. }
  99777. //return false;
  99778. };
  99779. OIMO.BoxCylinderCollisionDetector.prototype.supportPointB = function (c, dx, dy, dz, out) {
  99780. var rot = c.rotation.elements;
  99781. var ldx = rot[0] * dx + rot[3] * dy + rot[6] * dz;
  99782. var ldy = rot[1] * dx + rot[4] * dy + rot[7] * dz;
  99783. var ldz = rot[2] * dx + rot[5] * dy + rot[8] * dz;
  99784. var w = c.halfWidth;
  99785. var h = c.halfHeight;
  99786. var d = c.halfDepth;
  99787. var ox;
  99788. var oy;
  99789. var oz;
  99790. if (ldx < 0) ox = -w;
  99791. else ox = w;
  99792. if (ldy < 0) oy = -h;
  99793. else oy = h;
  99794. if (ldz < 0) oz = -d;
  99795. else oz = d;
  99796. ldx = rot[0] * ox + rot[1] * oy + rot[2] * oz + c.position.x;
  99797. ldy = rot[3] * ox + rot[4] * oy + rot[5] * oz + c.position.y;
  99798. ldz = rot[6] * ox + rot[7] * oy + rot[8] * oz + c.position.z;
  99799. out.init(ldx, ldy, ldz);
  99800. };
  99801. OIMO.BoxCylinderCollisionDetector.prototype.supportPointC = function (c, dx, dy, dz, out) {
  99802. var rot = c.rotation.elements;
  99803. var ldx = rot[0] * dx + rot[3] * dy + rot[6] * dz;
  99804. var ldy = rot[1] * dx + rot[4] * dy + rot[7] * dz;
  99805. var ldz = rot[2] * dx + rot[5] * dy + rot[8] * dz;
  99806. var radx = ldx;
  99807. var radz = ldz;
  99808. var len = radx * radx + radz * radz;
  99809. var rad = c.radius;
  99810. var hh = c.halfHeight;
  99811. var ox;
  99812. var oy;
  99813. var oz;
  99814. if (len == 0) {
  99815. if (ldy < 0) {
  99816. ox = rad;
  99817. oy = -hh;
  99818. oz = 0;
  99819. } else {
  99820. ox = rad;
  99821. oy = hh;
  99822. oz = 0;
  99823. }
  99824. } else {
  99825. len = c.radius / OIMO.sqrt(len);
  99826. if (ldy < 0) {
  99827. ox = radx * len;
  99828. oy = -hh;
  99829. oz = radz * len;
  99830. } else {
  99831. ox = radx * len;
  99832. oy = hh;
  99833. oz = radz * len;
  99834. }
  99835. }
  99836. ldx = rot[0] * ox + rot[1] * oy + rot[2] * oz + c.position.x;
  99837. ldy = rot[3] * ox + rot[4] * oy + rot[5] * oz + c.position.y;
  99838. ldz = rot[6] * ox + rot[7] * oy + rot[8] * oz + c.position.z;
  99839. out.init(ldx, ldy, ldz);
  99840. };
  99841. OIMO.BoxCylinderCollisionDetector.prototype.detectCollision = function (shape1, shape2, manifold) {
  99842. var b;
  99843. var c;
  99844. if (this.flip) {
  99845. b = shape2;
  99846. c = shape1;
  99847. } else {
  99848. b = shape1;
  99849. c = shape2;
  99850. }
  99851. var sep = new OIMO.Vec3();
  99852. var pos = new OIMO.Vec3();
  99853. var dep = new OIMO.Vec3();
  99854. var co;
  99855. if (!this.getSep(b, c, sep, pos, dep)) return;
  99856. var pbx = b.position.x;
  99857. var pby = b.position.y;
  99858. var pbz = b.position.z;
  99859. var pcx = c.position.x;
  99860. var pcy = c.position.y;
  99861. var pcz = c.position.z;
  99862. var bw = b.halfWidth;
  99863. var bh = b.halfHeight;
  99864. var bd = b.halfDepth;
  99865. var ch = c.halfHeight;
  99866. var r = c.radius;
  99867. var D = b.dimentions;
  99868. var nwx = D[0];//b.normalDirectionWidth.x;
  99869. var nwy = D[1];//b.normalDirectionWidth.y;
  99870. var nwz = D[2];//b.normalDirectionWidth.z;
  99871. var nhx = D[3];//b.normalDirectionHeight.x;
  99872. var nhy = D[4];//b.normalDirectionHeight.y;
  99873. var nhz = D[5];//b.normalDirectionHeight.z;
  99874. var ndx = D[6];//b.normalDirectionDepth.x;
  99875. var ndy = D[7];//b.normalDirectionDepth.y;
  99876. var ndz = D[8];//b.normalDirectionDepth.z;
  99877. var dwx = D[9];//b.halfDirectionWidth.x;
  99878. var dwy = D[10];//b.halfDirectionWidth.y;
  99879. var dwz = D[11];//b.halfDirectionWidth.z;
  99880. var dhx = D[12];//b.halfDirectionHeight.x;
  99881. var dhy = D[13];//b.halfDirectionHeight.y;
  99882. var dhz = D[14];//b.halfDirectionHeight.z;
  99883. var ddx = D[15];//b.halfDirectionDepth.x;
  99884. var ddy = D[16];//b.halfDirectionDepth.y;
  99885. var ddz = D[17];//b.halfDirectionDepth.z;
  99886. var ncx = c.normalDirection.x;
  99887. var ncy = c.normalDirection.y;
  99888. var ncz = c.normalDirection.z;
  99889. var dcx = c.halfDirection.x;
  99890. var dcy = c.halfDirection.y;
  99891. var dcz = c.halfDirection.z;
  99892. var nx = sep.x;
  99893. var ny = sep.y;
  99894. var nz = sep.z;
  99895. var dotw = nx * nwx + ny * nwy + nz * nwz;
  99896. var doth = nx * nhx + ny * nhy + nz * nhz;
  99897. var dotd = nx * ndx + ny * ndy + nz * ndz;
  99898. var dotc = nx * ncx + ny * ncy + nz * ncz;
  99899. var right1 = dotw > 0;
  99900. var right2 = doth > 0;
  99901. var right3 = dotd > 0;
  99902. var right4 = dotc > 0;
  99903. if (!right1) dotw = -dotw;
  99904. if (!right2) doth = -doth;
  99905. if (!right3) dotd = -dotd;
  99906. if (!right4) dotc = -dotc;
  99907. var state = 0;
  99908. if (dotc > 0.999) {
  99909. if (dotw > 0.999) {
  99910. if (dotw > dotc) state = 1;
  99911. else state = 4;
  99912. } else if (doth > 0.999) {
  99913. if (doth > dotc) state = 2;
  99914. else state = 4;
  99915. } else if (dotd > 0.999) {
  99916. if (dotd > dotc) state = 3;
  99917. else state = 4;
  99918. } else state = 4;
  99919. } else {
  99920. if (dotw > 0.999) state = 1;
  99921. else if (doth > 0.999) state = 2;
  99922. else if (dotd > 0.999) state = 3;
  99923. }
  99924. var cbx;
  99925. var cby;
  99926. var cbz;
  99927. var ccx;
  99928. var ccy;
  99929. var ccz;
  99930. var r00;
  99931. var r01;
  99932. var r02;
  99933. var r10;
  99934. var r11;
  99935. var r12;
  99936. var r20;
  99937. var r21;
  99938. var r22;
  99939. var px;
  99940. var py;
  99941. var pz;
  99942. var pd;
  99943. var dot;
  99944. var len;
  99945. var tx;
  99946. var ty;
  99947. var tz;
  99948. var td;
  99949. var dx;
  99950. var dy;
  99951. var dz;
  99952. var d1x;
  99953. var d1y;
  99954. var d1z;
  99955. var d2x;
  99956. var d2y;
  99957. var d2z;
  99958. var sx;
  99959. var sy;
  99960. var sz;
  99961. var sd;
  99962. var ex;
  99963. var ey;
  99964. var ez;
  99965. var ed;
  99966. var dot1;
  99967. var dot2;
  99968. var t1;
  99969. var t2;
  99970. var dir1x;
  99971. var dir1y;
  99972. var dir1z;
  99973. var dir2x;
  99974. var dir2y;
  99975. var dir2z;
  99976. var dir1l;
  99977. var dir2l;
  99978. if (state == 0) {
  99979. //manifold.addPoint(pos.x,pos.y,pos.z,nx,ny,nz,dep.x,b,c,0,0,false);
  99980. manifold.addPoint(pos.x, pos.y, pos.z, nx, ny, nz, dep.x, this.flip);
  99981. } else if (state == 4) {
  99982. if (right4) {
  99983. ccx = pcx - dcx;
  99984. ccy = pcy - dcy;
  99985. ccz = pcz - dcz;
  99986. nx = -ncx;
  99987. ny = -ncy;
  99988. nz = -ncz;
  99989. } else {
  99990. ccx = pcx + dcx;
  99991. ccy = pcy + dcy;
  99992. ccz = pcz + dcz;
  99993. nx = ncx;
  99994. ny = ncy;
  99995. nz = ncz;
  99996. }
  99997. var v1x;
  99998. var v1y;
  99999. var v1z;
  100000. var v2x;
  100001. var v2y;
  100002. var v2z;
  100003. var v3x;
  100004. var v3y;
  100005. var v3z;
  100006. var v4x;
  100007. var v4y;
  100008. var v4z;
  100009. dot = 1;
  100010. state = 0;
  100011. dot1 = nwx * nx + nwy * ny + nwz * nz;
  100012. if (dot1 < dot) {
  100013. dot = dot1;
  100014. state = 0;
  100015. }
  100016. if (-dot1 < dot) {
  100017. dot = -dot1;
  100018. state = 1;
  100019. }
  100020. dot1 = nhx * nx + nhy * ny + nhz * nz;
  100021. if (dot1 < dot) {
  100022. dot = dot1;
  100023. state = 2;
  100024. }
  100025. if (-dot1 < dot) {
  100026. dot = -dot1;
  100027. state = 3;
  100028. }
  100029. dot1 = ndx * nx + ndy * ny + ndz * nz;
  100030. if (dot1 < dot) {
  100031. dot = dot1;
  100032. state = 4;
  100033. }
  100034. if (-dot1 < dot) {
  100035. dot = -dot1;
  100036. state = 5;
  100037. }
  100038. var v = b.elements;
  100039. switch (state) {
  100040. case 0:
  100041. //v=b.vertex1;
  100042. v1x = v[0];//v.x;
  100043. v1y = v[1];//v.y;
  100044. v1z = v[2];//v.z;
  100045. //v=b.vertex3;
  100046. v2x = v[6];//v.x;
  100047. v2y = v[7];//v.y;
  100048. v2z = v[8];//v.z;
  100049. //v=b.vertex4;
  100050. v3x = v[9];//v.x;
  100051. v3y = v[10];//v.y;
  100052. v3z = v[11];//v.z;
  100053. //v=b.vertex2;
  100054. v4x = v[3];//v.x;
  100055. v4y = v[4];//v.y;
  100056. v4z = v[5];//v.z;
  100057. break;
  100058. case 1:
  100059. //v=b.vertex6;
  100060. v1x = v[15];//v.x;
  100061. v1y = v[16];//v.y;
  100062. v1z = v[17];//v.z;
  100063. //v=b.vertex8;
  100064. v2x = v[21];//v.x;
  100065. v2y = v[22];//v.y;
  100066. v2z = v[23];//v.z;
  100067. //v=b.vertex7;
  100068. v3x = v[18];//v.x;
  100069. v3y = v[19];//v.y;
  100070. v3z = v[20];//v.z;
  100071. //v=b.vertex5;
  100072. v4x = v[12];//v.x;
  100073. v4y = v[13];//v.y;
  100074. v4z = v[14];//v.z;
  100075. break;
  100076. case 2:
  100077. //v=b.vertex5;
  100078. v1x = v[12];//v.x;
  100079. v1y = v[13];//v.y;
  100080. v1z = v[14];//v.z;
  100081. //v=b.vertex1;
  100082. v2x = v[0];//v.x;
  100083. v2y = v[1];//v.y;
  100084. v2z = v[2];//v.z;
  100085. //v=b.vertex2;
  100086. v3x = v[3];//v.x;
  100087. v3y = v[4];//v.y;
  100088. v3z = v[5];//v.z;
  100089. //v=b.vertex6;
  100090. v4x = v[15];//v.x;
  100091. v4y = v[16];//v.y;
  100092. v4z = v[17];//v.z;
  100093. break;
  100094. case 3:
  100095. //v=b.vertex8;
  100096. v1x = v[21];//v.x;
  100097. v1y = v[22];//v.y;
  100098. v1z = v[23];//v.z;
  100099. //v=b.vertex4;
  100100. v2x = v[9];//v.x;
  100101. v2y = v[10];//v.y;
  100102. v2z = v[11];//v.z;
  100103. //v=b.vertex3;
  100104. v3x = v[6];//v.x;
  100105. v3y = v[7];//v.y;
  100106. v3z = v[8];//v.z;
  100107. //v=b.vertex7;
  100108. v4x = v[18];//v.x;
  100109. v4y = v[19];//v.y;
  100110. v4z = v[20];//v.z;
  100111. break;
  100112. case 4:
  100113. //v=b.vertex5;
  100114. v1x = v[12];//v.x;
  100115. v1y = v[13];//v.y;
  100116. v1z = v[14];//v.z;
  100117. //v=b.vertex7;
  100118. v2x = v[18];//v.x;
  100119. v2y = v[19];//v.y;
  100120. v2z = v[20];//v.z;
  100121. //v=b.vertex3;
  100122. v3x = v[6];//v.x;
  100123. v3y = v[7];//v.y;
  100124. v3z = v[8];//v.z;
  100125. //v=b.vertex1;
  100126. v4x = v[0];//v.x;
  100127. v4y = v[1];//v.y;
  100128. v4z = v[2];//v.z;
  100129. break;
  100130. case 5:
  100131. //v=b.vertex2;
  100132. v1x = v[3];//v.x;
  100133. v1y = v[4];//v.y;
  100134. v1z = v[5];//v.z;
  100135. //v=b.vertex4;
  100136. v2x = v[9];//v.x;
  100137. v2y = v[10];//v.y;
  100138. v2z = v[11];//v.z;
  100139. //v=b.vertex8;
  100140. v3x = v[21];//v.x;
  100141. v3y = v[22];//v.y;
  100142. v3z = v[23];//v.z;
  100143. //v=b.vertex6;
  100144. v4x = v[15];//v.x;
  100145. v4y = v[16];//v.y;
  100146. v4z = v[17];//v.z;
  100147. break;
  100148. }
  100149. pd = nx * (v1x - ccx) + ny * (v1y - ccy) + nz * (v1z - ccz);
  100150. if (pd <= 0) manifold.addPoint(v1x, v1y, v1z, -nx, -ny, -nz, pd, this.flip);
  100151. pd = nx * (v2x - ccx) + ny * (v2y - ccy) + nz * (v2z - ccz);
  100152. if (pd <= 0) manifold.addPoint(v2x, v2y, v2z, -nx, -ny, -nz, pd, this.flip);
  100153. pd = nx * (v3x - ccx) + ny * (v3y - ccy) + nz * (v3z - ccz);
  100154. if (pd <= 0) manifold.addPoint(v3x, v3y, v3z, -nx, -ny, -nz, pd, this.flip);
  100155. pd = nx * (v4x - ccx) + ny * (v4y - ccy) + nz * (v4z - ccz);
  100156. if (pd <= 0) manifold.addPoint(v4x, v4y, v4z, -nx, -ny, -nz, pd, this.flip);
  100157. } else {
  100158. switch (state) {
  100159. case 1:
  100160. if (right1) {
  100161. cbx = pbx + dwx;
  100162. cby = pby + dwy;
  100163. cbz = pbz + dwz;
  100164. nx = nwx;
  100165. ny = nwy;
  100166. nz = nwz;
  100167. } else {
  100168. cbx = pbx - dwx;
  100169. cby = pby - dwy;
  100170. cbz = pbz - dwz;
  100171. nx = -nwx;
  100172. ny = -nwy;
  100173. nz = -nwz;
  100174. }
  100175. dir1x = nhx;
  100176. dir1y = nhy;
  100177. dir1z = nhz;
  100178. dir1l = bh;
  100179. dir2x = ndx;
  100180. dir2y = ndy;
  100181. dir2z = ndz;
  100182. dir2l = bd;
  100183. break;
  100184. case 2:
  100185. if (right2) {
  100186. cbx = pbx + dhx;
  100187. cby = pby + dhy;
  100188. cbz = pbz + dhz;
  100189. nx = nhx;
  100190. ny = nhy;
  100191. nz = nhz;
  100192. } else {
  100193. cbx = pbx - dhx;
  100194. cby = pby - dhy;
  100195. cbz = pbz - dhz;
  100196. nx = -nhx;
  100197. ny = -nhy;
  100198. nz = -nhz;
  100199. }
  100200. dir1x = nwx;
  100201. dir1y = nwy;
  100202. dir1z = nwz;
  100203. dir1l = bw;
  100204. dir2x = ndx;
  100205. dir2y = ndy;
  100206. dir2z = ndz;
  100207. dir2l = bd;
  100208. break;
  100209. case 3:
  100210. if (right3) {
  100211. cbx = pbx + ddx;
  100212. cby = pby + ddy;
  100213. cbz = pbz + ddz;
  100214. nx = ndx;
  100215. ny = ndy;
  100216. nz = ndz;
  100217. } else {
  100218. cbx = pbx - ddx;
  100219. cby = pby - ddy;
  100220. cbz = pbz - ddz;
  100221. nx = -ndx;
  100222. ny = -ndy;
  100223. nz = -ndz;
  100224. }
  100225. dir1x = nwx;
  100226. dir1y = nwy;
  100227. dir1z = nwz;
  100228. dir1l = bw;
  100229. dir2x = nhx;
  100230. dir2y = nhy;
  100231. dir2z = nhz;
  100232. dir2l = bh;
  100233. break;
  100234. }
  100235. dot = nx * ncx + ny * ncy + nz * ncz;
  100236. if (dot < 0) len = ch;
  100237. else len = -ch;
  100238. ccx = pcx + len * ncx;
  100239. ccy = pcy + len * ncy;
  100240. ccz = pcz + len * ncz;
  100241. if (dotc >= 0.999999) {
  100242. tx = -ny;
  100243. ty = nz;
  100244. tz = nx;
  100245. } else {
  100246. tx = nx;
  100247. ty = ny;
  100248. tz = nz;
  100249. }
  100250. len = tx * ncx + ty * ncy + tz * ncz;
  100251. dx = len * ncx - tx;
  100252. dy = len * ncy - ty;
  100253. dz = len * ncz - tz;
  100254. len = OIMO.sqrt(dx * dx + dy * dy + dz * dz);
  100255. if (len == 0) return;
  100256. len = r / len;
  100257. dx *= len;
  100258. dy *= len;
  100259. dz *= len;
  100260. tx = ccx + dx;
  100261. ty = ccy + dy;
  100262. tz = ccz + dz;
  100263. if (dot < -0.96 || dot > 0.96) {
  100264. r00 = ncx * ncx * 1.5 - 0.5;
  100265. r01 = ncx * ncy * 1.5 - ncz * 0.866025403;
  100266. r02 = ncx * ncz * 1.5 + ncy * 0.866025403;
  100267. r10 = ncy * ncx * 1.5 + ncz * 0.866025403;
  100268. r11 = ncy * ncy * 1.5 - 0.5;
  100269. r12 = ncy * ncz * 1.5 - ncx * 0.866025403;
  100270. r20 = ncz * ncx * 1.5 - ncy * 0.866025403;
  100271. r21 = ncz * ncy * 1.5 + ncx * 0.866025403;
  100272. r22 = ncz * ncz * 1.5 - 0.5;
  100273. px = tx;
  100274. py = ty;
  100275. pz = tz;
  100276. pd = nx * (px - cbx) + ny * (py - cby) + nz * (pz - cbz);
  100277. tx = px - pd * nx - cbx;
  100278. ty = py - pd * ny - cby;
  100279. tz = pz - pd * nz - cbz;
  100280. sd = dir1x * tx + dir1y * ty + dir1z * tz;
  100281. ed = dir2x * tx + dir2y * ty + dir2z * tz;
  100282. if (sd < -dir1l) sd = -dir1l;
  100283. else if (sd > dir1l) sd = dir1l;
  100284. if (ed < -dir2l) ed = -dir2l;
  100285. else if (ed > dir2l) ed = dir2l;
  100286. tx = sd * dir1x + ed * dir2x;
  100287. ty = sd * dir1y + ed * dir2y;
  100288. tz = sd * dir1z + ed * dir2z;
  100289. px = cbx + tx;
  100290. py = cby + ty;
  100291. pz = cbz + tz;
  100292. manifold.addPoint(px, py, pz, nx, ny, nz, pd, this.flip);
  100293. px = dx * r00 + dy * r01 + dz * r02;
  100294. py = dx * r10 + dy * r11 + dz * r12;
  100295. pz = dx * r20 + dy * r21 + dz * r22;
  100296. px = (dx = px) + ccx;
  100297. py = (dy = py) + ccy;
  100298. pz = (dz = pz) + ccz;
  100299. pd = nx * (px - cbx) + ny * (py - cby) + nz * (pz - cbz);
  100300. if (pd <= 0) {
  100301. tx = px - pd * nx - cbx;
  100302. ty = py - pd * ny - cby;
  100303. tz = pz - pd * nz - cbz;
  100304. sd = dir1x * tx + dir1y * ty + dir1z * tz;
  100305. ed = dir2x * tx + dir2y * ty + dir2z * tz;
  100306. if (sd < -dir1l) sd = -dir1l;
  100307. else if (sd > dir1l) sd = dir1l;
  100308. if (ed < -dir2l) ed = -dir2l;
  100309. else if (ed > dir2l) ed = dir2l;
  100310. tx = sd * dir1x + ed * dir2x;
  100311. ty = sd * dir1y + ed * dir2y;
  100312. tz = sd * dir1z + ed * dir2z;
  100313. px = cbx + tx;
  100314. py = cby + ty;
  100315. pz = cbz + tz;
  100316. //manifold.addPoint(px,py,pz,nx,ny,nz,pd,b,c,2,0,false);
  100317. manifold.addPoint(px, py, pz, nx, ny, nz, pd, this.flip);
  100318. }
  100319. px = dx * r00 + dy * r01 + dz * r02;
  100320. py = dx * r10 + dy * r11 + dz * r12;
  100321. pz = dx * r20 + dy * r21 + dz * r22;
  100322. px = (dx = px) + ccx;
  100323. py = (dy = py) + ccy;
  100324. pz = (dz = pz) + ccz;
  100325. pd = nx * (px - cbx) + ny * (py - cby) + nz * (pz - cbz);
  100326. if (pd <= 0) {
  100327. tx = px - pd * nx - cbx;
  100328. ty = py - pd * ny - cby;
  100329. tz = pz - pd * nz - cbz;
  100330. sd = dir1x * tx + dir1y * ty + dir1z * tz;
  100331. ed = dir2x * tx + dir2y * ty + dir2z * tz;
  100332. if (sd < -dir1l) sd = -dir1l;
  100333. else if (sd > dir1l) sd = dir1l;
  100334. if (ed < -dir2l) ed = -dir2l;
  100335. else if (ed > dir2l) ed = dir2l;
  100336. tx = sd * dir1x + ed * dir2x;
  100337. ty = sd * dir1y + ed * dir2y;
  100338. tz = sd * dir1z + ed * dir2z;
  100339. px = cbx + tx;
  100340. py = cby + ty;
  100341. pz = cbz + tz;
  100342. //manifold.addPoint(px,py,pz,nx,ny,nz,pd,b,c,3,0,false);
  100343. manifold.addPoint(px, py, pz, nx, ny, nz, pd, this.flip);
  100344. }
  100345. } else {
  100346. sx = tx;
  100347. sy = ty;
  100348. sz = tz;
  100349. sd = nx * (sx - cbx) + ny * (sy - cby) + nz * (sz - cbz);
  100350. sx -= sd * nx;
  100351. sy -= sd * ny;
  100352. sz -= sd * nz;
  100353. if (dot > 0) {
  100354. ex = tx + dcx * 2;
  100355. ey = ty + dcy * 2;
  100356. ez = tz + dcz * 2;
  100357. } else {
  100358. ex = tx - dcx * 2;
  100359. ey = ty - dcy * 2;
  100360. ez = tz - dcz * 2;
  100361. }
  100362. ed = nx * (ex - cbx) + ny * (ey - cby) + nz * (ez - cbz);
  100363. ex -= ed * nx;
  100364. ey -= ed * ny;
  100365. ez -= ed * nz;
  100366. d1x = sx - cbx;
  100367. d1y = sy - cby;
  100368. d1z = sz - cbz;
  100369. d2x = ex - cbx;
  100370. d2y = ey - cby;
  100371. d2z = ez - cbz;
  100372. tx = ex - sx;
  100373. ty = ey - sy;
  100374. tz = ez - sz;
  100375. td = ed - sd;
  100376. dotw = d1x * dir1x + d1y * dir1y + d1z * dir1z;
  100377. doth = d2x * dir1x + d2y * dir1y + d2z * dir1z;
  100378. dot1 = dotw - dir1l;
  100379. dot2 = doth - dir1l;
  100380. if (dot1 > 0) {
  100381. if (dot2 > 0) return;
  100382. t1 = dot1 / (dot1 - dot2);
  100383. sx = sx + tx * t1;
  100384. sy = sy + ty * t1;
  100385. sz = sz + tz * t1;
  100386. sd = sd + td * t1;
  100387. d1x = sx - cbx;
  100388. d1y = sy - cby;
  100389. d1z = sz - cbz;
  100390. dotw = d1x * dir1x + d1y * dir1y + d1z * dir1z;
  100391. tx = ex - sx;
  100392. ty = ey - sy;
  100393. tz = ez - sz;
  100394. td = ed - sd;
  100395. } else if (dot2 > 0) {
  100396. t1 = dot1 / (dot1 - dot2);
  100397. ex = sx + tx * t1;
  100398. ey = sy + ty * t1;
  100399. ez = sz + tz * t1;
  100400. ed = sd + td * t1;
  100401. d2x = ex - cbx;
  100402. d2y = ey - cby;
  100403. d2z = ez - cbz;
  100404. doth = d2x * dir1x + d2y * dir1y + d2z * dir1z;
  100405. tx = ex - sx;
  100406. ty = ey - sy;
  100407. tz = ez - sz;
  100408. td = ed - sd;
  100409. }
  100410. dot1 = dotw + dir1l;
  100411. dot2 = doth + dir1l;
  100412. if (dot1 < 0) {
  100413. if (dot2 < 0) return;
  100414. t1 = dot1 / (dot1 - dot2);
  100415. sx = sx + tx * t1;
  100416. sy = sy + ty * t1;
  100417. sz = sz + tz * t1;
  100418. sd = sd + td * t1;
  100419. d1x = sx - cbx;
  100420. d1y = sy - cby;
  100421. d1z = sz - cbz;
  100422. tx = ex - sx;
  100423. ty = ey - sy;
  100424. tz = ez - sz;
  100425. td = ed - sd;
  100426. } else if (dot2 < 0) {
  100427. t1 = dot1 / (dot1 - dot2);
  100428. ex = sx + tx * t1;
  100429. ey = sy + ty * t1;
  100430. ez = sz + tz * t1;
  100431. ed = sd + td * t1;
  100432. d2x = ex - cbx;
  100433. d2y = ey - cby;
  100434. d2z = ez - cbz;
  100435. tx = ex - sx;
  100436. ty = ey - sy;
  100437. tz = ez - sz;
  100438. td = ed - sd;
  100439. }
  100440. dotw = d1x * dir2x + d1y * dir2y + d1z * dir2z;
  100441. doth = d2x * dir2x + d2y * dir2y + d2z * dir2z;
  100442. dot1 = dotw - dir2l;
  100443. dot2 = doth - dir2l;
  100444. if (dot1 > 0) {
  100445. if (dot2 > 0) return;
  100446. t1 = dot1 / (dot1 - dot2);
  100447. sx = sx + tx * t1;
  100448. sy = sy + ty * t1;
  100449. sz = sz + tz * t1;
  100450. sd = sd + td * t1;
  100451. d1x = sx - cbx;
  100452. d1y = sy - cby;
  100453. d1z = sz - cbz;
  100454. dotw = d1x * dir2x + d1y * dir2y + d1z * dir2z;
  100455. tx = ex - sx;
  100456. ty = ey - sy;
  100457. tz = ez - sz;
  100458. td = ed - sd;
  100459. } else if (dot2 > 0) {
  100460. t1 = dot1 / (dot1 - dot2);
  100461. ex = sx + tx * t1;
  100462. ey = sy + ty * t1;
  100463. ez = sz + tz * t1;
  100464. ed = sd + td * t1;
  100465. d2x = ex - cbx;
  100466. d2y = ey - cby;
  100467. d2z = ez - cbz;
  100468. doth = d2x * dir2x + d2y * dir2y + d2z * dir2z;
  100469. tx = ex - sx;
  100470. ty = ey - sy;
  100471. tz = ez - sz;
  100472. td = ed - sd;
  100473. }
  100474. dot1 = dotw + dir2l;
  100475. dot2 = doth + dir2l;
  100476. if (dot1 < 0) {
  100477. if (dot2 < 0) return;
  100478. t1 = dot1 / (dot1 - dot2);
  100479. sx = sx + tx * t1;
  100480. sy = sy + ty * t1;
  100481. sz = sz + tz * t1;
  100482. sd = sd + td * t1;
  100483. } else if (dot2 < 0) {
  100484. t1 = dot1 / (dot1 - dot2);
  100485. ex = sx + tx * t1;
  100486. ey = sy + ty * t1;
  100487. ez = sz + tz * t1;
  100488. ed = sd + td * t1;
  100489. }
  100490. if (sd < 0) {
  100491. //manifold.addPoint(sx,sy,sz,nx,ny,nz,sd,b,c,1,0,false);
  100492. manifold.addPoint(sx, sy, sz, nx, ny, nz, sd, this.flip);
  100493. }
  100494. if (ed < 0) {
  100495. //manifold.addPoint(ex,ey,ez,nx,ny,nz,ed,b,c,4,0,false);
  100496. manifold.addPoint(ex, ey, ez, nx, ny, nz, ed, this.flip);
  100497. }
  100498. }
  100499. }
  100500. };
  100501. OIMO.CylinderCylinderCollisionDetector = function () {
  100502. OIMO.CollisionDetector.call(this);
  100503. };
  100504. OIMO.CylinderCylinderCollisionDetector.prototype = Object.create(OIMO.CollisionDetector.prototype);
  100505. OIMO.CylinderCylinderCollisionDetector.prototype.constructor = OIMO.CylinderCylinderCollisionDetector;
  100506. OIMO.CylinderCylinderCollisionDetector.prototype.getSep = function (c1, c2, sep, pos, dep) {
  100507. var t1x;
  100508. var t1y;
  100509. var t1z;
  100510. var t2x;
  100511. var t2y;
  100512. var t2z;
  100513. var sup = new OIMO.Vec3();
  100514. var len;
  100515. var p1x;
  100516. var p1y;
  100517. var p1z;
  100518. var p2x;
  100519. var p2y;
  100520. var p2z;
  100521. var v01x = c1.position.x;
  100522. var v01y = c1.position.y;
  100523. var v01z = c1.position.z;
  100524. var v02x = c2.position.x;
  100525. var v02y = c2.position.y;
  100526. var v02z = c2.position.z;
  100527. var v0x = v02x - v01x;
  100528. var v0y = v02y - v01y;
  100529. var v0z = v02z - v01z;
  100530. if (v0x * v0x + v0y * v0y + v0z * v0z == 0) v0y = 0.001;
  100531. var nx = -v0x;
  100532. var ny = -v0y;
  100533. var nz = -v0z;
  100534. this.supportPoint(c1, -nx, -ny, -nz, sup);
  100535. var v11x = sup.x;
  100536. var v11y = sup.y;
  100537. var v11z = sup.z;
  100538. this.supportPoint(c2, nx, ny, nz, sup);
  100539. var v12x = sup.x;
  100540. var v12y = sup.y;
  100541. var v12z = sup.z;
  100542. var v1x = v12x - v11x;
  100543. var v1y = v12y - v11y;
  100544. var v1z = v12z - v11z;
  100545. if (v1x * nx + v1y * ny + v1z * nz <= 0) {
  100546. return false;
  100547. }
  100548. nx = v1y * v0z - v1z * v0y;
  100549. ny = v1z * v0x - v1x * v0z;
  100550. nz = v1x * v0y - v1y * v0x;
  100551. if (nx * nx + ny * ny + nz * nz == 0) {
  100552. sep.init(v1x - v0x, v1y - v0y, v1z - v0z);
  100553. sep.normalize(sep);
  100554. pos.init((v11x + v12x) * 0.5, (v11y + v12y) * 0.5, (v11z + v12z) * 0.5);
  100555. return true;
  100556. }
  100557. this.supportPoint(c1, -nx, -ny, -nz, sup);
  100558. var v21x = sup.x;
  100559. var v21y = sup.y;
  100560. var v21z = sup.z;
  100561. this.supportPoint(c2, nx, ny, nz, sup);
  100562. var v22x = sup.x;
  100563. var v22y = sup.y;
  100564. var v22z = sup.z;
  100565. var v2x = v22x - v21x;
  100566. var v2y = v22y - v21y;
  100567. var v2z = v22z - v21z;
  100568. if (v2x * nx + v2y * ny + v2z * nz <= 0) {
  100569. return false;
  100570. }
  100571. t1x = v1x - v0x;
  100572. t1y = v1y - v0y;
  100573. t1z = v1z - v0z;
  100574. t2x = v2x - v0x;
  100575. t2y = v2y - v0y;
  100576. t2z = v2z - v0z;
  100577. nx = t1y * t2z - t1z * t2y;
  100578. ny = t1z * t2x - t1x * t2z;
  100579. nz = t1x * t2y - t1y * t2x;
  100580. if (nx * v0x + ny * v0y + nz * v0z > 0) {
  100581. t1x = v1x;
  100582. t1y = v1y;
  100583. t1z = v1z;
  100584. v1x = v2x;
  100585. v1y = v2y;
  100586. v1z = v2z;
  100587. v2x = t1x;
  100588. v2y = t1y;
  100589. v2z = t1z;
  100590. t1x = v11x;
  100591. t1y = v11y;
  100592. t1z = v11z;
  100593. v11x = v21x;
  100594. v11y = v21y;
  100595. v11z = v21z;
  100596. v21x = t1x;
  100597. v21y = t1y;
  100598. v21z = t1z;
  100599. t1x = v12x;
  100600. t1y = v12y;
  100601. t1z = v12z;
  100602. v12x = v22x;
  100603. v12y = v22y;
  100604. v12z = v22z;
  100605. v22x = t1x;
  100606. v22y = t1y;
  100607. v22z = t1z;
  100608. nx = -nx;
  100609. ny = -ny;
  100610. nz = -nz;
  100611. }
  100612. var iterations = 0;
  100613. while (true) {
  100614. if (++iterations > 100) {
  100615. return false;
  100616. }
  100617. this.supportPoint(c1, -nx, -ny, -nz, sup);
  100618. var v31x = sup.x;
  100619. var v31y = sup.y;
  100620. var v31z = sup.z;
  100621. this.supportPoint(c2, nx, ny, nz, sup);
  100622. var v32x = sup.x;
  100623. var v32y = sup.y;
  100624. var v32z = sup.z;
  100625. var v3x = v32x - v31x;
  100626. var v3y = v32y - v31y;
  100627. var v3z = v32z - v31z;
  100628. if (v3x * nx + v3y * ny + v3z * nz <= 0) {
  100629. return false;
  100630. }
  100631. if ((v1y * v3z - v1z * v3y) * v0x + (v1z * v3x - v1x * v3z) * v0y + (v1x * v3y - v1y * v3x) * v0z < 0) {
  100632. v2x = v3x;
  100633. v2y = v3y;
  100634. v2z = v3z;
  100635. v21x = v31x;
  100636. v21y = v31y;
  100637. v21z = v31z;
  100638. v22x = v32x;
  100639. v22y = v32y;
  100640. v22z = v32z;
  100641. t1x = v1x - v0x;
  100642. t1y = v1y - v0y;
  100643. t1z = v1z - v0z;
  100644. t2x = v3x - v0x;
  100645. t2y = v3y - v0y;
  100646. t2z = v3z - v0z;
  100647. nx = t1y * t2z - t1z * t2y;
  100648. ny = t1z * t2x - t1x * t2z;
  100649. nz = t1x * t2y - t1y * t2x;
  100650. continue;
  100651. }
  100652. if ((v3y * v2z - v3z * v2y) * v0x + (v3z * v2x - v3x * v2z) * v0y + (v3x * v2y - v3y * v2x) * v0z < 0) {
  100653. v1x = v3x;
  100654. v1y = v3y;
  100655. v1z = v3z;
  100656. v11x = v31x;
  100657. v11y = v31y;
  100658. v11z = v31z;
  100659. v12x = v32x;
  100660. v12y = v32y;
  100661. v12z = v32z;
  100662. t1x = v3x - v0x;
  100663. t1y = v3y - v0y;
  100664. t1z = v3z - v0z;
  100665. t2x = v2x - v0x;
  100666. t2y = v2y - v0y;
  100667. t2z = v2z - v0z;
  100668. nx = t1y * t2z - t1z * t2y;
  100669. ny = t1z * t2x - t1x * t2z;
  100670. nz = t1x * t2y - t1y * t2x;
  100671. continue;
  100672. }
  100673. var hit = false;
  100674. while (true) {
  100675. t1x = v2x - v1x;
  100676. t1y = v2y - v1y;
  100677. t1z = v2z - v1z;
  100678. t2x = v3x - v1x;
  100679. t2y = v3y - v1y;
  100680. t2z = v3z - v1z;
  100681. nx = t1y * t2z - t1z * t2y;
  100682. ny = t1z * t2x - t1x * t2z;
  100683. nz = t1x * t2y - t1y * t2x;
  100684. len = 1 / OIMO.sqrt(nx * nx + ny * ny + nz * nz);
  100685. nx *= len;
  100686. ny *= len;
  100687. nz *= len;
  100688. if (nx * v1x + ny * v1y + nz * v1z >= 0 && !hit) {
  100689. var b0 = (v1y * v2z - v1z * v2y) * v3x + (v1z * v2x - v1x * v2z) * v3y + (v1x * v2y - v1y * v2x) * v3z;
  100690. var b1 = (v3y * v2z - v3z * v2y) * v0x + (v3z * v2x - v3x * v2z) * v0y + (v3x * v2y - v3y * v2x) * v0z;
  100691. var b2 = (v0y * v1z - v0z * v1y) * v3x + (v0z * v1x - v0x * v1z) * v3y + (v0x * v1y - v0y * v1x) * v3z;
  100692. var b3 = (v2y * v1z - v2z * v1y) * v0x + (v2z * v1x - v2x * v1z) * v0y + (v2x * v1y - v2y * v1x) * v0z;
  100693. var sum = b0 + b1 + b2 + b3;
  100694. if (sum <= 0) {
  100695. b0 = 0;
  100696. b1 = (v2y * v3z - v2z * v3y) * nx + (v2z * v3x - v2x * v3z) * ny + (v2x * v3y - v2y * v3x) * nz;
  100697. b2 = (v3y * v2z - v3z * v2y) * nx + (v3z * v2x - v3x * v2z) * ny + (v3x * v2y - v3y * v2x) * nz;
  100698. b3 = (v1y * v2z - v1z * v2y) * nx + (v1z * v2x - v1x * v2z) * ny + (v1x * v2y - v1y * v2x) * nz;
  100699. sum = b1 + b2 + b3;
  100700. }
  100701. var inv = 1 / sum;
  100702. p1x = (v01x * b0 + v11x * b1 + v21x * b2 + v31x * b3) * inv;
  100703. p1y = (v01y * b0 + v11y * b1 + v21y * b2 + v31y * b3) * inv;
  100704. p1z = (v01z * b0 + v11z * b1 + v21z * b2 + v31z * b3) * inv;
  100705. p2x = (v02x * b0 + v12x * b1 + v22x * b2 + v32x * b3) * inv;
  100706. p2y = (v02y * b0 + v12y * b1 + v22y * b2 + v32y * b3) * inv;
  100707. p2z = (v02z * b0 + v12z * b1 + v22z * b2 + v32z * b3) * inv;
  100708. hit = true;
  100709. }
  100710. this.supportPoint(c1, -nx, -ny, -nz, sup);
  100711. var v41x = sup.x;
  100712. var v41y = sup.y;
  100713. var v41z = sup.z;
  100714. this.supportPoint(c2, nx, ny, nz, sup);
  100715. var v42x = sup.x;
  100716. var v42y = sup.y;
  100717. var v42z = sup.z;
  100718. var v4x = v42x - v41x;
  100719. var v4y = v42y - v41y;
  100720. var v4z = v42z - v41z;
  100721. var separation = -(v4x * nx + v4y * ny + v4z * nz);
  100722. if ((v4x - v3x) * nx + (v4y - v3y) * ny + (v4z - v3z) * nz <= 0.01 || separation >= 0) {
  100723. if (hit) {
  100724. sep.init(-nx, -ny, -nz);
  100725. pos.init((p1x + p2x) * 0.5, (p1y + p2y) * 0.5, (p1z + p2z) * 0.5);
  100726. dep.x = separation;
  100727. return true;
  100728. }
  100729. return false;
  100730. }
  100731. if (
  100732. (v4y * v1z - v4z * v1y) * v0x +
  100733. (v4z * v1x - v4x * v1z) * v0y +
  100734. (v4x * v1y - v4y * v1x) * v0z < 0
  100735. ) {
  100736. if (
  100737. (v4y * v2z - v4z * v2y) * v0x +
  100738. (v4z * v2x - v4x * v2z) * v0y +
  100739. (v4x * v2y - v4y * v2x) * v0z < 0
  100740. ) {
  100741. v1x = v4x;
  100742. v1y = v4y;
  100743. v1z = v4z;
  100744. v11x = v41x;
  100745. v11y = v41y;
  100746. v11z = v41z;
  100747. v12x = v42x;
  100748. v12y = v42y;
  100749. v12z = v42z;
  100750. } else {
  100751. v3x = v4x;
  100752. v3y = v4y;
  100753. v3z = v4z;
  100754. v31x = v41x;
  100755. v31y = v41y;
  100756. v31z = v41z;
  100757. v32x = v42x;
  100758. v32y = v42y;
  100759. v32z = v42z;
  100760. }
  100761. } else {
  100762. if (
  100763. (v4y * v3z - v4z * v3y) * v0x +
  100764. (v4z * v3x - v4x * v3z) * v0y +
  100765. (v4x * v3y - v4y * v3x) * v0z < 0
  100766. ) {
  100767. v2x = v4x;
  100768. v2y = v4y;
  100769. v2z = v4z;
  100770. v21x = v41x;
  100771. v21y = v41y;
  100772. v21z = v41z;
  100773. v22x = v42x;
  100774. v22y = v42y;
  100775. v22z = v42z;
  100776. } else {
  100777. v1x = v4x;
  100778. v1y = v4y;
  100779. v1z = v4z;
  100780. v11x = v41x;
  100781. v11y = v41y;
  100782. v11z = v41z;
  100783. v12x = v42x;
  100784. v12y = v42y;
  100785. v12z = v42z;
  100786. }
  100787. }
  100788. }
  100789. }
  100790. //return false;
  100791. };
  100792. OIMO.CylinderCylinderCollisionDetector.prototype.supportPoint = function (c, dx, dy, dz, out) {
  100793. var rot = c.rotation.elements;
  100794. var ldx = rot[0] * dx + rot[3] * dy + rot[6] * dz;
  100795. var ldy = rot[1] * dx + rot[4] * dy + rot[7] * dz;
  100796. var ldz = rot[2] * dx + rot[5] * dy + rot[8] * dz;
  100797. var radx = ldx;
  100798. var radz = ldz;
  100799. var len = radx * radx + radz * radz;
  100800. var rad = c.radius;
  100801. var hh = c.halfHeight;
  100802. var ox;
  100803. var oy;
  100804. var oz;
  100805. if (len == 0) {
  100806. if (ldy < 0) {
  100807. ox = rad;
  100808. oy = -hh;
  100809. oz = 0;
  100810. } else {
  100811. ox = rad;
  100812. oy = hh;
  100813. oz = 0;
  100814. }
  100815. } else {
  100816. len = c.radius / OIMO.sqrt(len);
  100817. if (ldy < 0) {
  100818. ox = radx * len;
  100819. oy = -hh;
  100820. oz = radz * len;
  100821. } else {
  100822. ox = radx * len;
  100823. oy = hh;
  100824. oz = radz * len;
  100825. }
  100826. }
  100827. ldx = rot[0] * ox + rot[1] * oy + rot[2] * oz + c.position.x;
  100828. ldy = rot[3] * ox + rot[4] * oy + rot[5] * oz + c.position.y;
  100829. ldz = rot[6] * ox + rot[7] * oy + rot[8] * oz + c.position.z;
  100830. out.init(ldx, ldy, ldz);
  100831. };
  100832. OIMO.CylinderCylinderCollisionDetector.prototype.detectCollision = function (shape1, shape2, manifold) {
  100833. var c1;
  100834. var c2;
  100835. if (shape1.id < shape2.id) {
  100836. c1 = shape1;
  100837. c2 = shape2;
  100838. } else {
  100839. c1 = shape2;
  100840. c2 = shape1;
  100841. }
  100842. var p1 = c1.position;
  100843. var p2 = c2.position;
  100844. var p1x = p1.x;
  100845. var p1y = p1.y;
  100846. var p1z = p1.z;
  100847. var p2x = p2.x;
  100848. var p2y = p2.y;
  100849. var p2z = p2.z;
  100850. var h1 = c1.halfHeight;
  100851. var h2 = c2.halfHeight;
  100852. var n1 = c1.normalDirection;
  100853. var n2 = c2.normalDirection;
  100854. var d1 = c1.halfDirection;
  100855. var d2 = c2.halfDirection;
  100856. var r1 = c1.radius;
  100857. var r2 = c2.radius;
  100858. var n1x = n1.x;
  100859. var n1y = n1.y;
  100860. var n1z = n1.z;
  100861. var n2x = n2.x;
  100862. var n2y = n2.y;
  100863. var n2z = n2.z;
  100864. var d1x = d1.x;
  100865. var d1y = d1.y;
  100866. var d1z = d1.z;
  100867. var d2x = d2.x;
  100868. var d2y = d2.y;
  100869. var d2z = d2.z;
  100870. var dx = p1x - p2x;
  100871. var dy = p1y - p2y;
  100872. var dz = p1z - p2z;
  100873. var len;
  100874. var len1;
  100875. var len2;
  100876. var c;
  100877. var c1x;
  100878. var c1y;
  100879. var c1z;
  100880. var c2x;
  100881. var c2y;
  100882. var c2z;
  100883. var tx;
  100884. var ty;
  100885. var tz;
  100886. var sx;
  100887. var sy;
  100888. var sz;
  100889. var ex;
  100890. var ey;
  100891. var ez;
  100892. var depth1;
  100893. var depth2;
  100894. var dot;
  100895. var t1;
  100896. var t2;
  100897. var sep = new OIMO.Vec3();
  100898. var pos = new OIMO.Vec3();
  100899. var dep = new OIMO.Vec3();
  100900. if (!this.getSep(c1, c2, sep, pos, dep)) return;
  100901. var dot1 = sep.x * n1x + sep.y * n1y + sep.z * n1z;
  100902. var dot2 = sep.x * n2x + sep.y * n2y + sep.z * n2z;
  100903. var right1 = dot1 > 0;
  100904. var right2 = dot2 > 0;
  100905. if (!right1) dot1 = -dot1;
  100906. if (!right2) dot2 = -dot2;
  100907. var state = 0;
  100908. if (dot1 > 0.999 || dot2 > 0.999) {
  100909. if (dot1 > dot2) state = 1;
  100910. else state = 2;
  100911. }
  100912. var nx;
  100913. var ny;
  100914. var nz;
  100915. var depth = dep.x;
  100916. var r00;
  100917. var r01;
  100918. var r02;
  100919. var r10;
  100920. var r11;
  100921. var r12;
  100922. var r20;
  100923. var r21;
  100924. var r22;
  100925. var px;
  100926. var py;
  100927. var pz;
  100928. var pd;
  100929. var a;
  100930. var b;
  100931. var e;
  100932. var f;
  100933. nx = sep.x;
  100934. ny = sep.y;
  100935. nz = sep.z;
  100936. switch (state) {
  100937. case 0:
  100938. manifold.addPoint(pos.x, pos.y, pos.z, nx, ny, nz, depth, false);
  100939. break;
  100940. case 1:
  100941. if (right1) {
  100942. c1x = p1x + d1x;
  100943. c1y = p1y + d1y;
  100944. c1z = p1z + d1z;
  100945. nx = n1x;
  100946. ny = n1y;
  100947. nz = n1z;
  100948. } else {
  100949. c1x = p1x - d1x;
  100950. c1y = p1y - d1y;
  100951. c1z = p1z - d1z;
  100952. nx = -n1x;
  100953. ny = -n1y;
  100954. nz = -n1z;
  100955. }
  100956. dot = nx * n2x + ny * n2y + nz * n2z;
  100957. if (dot < 0) len = h2;
  100958. else len = -h2;
  100959. c2x = p2x + len * n2x;
  100960. c2y = p2y + len * n2y;
  100961. c2z = p2z + len * n2z;
  100962. if (dot2 >= 0.999999) {
  100963. tx = -ny;
  100964. ty = nz;
  100965. tz = nx;
  100966. } else {
  100967. tx = nx;
  100968. ty = ny;
  100969. tz = nz;
  100970. }
  100971. len = tx * n2x + ty * n2y + tz * n2z;
  100972. dx = len * n2x - tx;
  100973. dy = len * n2y - ty;
  100974. dz = len * n2z - tz;
  100975. len = OIMO.sqrt(dx * dx + dy * dy + dz * dz);
  100976. if (len == 0) break;
  100977. len = r2 / len;
  100978. dx *= len;
  100979. dy *= len;
  100980. dz *= len;
  100981. tx = c2x + dx;
  100982. ty = c2y + dy;
  100983. tz = c2z + dz;
  100984. if (dot < -0.96 || dot > 0.96) {
  100985. r00 = n2x * n2x * 1.5 - 0.5;
  100986. r01 = n2x * n2y * 1.5 - n2z * 0.866025403;
  100987. r02 = n2x * n2z * 1.5 + n2y * 0.866025403;
  100988. r10 = n2y * n2x * 1.5 + n2z * 0.866025403;
  100989. r11 = n2y * n2y * 1.5 - 0.5;
  100990. r12 = n2y * n2z * 1.5 - n2x * 0.866025403;
  100991. r20 = n2z * n2x * 1.5 - n2y * 0.866025403;
  100992. r21 = n2z * n2y * 1.5 + n2x * 0.866025403;
  100993. r22 = n2z * n2z * 1.5 - 0.5;
  100994. px = tx;
  100995. py = ty;
  100996. pz = tz;
  100997. pd = nx * (px - c1x) + ny * (py - c1y) + nz * (pz - c1z);
  100998. tx = px - pd * nx - c1x;
  100999. ty = py - pd * ny - c1y;
  101000. tz = pz - pd * nz - c1z;
  101001. len = tx * tx + ty * ty + tz * tz;
  101002. if (len > r1 * r1) {
  101003. len = r1 / OIMO.sqrt(len);
  101004. tx *= len;
  101005. ty *= len;
  101006. tz *= len;
  101007. }
  101008. px = c1x + tx;
  101009. py = c1y + ty;
  101010. pz = c1z + tz;
  101011. manifold.addPoint(px, py, pz, nx, ny, nz, pd, false);
  101012. px = dx * r00 + dy * r01 + dz * r02;
  101013. py = dx * r10 + dy * r11 + dz * r12;
  101014. pz = dx * r20 + dy * r21 + dz * r22;
  101015. px = (dx = px) + c2x;
  101016. py = (dy = py) + c2y;
  101017. pz = (dz = pz) + c2z;
  101018. pd = nx * (px - c1x) + ny * (py - c1y) + nz * (pz - c1z);
  101019. if (pd <= 0) {
  101020. tx = px - pd * nx - c1x;
  101021. ty = py - pd * ny - c1y;
  101022. tz = pz - pd * nz - c1z;
  101023. len = tx * tx + ty * ty + tz * tz;
  101024. if (len > r1 * r1) {
  101025. len = r1 / OIMO.sqrt(len);
  101026. tx *= len;
  101027. ty *= len;
  101028. tz *= len;
  101029. }
  101030. px = c1x + tx;
  101031. py = c1y + ty;
  101032. pz = c1z + tz;
  101033. manifold.addPoint(px, py, pz, nx, ny, nz, pd, false);
  101034. }
  101035. px = dx * r00 + dy * r01 + dz * r02;
  101036. py = dx * r10 + dy * r11 + dz * r12;
  101037. pz = dx * r20 + dy * r21 + dz * r22;
  101038. px = (dx = px) + c2x;
  101039. py = (dy = py) + c2y;
  101040. pz = (dz = pz) + c2z;
  101041. pd = nx * (px - c1x) + ny * (py - c1y) + nz * (pz - c1z);
  101042. if (pd <= 0) {
  101043. tx = px - pd * nx - c1x;
  101044. ty = py - pd * ny - c1y;
  101045. tz = pz - pd * nz - c1z;
  101046. len = tx * tx + ty * ty + tz * tz;
  101047. if (len > r1 * r1) {
  101048. len = r1 / OIMO.sqrt(len);
  101049. tx *= len;
  101050. ty *= len;
  101051. tz *= len;
  101052. }
  101053. px = c1x + tx;
  101054. py = c1y + ty;
  101055. pz = c1z + tz;
  101056. manifold.addPoint(px, py, pz, nx, ny, nz, pd, false);
  101057. }
  101058. } else {
  101059. sx = tx;
  101060. sy = ty;
  101061. sz = tz;
  101062. depth1 = nx * (sx - c1x) + ny * (sy - c1y) + nz * (sz - c1z);
  101063. sx -= depth1 * nx;
  101064. sy -= depth1 * ny;
  101065. sz -= depth1 * nz;
  101066. if (dot > 0) {
  101067. ex = tx + n2x * h2 * 2;
  101068. ey = ty + n2y * h2 * 2;
  101069. ez = tz + n2z * h2 * 2;
  101070. } else {
  101071. ex = tx - n2x * h2 * 2;
  101072. ey = ty - n2y * h2 * 2;
  101073. ez = tz - n2z * h2 * 2;
  101074. }
  101075. depth2 = nx * (ex - c1x) + ny * (ey - c1y) + nz * (ez - c1z);
  101076. ex -= depth2 * nx;
  101077. ey -= depth2 * ny;
  101078. ez -= depth2 * nz;
  101079. dx = c1x - sx;
  101080. dy = c1y - sy;
  101081. dz = c1z - sz;
  101082. tx = ex - sx;
  101083. ty = ey - sy;
  101084. tz = ez - sz;
  101085. a = dx * dx + dy * dy + dz * dz;
  101086. b = dx * tx + dy * ty + dz * tz;
  101087. e = tx * tx + ty * ty + tz * tz;
  101088. f = b * b - e * (a - r1 * r1);
  101089. if (f < 0) break;
  101090. f = OIMO.sqrt(f);
  101091. t1 = (b + f) / e;
  101092. t2 = (b - f) / e;
  101093. if (t2 < t1) {
  101094. len = t1;
  101095. t1 = t2;
  101096. t2 = len;
  101097. }
  101098. if (t2 > 1) t2 = 1;
  101099. if (t1 < 0) t1 = 0;
  101100. tx = sx + (ex - sx) * t1;
  101101. ty = sy + (ey - sy) * t1;
  101102. tz = sz + (ez - sz) * t1;
  101103. ex = sx + (ex - sx) * t2;
  101104. ey = sy + (ey - sy) * t2;
  101105. ez = sz + (ez - sz) * t2;
  101106. sx = tx;
  101107. sy = ty;
  101108. sz = tz;
  101109. len = depth1 + (depth2 - depth1) * t1;
  101110. depth2 = depth1 + (depth2 - depth1) * t2;
  101111. depth1 = len;
  101112. if (depth1 < 0) manifold.addPoint(sx, sy, sz, nx, ny, nz, pd, false);
  101113. if (depth2 < 0) manifold.addPoint(ex, ey, ez, nx, ny, nz, pd, false);
  101114. }
  101115. break;
  101116. case 2:
  101117. if (right2) {
  101118. c2x = p2x - d2x;
  101119. c2y = p2y - d2y;
  101120. c2z = p2z - d2z;
  101121. nx = -n2x;
  101122. ny = -n2y;
  101123. nz = -n2z;
  101124. } else {
  101125. c2x = p2x + d2x;
  101126. c2y = p2y + d2y;
  101127. c2z = p2z + d2z;
  101128. nx = n2x;
  101129. ny = n2y;
  101130. nz = n2z;
  101131. }
  101132. dot = nx * n1x + ny * n1y + nz * n1z;
  101133. if (dot < 0) len = h1;
  101134. else len = -h1;
  101135. c1x = p1x + len * n1x;
  101136. c1y = p1y + len * n1y;
  101137. c1z = p1z + len * n1z;
  101138. if (dot1 >= 0.999999) {
  101139. tx = -ny;
  101140. ty = nz;
  101141. tz = nx;
  101142. } else {
  101143. tx = nx;
  101144. ty = ny;
  101145. tz = nz;
  101146. }
  101147. len = tx * n1x + ty * n1y + tz * n1z;
  101148. dx = len * n1x - tx;
  101149. dy = len * n1y - ty;
  101150. dz = len * n1z - tz;
  101151. len = OIMO.sqrt(dx * dx + dy * dy + dz * dz);
  101152. if (len == 0) break;
  101153. len = r1 / len;
  101154. dx *= len;
  101155. dy *= len;
  101156. dz *= len;
  101157. tx = c1x + dx;
  101158. ty = c1y + dy;
  101159. tz = c1z + dz;
  101160. if (dot < -0.96 || dot > 0.96) {
  101161. r00 = n1x * n1x * 1.5 - 0.5;
  101162. r01 = n1x * n1y * 1.5 - n1z * 0.866025403;
  101163. r02 = n1x * n1z * 1.5 + n1y * 0.866025403;
  101164. r10 = n1y * n1x * 1.5 + n1z * 0.866025403;
  101165. r11 = n1y * n1y * 1.5 - 0.5;
  101166. r12 = n1y * n1z * 1.5 - n1x * 0.866025403;
  101167. r20 = n1z * n1x * 1.5 - n1y * 0.866025403;
  101168. r21 = n1z * n1y * 1.5 + n1x * 0.866025403;
  101169. r22 = n1z * n1z * 1.5 - 0.5;
  101170. px = tx;
  101171. py = ty;
  101172. pz = tz;
  101173. pd = nx * (px - c2x) + ny * (py - c2y) + nz * (pz - c2z);
  101174. tx = px - pd * nx - c2x;
  101175. ty = py - pd * ny - c2y;
  101176. tz = pz - pd * nz - c2z;
  101177. len = tx * tx + ty * ty + tz * tz;
  101178. if (len > r2 * r2) {
  101179. len = r2 / OIMO.sqrt(len);
  101180. tx *= len;
  101181. ty *= len;
  101182. tz *= len;
  101183. }
  101184. px = c2x + tx;
  101185. py = c2y + ty;
  101186. pz = c2z + tz;
  101187. manifold.addPoint(px, py, pz, -nx, -ny, -nz, pd, false);
  101188. px = dx * r00 + dy * r01 + dz * r02;
  101189. py = dx * r10 + dy * r11 + dz * r12;
  101190. pz = dx * r20 + dy * r21 + dz * r22;
  101191. px = (dx = px) + c1x;
  101192. py = (dy = py) + c1y;
  101193. pz = (dz = pz) + c1z;
  101194. pd = nx * (px - c2x) + ny * (py - c2y) + nz * (pz - c2z);
  101195. if (pd <= 0) {
  101196. tx = px - pd * nx - c2x;
  101197. ty = py - pd * ny - c2y;
  101198. tz = pz - pd * nz - c2z;
  101199. len = tx * tx + ty * ty + tz * tz;
  101200. if (len > r2 * r2) {
  101201. len = r2 / OIMO.sqrt(len);
  101202. tx *= len;
  101203. ty *= len;
  101204. tz *= len;
  101205. }
  101206. px = c2x + tx;
  101207. py = c2y + ty;
  101208. pz = c2z + tz;
  101209. manifold.addPoint(px, py, pz, -nx, -ny, -nz, pd, false);
  101210. }
  101211. px = dx * r00 + dy * r01 + dz * r02;
  101212. py = dx * r10 + dy * r11 + dz * r12;
  101213. pz = dx * r20 + dy * r21 + dz * r22;
  101214. px = (dx = px) + c1x;
  101215. py = (dy = py) + c1y;
  101216. pz = (dz = pz) + c1z;
  101217. pd = nx * (px - c2x) + ny * (py - c2y) + nz * (pz - c2z);
  101218. if (pd <= 0) {
  101219. tx = px - pd * nx - c2x;
  101220. ty = py - pd * ny - c2y;
  101221. tz = pz - pd * nz - c2z;
  101222. len = tx * tx + ty * ty + tz * tz;
  101223. if (len > r2 * r2) {
  101224. len = r2 / OIMO.sqrt(len);
  101225. tx *= len;
  101226. ty *= len;
  101227. tz *= len;
  101228. }
  101229. px = c2x + tx;
  101230. py = c2y + ty;
  101231. pz = c2z + tz;
  101232. manifold.addPoint(px, py, pz, -nx, -ny, -nz, pd, false);
  101233. }
  101234. } else {
  101235. sx = tx;
  101236. sy = ty;
  101237. sz = tz;
  101238. depth1 = nx * (sx - c2x) + ny * (sy - c2y) + nz * (sz - c2z);
  101239. sx -= depth1 * nx;
  101240. sy -= depth1 * ny;
  101241. sz -= depth1 * nz;
  101242. if (dot > 0) {
  101243. ex = tx + n1x * h1 * 2;
  101244. ey = ty + n1y * h1 * 2;
  101245. ez = tz + n1z * h1 * 2;
  101246. } else {
  101247. ex = tx - n1x * h1 * 2;
  101248. ey = ty - n1y * h1 * 2;
  101249. ez = tz - n1z * h1 * 2;
  101250. }
  101251. depth2 = nx * (ex - c2x) + ny * (ey - c2y) + nz * (ez - c2z);
  101252. ex -= depth2 * nx;
  101253. ey -= depth2 * ny;
  101254. ez -= depth2 * nz;
  101255. dx = c2x - sx;
  101256. dy = c2y - sy;
  101257. dz = c2z - sz;
  101258. tx = ex - sx;
  101259. ty = ey - sy;
  101260. tz = ez - sz;
  101261. a = dx * dx + dy * dy + dz * dz;
  101262. b = dx * tx + dy * ty + dz * tz;
  101263. e = tx * tx + ty * ty + tz * tz;
  101264. f = b * b - e * (a - r2 * r2);
  101265. if (f < 0) break;
  101266. f = OIMO.sqrt(f);
  101267. t1 = (b + f) / e;
  101268. t2 = (b - f) / e;
  101269. if (t2 < t1) {
  101270. len = t1;
  101271. t1 = t2;
  101272. t2 = len;
  101273. }
  101274. if (t2 > 1) t2 = 1;
  101275. if (t1 < 0) t1 = 0;
  101276. tx = sx + (ex - sx) * t1;
  101277. ty = sy + (ey - sy) * t1;
  101278. tz = sz + (ez - sz) * t1;
  101279. ex = sx + (ex - sx) * t2;
  101280. ey = sy + (ey - sy) * t2;
  101281. ez = sz + (ez - sz) * t2;
  101282. sx = tx;
  101283. sy = ty;
  101284. sz = tz;
  101285. len = depth1 + (depth2 - depth1) * t1;
  101286. depth2 = depth1 + (depth2 - depth1) * t2;
  101287. depth1 = len;
  101288. if (depth1 < 0) {
  101289. manifold.addPoint(sx, sy, sz, -nx, -ny, -nz, depth1, false);
  101290. }
  101291. if (depth2 < 0) {
  101292. manifold.addPoint(ex, ey, ez, -nx, -ny, -nz, depth2, false);
  101293. }
  101294. }
  101295. break;
  101296. }
  101297. };
  101298. OIMO.SphereCylinderCollisionDetector = function (flip) {
  101299. OIMO.CollisionDetector.call(this);
  101300. this.flip = flip;
  101301. };
  101302. OIMO.SphereCylinderCollisionDetector.prototype = Object.create(OIMO.CollisionDetector.prototype);
  101303. OIMO.SphereCylinderCollisionDetector.prototype.constructor = OIMO.SphereCylinderCollisionDetector;
  101304. OIMO.SphereCylinderCollisionDetector.prototype.detectCollision = function (shape1, shape2, manifold) {
  101305. var s;
  101306. var c;
  101307. if (this.flip) {
  101308. s = shape2;
  101309. c = shape1;
  101310. } else {
  101311. s = shape1;
  101312. c = shape2;
  101313. }
  101314. var ps = s.position;
  101315. var psx = ps.x;
  101316. var psy = ps.y;
  101317. var psz = ps.z;
  101318. var pc = c.position;
  101319. var pcx = pc.x;
  101320. var pcy = pc.y;
  101321. var pcz = pc.z;
  101322. var dirx = c.normalDirection.x;
  101323. var diry = c.normalDirection.y;
  101324. var dirz = c.normalDirection.z;
  101325. var rads = s.radius;
  101326. var radc = c.radius;
  101327. var rad2 = rads + radc;
  101328. var halfh = c.halfHeight;
  101329. var dx = psx - pcx;
  101330. var dy = psy - pcy;
  101331. var dz = psz - pcz;
  101332. var dot = dx * dirx + dy * diry + dz * dirz;
  101333. if (dot < -halfh - rads || dot > halfh + rads) return;
  101334. var cx = pcx + dot * dirx;
  101335. var cy = pcy + dot * diry;
  101336. var cz = pcz + dot * dirz;
  101337. var d2x = psx - cx;
  101338. var d2y = psy - cy;
  101339. var d2z = psz - cz;
  101340. var len = d2x * d2x + d2y * d2y + d2z * d2z;
  101341. if (len > rad2 * rad2) return;
  101342. if (len > radc * radc) {
  101343. len = radc / OIMO.sqrt(len);
  101344. d2x *= len;
  101345. d2y *= len;
  101346. d2z *= len;
  101347. }
  101348. if (dot < -halfh) dot = -halfh;
  101349. else if (dot > halfh) dot = halfh;
  101350. cx = pcx + dot * dirx + d2x;
  101351. cy = pcy + dot * diry + d2y;
  101352. cz = pcz + dot * dirz + d2z;
  101353. dx = cx - psx;
  101354. dy = cy - psy;
  101355. dz = cz - psz;
  101356. len = dx * dx + dy * dy + dz * dz;
  101357. var invLen;
  101358. if (len > 0 && len < rads * rads) {
  101359. len = OIMO.sqrt(len);
  101360. invLen = 1 / len;
  101361. dx *= invLen;
  101362. dy *= invLen;
  101363. dz *= invLen;
  101364. ///result.addContactInfo(psx+dx*rads,psy+dy*rads,psz+dz*rads,dx,dy,dz,len-rads,s,c,0,0,false);
  101365. manifold.addPoint(psx + dx * rads, psy + dy * rads, psz + dz * rads, dx, dy, dz, len - rads, this.flip);
  101366. }
  101367. };
  101368. /**
  101369. * Class for checking collisions between 2 tetras,
  101370. * a shape that is made with 4 vertices and 4 faces
  101371. * arranged in triangles. With this algorigthm, soft
  101372. * body physics are possible and easier to implement.
  101373. * @author xprogram
  101374. */
  101375. OIMO.TetraTetraCollisionDetector = function () {
  101376. OIMO.CollisionDetector.call(this);
  101377. };
  101378. OIMO.TetraTetraCollisionDetector.prototype = Object.create(OIMO.CollisionDetector.prototype);
  101379. OIMO.TetraTetraCollisionDetector.prototype.constructor = OIMO.TetraTetraCollisionDetector;
  101380. OIMO.TetraTetraCollisionDetector.prototype.detectCollision = function (tet1, tet2, manifold) {
  101381. /*
  101382. * What we are doing:
  101383. * Each tetra is represented by four 3D triangles. The only
  101384. * quick way of finding if another tetra is within the other
  101385. * tetra is to see if a single vertex is within the triangles
  101386. * of the other tetra. So, for example, a tetra is represented
  101387. * by points B, C, D and E with triangles BCD, BCE, DCE and BDE.
  101388. * There is another tetra with a vertex A which was detected for
  101389. * collision by the broadphase. Now, if the point A is between ALL
  101390. * triangles of the other tetra (BCD, BCE, etc.) then the collision
  101391. * is valid and we can pass point A to the manifold. Since the only
  101392. * points on the tetra are the 4 vertices, collision detection is
  101393. * not so complex. However, it can be time-consuming because we
  101394. * need to split the 3D triangles into three 2D triangles each for
  101395. * collision detection.
  101396. */
  101397. var i, j, vec, fs1 = tet1.faces, vs1 = tet1.verts, fs2 = tet2.faces, vs2 = tet2.verts;
  101398. var j1, j2, j3, ts = 0; // Triangle vertices `j1`, `j2` and `j3`
  101399. // fs is undeclared
  101400. var fs = fs1;
  101401. for (i = 0; i < 4; i++) {
  101402. vec = vs1[i];
  101403. for (j = 0; j < 4; j++) {
  101404. j1 = vs2[fs[i].a];
  101405. j2 = vs2[fs[i].b];
  101406. j3 = vs2[fs[i].c];
  101407. if (
  101408. tricheck(pt(vec.x, vec.y), pt(j1.x, j1.y), pt(j2.x, j2.y), pt(j3.x, j3.y)) &&
  101409. tricheck(pt(vec.x, vec.z), pt(j1.x, j1.z), pt(j2.x, j2.z), pt(j3.x, j3.z)) &&
  101410. tricheck(pt(vec.z, vec.y), pt(j1.z, j1.y), pt(j2.z, j2.y), pt(j3.z, j3.y))
  101411. )
  101412. ts++;
  101413. if (ts === 4) // Only add point if it is inside all 4 triangles
  101414. manifold.addPoint(vec);
  101415. }
  101416. }
  101417. };
  101418. // Taken from: http://jsfiddle.net/PerroAZUL/zdaY8/1/
  101419. function tricheck(p, p0, p1, p2) {
  101420. var A = 0.5 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  101421. var sg = A < 0 ? -1 : 1;
  101422. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sg;
  101423. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sg;
  101424. return s > 0 && t > 0 && (s + t) < 2 * A * sg;
  101425. }
  101426. function pt(x, y) { return { x: x, y: y }; }
  101427. /**
  101428. * An axis-aligned bounding box.
  101429. * @author saharan
  101430. * @author lo-th
  101431. */
  101432. OIMO.AABB = function (minX, maxX, minY, maxY, minZ, maxZ) {
  101433. this.elements = new OIMO_ARRAY_TYPE(6);
  101434. var te = this.elements;
  101435. te[0] = minX || 0; te[1] = minY || 0; te[2] = minZ || 0;
  101436. te[3] = maxX || 0; te[4] = maxY || 0; te[5] = maxZ || 0;
  101437. };
  101438. OIMO.AABB.prototype = {
  101439. constructor: OIMO.AABB,
  101440. set: function (minX, maxX, minY, maxY, minZ, maxZ) {
  101441. var te = this.elements;
  101442. te[0] = minX; te[3] = maxX;
  101443. te[1] = minY; te[4] = maxY;
  101444. te[2] = minZ; te[5] = maxZ;
  101445. return this;
  101446. },
  101447. intersectTest: function (aabb) {
  101448. var te = this.elements;
  101449. var ue = aabb.elements;
  101450. 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];
  101451. },
  101452. intersectTestTwo: function (aabb) {
  101453. var te = this.elements;
  101454. var ue = aabb.elements;
  101455. 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];
  101456. },
  101457. clone: function () {
  101458. return new this.constructor().fromArray(this.elements);
  101459. },
  101460. copy: function (aabb, margin) {
  101461. var m = margin || 0;
  101462. var me = aabb.elements;
  101463. this.set(me[0] - m, me[3] + m, me[1] - m, me[4] + m, me[2] - m, me[5] + m);
  101464. return this;
  101465. },
  101466. fromArray: function (array) {
  101467. this.elements.set(array);
  101468. return this;
  101469. },
  101470. // Set this AABB to the combined AABB of aabb1 and aabb2.
  101471. combine: function (aabb1, aabb2) {
  101472. var a = aabb1.elements;
  101473. var b = aabb2.elements;
  101474. var te = this.elements;
  101475. te[0] = a[0] < b[0] ? a[0] : b[0];
  101476. te[1] = a[1] < b[1] ? a[1] : b[1];
  101477. te[2] = a[2] < b[2] ? a[2] : b[2];
  101478. te[3] = a[3] > b[3] ? a[3] : b[3];
  101479. te[4] = a[4] > b[4] ? a[4] : b[4];
  101480. te[5] = a[5] > b[5] ? a[5] : b[5];
  101481. return this;
  101482. },
  101483. // Get the surface area.
  101484. surfaceArea: function () {
  101485. var te = this.elements;
  101486. var a = te[3] - te[0];
  101487. var h = te[4] - te[1];
  101488. var d = te[5] - te[2];
  101489. return 2 * (a * (h + d) + h * d);
  101490. },
  101491. // Get whether the AABB intersects with the point or not.
  101492. intersectsWithPoint: function (x, y, z) {
  101493. var te = this.elements;
  101494. return x >= te[0] && x <= te[3] && y >= te[1] && y <= te[4] && z >= te[2] && z <= te[5];
  101495. },
  101496. /**
  101497. * Set the AABB from an array
  101498. * of vertices. From THREE.
  101499. * @author mrdoob
  101500. * @author xprogram
  101501. */
  101502. setFromPoints: function (arr) {
  101503. this.makeEmpty();
  101504. for (var i = 0; i < arr.length; i++) {
  101505. this.expandByPoint(arr[i]);
  101506. }
  101507. },
  101508. makeEmpty: function () {
  101509. this.set(-Infinity, -Infinity, -Infinity, Infinity, Infinity, Infinity);
  101510. },
  101511. expandByPoint: function (pt) {
  101512. var te = this.elements;
  101513. this.set(
  101514. OIMO.min(te[0], pt.x), OIMO.min(te[1], pt.y), OIMO.min(te[2], pt.z),
  101515. OIMO.max(te[3], pt.x), OIMO.max(te[4], pt.y), OIMO.max(te[5], pt.z)
  101516. );
  101517. }
  101518. };
  101519. /**
  101520. * A proxy is used for broad-phase collecting pairs that can be colliding.
  101521. */
  101522. OIMO.Proxy = function (shape) {
  101523. // The parent shape.
  101524. this.shape = shape;
  101525. // The axis-aligned bounding box.
  101526. this.aabb = shape.aabb;
  101527. };
  101528. OIMO.Proxy.prototype = {
  101529. constructor: OIMO.Proxy,
  101530. // Update the proxy.
  101531. update: function () {
  101532. OIMO.Error("Proxy", "Inheritance error.");
  101533. }
  101534. };
  101535. /**
  101536. * A basic implementation of proxies.
  101537. * @author saharan
  101538. */
  101539. OIMO.BasicProxy = function (shape) {
  101540. OIMO.Proxy.call(this, shape);
  101541. this.id = OIMO.proxyID++;
  101542. };
  101543. OIMO.BasicProxy.prototype = Object.create(OIMO.Proxy.prototype);
  101544. OIMO.BasicProxy.prototype.constructor = OIMO.BasicProxy;
  101545. OIMO.BasicProxy.prototype.update = function () {
  101546. };
  101547. /**
  101548. * The broad-phase is used for collecting all possible pairs for collision.
  101549. */
  101550. OIMO.BroadPhase = function () {
  101551. this.types = OIMO.BR_NULL;
  101552. this.numPairChecks = 0;
  101553. this.numPairs = 0;
  101554. this.pairs = [];
  101555. };
  101556. OIMO.BroadPhase.prototype = {
  101557. constructor: OIMO.BroadPhase,
  101558. /**
  101559. * Create a new proxy.
  101560. * @param shape
  101561. * @return
  101562. */
  101563. createProxy: function (shape) {
  101564. OIMO.Error("BroadPhase", "Inheritance error.");
  101565. },
  101566. /**
  101567. * Add the proxy into the broad-phase.
  101568. * @param proxy
  101569. */
  101570. addProxy: function (proxy) {
  101571. OIMO.Error("BroadPhase", "Inheritance error.");
  101572. },
  101573. /**
  101574. * Remove the proxy from the broad-phase.
  101575. * @param proxy
  101576. */
  101577. removeProxy: function (proxy) {
  101578. OIMO.Error("BroadPhase", "Inheritance error.");
  101579. },
  101580. /**
  101581. * Returns whether the pair is available or not.
  101582. * @param s1
  101583. * @param s2
  101584. * @return
  101585. */
  101586. isAvailablePair: function (s1, s2) {
  101587. var b1 = s1.parent;
  101588. var b2 = s2.parent;
  101589. if (b1 == b2 || // same parents
  101590. (!b1.isDynamic && !b2.isDynamic) || // static or kinematic object
  101591. (s1.belongsTo & s2.collidesWith) == 0 ||
  101592. (s2.belongsTo & s1.collidesWith) == 0 // collision filtering
  101593. ) { return false; }
  101594. var js;
  101595. if (b1.numJoints < b2.numJoints) js = b1.jointLink;
  101596. else js = b2.jointLink;
  101597. while (js !== null) {
  101598. var joint = js.joint;
  101599. if (!joint.allowCollision && ((joint.body1 == b1 && joint.body2 == b2) || (joint.body1 == b2 && joint.body2 == b1))) { return false; }
  101600. js = js.next;
  101601. }
  101602. return true;
  101603. },
  101604. // Detect overlapping pairs.
  101605. detectPairs: function () {
  101606. // clear old
  101607. this.pairs = [];
  101608. this.numPairs = 0;
  101609. this.numPairChecks = 0;
  101610. this.collectPairs();
  101611. },
  101612. collectPairs: function () {
  101613. OIMO.Error("BroadPhase", "Inheritance error.");
  101614. },
  101615. addPair: function (s1, s2) {
  101616. var pair = new OIMO.Pair(s1, s2);
  101617. this.pairs.push(pair);
  101618. this.numPairs++;
  101619. }
  101620. };
  101621. /**
  101622. * A broad-phase algorithm with brute-force search.
  101623. * This always checks for all possible pairs.
  101624. */
  101625. OIMO.BruteForceBroadPhase = function () {
  101626. OIMO.BroadPhase.call(this);
  101627. this.types = OIMO.BR_BRUTE_FORCE;;
  101628. //this.numProxies=0;
  101629. ///this.maxProxies = 256;
  101630. this.proxies = [];
  101631. //this.proxies.length = 256;
  101632. };
  101633. OIMO.BruteForceBroadPhase.prototype = Object.create(OIMO.BroadPhase.prototype);
  101634. OIMO.BruteForceBroadPhase.prototype.constructor = OIMO.BruteForceBroadPhase;
  101635. OIMO.BruteForceBroadPhase.prototype.createProxy = function (shape) {
  101636. return new OIMO.BasicProxy(shape);
  101637. };
  101638. OIMO.BruteForceBroadPhase.prototype.addProxy = function (proxy) {
  101639. /*if(this.numProxies==this.maxProxies){
  101640. //this.maxProxies<<=1;
  101641. this.maxProxies*=2;
  101642. var newProxies=[];
  101643. newProxies.length = this.maxProxies;
  101644. var i = this.numProxies;
  101645. while(i--){
  101646. //for(var i=0, l=this.numProxies;i<l;i++){
  101647. newProxies[i]=this.proxies[i];
  101648. }
  101649. this.proxies=newProxies;
  101650. }*/
  101651. //this.proxies[this.numProxies++] = proxy;
  101652. this.proxies.push(proxy);
  101653. //this.numProxies++;
  101654. };
  101655. OIMO.BruteForceBroadPhase.prototype.removeProxy = function (proxy) {
  101656. var n = this.proxies.indexOf(proxy);
  101657. if (n > -1) {
  101658. this.proxies.splice(n, 1);
  101659. //this.numProxies--;
  101660. }
  101661. /*var i = this.numProxies;
  101662. while(i--){
  101663. //for(var i=0, l=this.numProxies;i<l;i++){
  101664. if(this.proxies[i] == proxy){
  101665. this.proxies[i] = this.proxies[--this.numProxies];
  101666. this.proxies[this.numProxies] = null;
  101667. return;
  101668. }
  101669. }*/
  101670. };
  101671. OIMO.BruteForceBroadPhase.prototype.collectPairs = function () {
  101672. var i = 0, j, p1, p2;
  101673. var px = this.proxies;
  101674. var l = px.length;//this.numProxies;
  101675. //var ar1 = [];
  101676. //var ar2 = [];
  101677. //for( i = px.length ; i-- ; ar1[ i ] = px[ i ] ){};
  101678. //for( i = px.length ; i-- ; ar2[ i ] = px[ i ] ){};
  101679. //var ar1 = JSON.parse(JSON.stringify(this.proxies))
  101680. //var ar2 = JSON.parse(JSON.stringify(this.proxies))
  101681. this.numPairChecks = l * (l - 1) >> 1;
  101682. //this.numPairChecks=this.numProxies*(this.numProxies-1)*0.5;
  101683. while (i < l) {
  101684. p1 = px[i++];
  101685. j = i + 1;
  101686. while (j < l) {
  101687. p2 = px[j++];
  101688. if (p1.aabb.intersectTest(p2.aabb) || !this.isAvailablePair(p1.shape, p2.shape)) continue;
  101689. this.addPair(p1.shape, p2.shape);
  101690. }
  101691. }
  101692. };
  101693. /**
  101694. * A pair of shapes that may collide.
  101695. * @author saharan
  101696. */
  101697. OIMO.Pair = function (s1, s2) {
  101698. // The first shape.
  101699. this.shape1 = s1 || null;
  101700. // The second shape.
  101701. this.shape2 = s2 || null;
  101702. };
  101703. /**
  101704. * A projection axis for sweep and prune broad-phase.
  101705. * @author saharan
  101706. */
  101707. OIMO.SAPAxis = function () {
  101708. this.numElements = 0;
  101709. this.bufferSize = 256;
  101710. this.elements = [];
  101711. this.elements.length = this.bufferSize;
  101712. this.stack = new OIMO_ARRAY_TYPE(64);
  101713. };
  101714. OIMO.SAPAxis.prototype = {
  101715. constructor: OIMO.SAPAxis,
  101716. addElements: function (min, max) {
  101717. if (this.numElements + 2 >= this.bufferSize) {
  101718. //this.bufferSize<<=1;
  101719. this.bufferSize *= 2;
  101720. var newElements = [];
  101721. var i = this.numElements;
  101722. while (i--) {
  101723. //for(var i=0, l=this.numElements; i<l; i++){
  101724. newElements[i] = this.elements[i];
  101725. }
  101726. }
  101727. this.elements[this.numElements++] = min;
  101728. this.elements[this.numElements++] = max;
  101729. },
  101730. removeElements: function (min, max) {
  101731. var minIndex = -1;
  101732. var maxIndex = -1;
  101733. for (var i = 0, l = this.numElements; i < l; i++) {
  101734. var e = this.elements[i];
  101735. if (e == min || e == max) {
  101736. if (minIndex == -1) {
  101737. minIndex = i;
  101738. } else {
  101739. maxIndex = i;
  101740. break;
  101741. }
  101742. }
  101743. }
  101744. for (i = minIndex + 1, l = maxIndex; i < l; i++) {
  101745. this.elements[i - 1] = this.elements[i];
  101746. }
  101747. for (i = maxIndex + 1, l = this.numElements; i < l; i++) {
  101748. this.elements[i - 2] = this.elements[i];
  101749. }
  101750. this.elements[--this.numElements] = null;
  101751. this.elements[--this.numElements] = null;
  101752. },
  101753. sort: function () {
  101754. var count = 0;
  101755. var threshold = 1;
  101756. while ((this.numElements >> threshold) != 0) threshold++;
  101757. threshold = threshold * this.numElements >> 2;
  101758. count = 0;
  101759. var giveup = false;
  101760. var elements = this.elements;
  101761. for (var i = 1, l = this.numElements; i < l; i++) { // try insertion sort
  101762. var tmp = elements[i];
  101763. var pivot = tmp.value;
  101764. var tmp2 = elements[i - 1];
  101765. if (tmp2.value > pivot) {
  101766. var j = i;
  101767. do {
  101768. elements[j] = tmp2;
  101769. if (--j == 0) break;
  101770. tmp2 = elements[j - 1];
  101771. } while (tmp2.value > pivot);
  101772. elements[j] = tmp;
  101773. count += i - j;
  101774. if (count > threshold) {
  101775. giveup = true; // stop and use quick sort
  101776. break;
  101777. }
  101778. }
  101779. }
  101780. if (!giveup) return;
  101781. count = 2; var stack = this.stack;
  101782. stack[0] = 0;
  101783. stack[1] = this.numElements - 1;
  101784. while (count > 0) {
  101785. var right = stack[--count];
  101786. var left = stack[--count];
  101787. var diff = right - left;
  101788. if (diff > 16) { // quick sort
  101789. //var mid=left+(diff>>1);
  101790. var mid = left + (OIMO.floor(diff * 0.5));
  101791. tmp = elements[mid];
  101792. elements[mid] = elements[right];
  101793. elements[right] = tmp;
  101794. pivot = tmp.value;
  101795. i = left - 1;
  101796. j = right;
  101797. while (true) {
  101798. var ei;
  101799. var ej;
  101800. do { ei = elements[++i]; } while (ei.value < pivot);
  101801. do { ej = elements[--j]; } while (pivot < ej.value && j != left);
  101802. if (i >= j) break;
  101803. elements[i] = ej;
  101804. elements[j] = ei;
  101805. }
  101806. elements[right] = elements[i];
  101807. elements[i] = tmp;
  101808. if (i - left > right - i) {
  101809. stack[count++] = left;
  101810. stack[count++] = i - 1;
  101811. stack[count++] = i + 1;
  101812. stack[count++] = right;
  101813. } else {
  101814. stack[count++] = i + 1;
  101815. stack[count++] = right;
  101816. stack[count++] = left;
  101817. stack[count++] = i - 1;
  101818. }
  101819. } else {
  101820. for (i = left + 1; i <= right; i++) {
  101821. tmp = elements[i];
  101822. pivot = tmp.value;
  101823. tmp2 = elements[i - 1];
  101824. if (tmp2.value > pivot) {
  101825. j = i;
  101826. do {
  101827. elements[j] = tmp2;
  101828. if (--j == 0) break;
  101829. tmp2 = elements[j - 1];
  101830. } while (tmp2.value > pivot);
  101831. elements[j] = tmp;
  101832. }
  101833. }
  101834. }
  101835. }
  101836. },
  101837. calculateTestCount: function () {
  101838. var num = 1;
  101839. var sum = 0;
  101840. for (var i = 1, l = this.numElements; i < l; i++) {
  101841. if (this.elements[i].max) {
  101842. num--;
  101843. } else {
  101844. sum += num;
  101845. num++;
  101846. }
  101847. }
  101848. return sum;
  101849. }
  101850. }
  101851. /**
  101852. * A broad-phase collision detection algorithm using sweep and prune.
  101853. * @author saharan
  101854. * @author lo-th
  101855. */
  101856. OIMO.SAPBroadPhase = function () {
  101857. OIMO.BroadPhase.call(this);
  101858. this.types = OIMO.BR_SWEEP_AND_PRUNE;
  101859. this.numElementsD = 0;
  101860. this.numElementsS = 0;
  101861. // dynamic proxies
  101862. this.axesD = [
  101863. new OIMO.SAPAxis(),
  101864. new OIMO.SAPAxis(),
  101865. new OIMO.SAPAxis()
  101866. ];
  101867. // static or sleeping proxies
  101868. this.axesS = [
  101869. new OIMO.SAPAxis(),
  101870. new OIMO.SAPAxis(),
  101871. new OIMO.SAPAxis()
  101872. ];
  101873. this.index1 = 0;
  101874. this.index2 = 1;
  101875. };
  101876. OIMO.SAPBroadPhase.prototype = Object.create(OIMO.BroadPhase.prototype);
  101877. OIMO.SAPBroadPhase.prototype.constructor = OIMO.SAPBroadPhase;
  101878. OIMO.SAPBroadPhase.prototype.createProxy = function (shape) {
  101879. return new OIMO.SAPProxy(this, shape);
  101880. };
  101881. OIMO.SAPBroadPhase.prototype.addProxy = function (proxy) {
  101882. var p = proxy;
  101883. if (p.isDynamic()) {
  101884. this.axesD[0].addElements(p.min[0], p.max[0]);
  101885. this.axesD[1].addElements(p.min[1], p.max[1]);
  101886. this.axesD[2].addElements(p.min[2], p.max[2]);
  101887. p.belongsTo = 1;
  101888. this.numElementsD += 2;
  101889. } else {
  101890. this.axesS[0].addElements(p.min[0], p.max[0]);
  101891. this.axesS[1].addElements(p.min[1], p.max[1]);
  101892. this.axesS[2].addElements(p.min[2], p.max[2]);
  101893. p.belongsTo = 2;
  101894. this.numElementsS += 2;
  101895. }
  101896. };
  101897. OIMO.SAPBroadPhase.prototype.removeProxy = function (proxy) {
  101898. var p = proxy;
  101899. if (p.belongsTo == 0) return;
  101900. /*else if ( p.belongsTo == 1 ) {
  101901. this.axesD[0].removeElements( p.min[0], p.max[0] );
  101902. this.axesD[1].removeElements( p.min[1], p.max[1] );
  101903. this.axesD[2].removeElements( p.min[2], p.max[2] );
  101904. this.numElementsD -= 2;
  101905. } else if ( p.belongsTo == 2 ) {
  101906. this.axesS[0].removeElements( p.min[0], p.max[0] );
  101907. this.axesS[1].removeElements( p.min[1], p.max[1] );
  101908. this.axesS[2].removeElements( p.min[2], p.max[2] );
  101909. this.numElementsS -= 2;
  101910. }*/
  101911. switch (p.belongsTo) {
  101912. case 1:
  101913. this.axesD[0].removeElements(p.min[0], p.max[0]);
  101914. this.axesD[1].removeElements(p.min[1], p.max[1]);
  101915. this.axesD[2].removeElements(p.min[2], p.max[2]);
  101916. this.numElementsD -= 2;
  101917. break;
  101918. case 2:
  101919. this.axesS[0].removeElements(p.min[0], p.max[0]);
  101920. this.axesS[1].removeElements(p.min[1], p.max[1]);
  101921. this.axesS[2].removeElements(p.min[2], p.max[2]);
  101922. this.numElementsS -= 2;
  101923. break;
  101924. }
  101925. p.belongsTo = 0;
  101926. };
  101927. OIMO.SAPBroadPhase.prototype.collectPairs = function () {
  101928. if (this.numElementsD == 0) return;
  101929. var axis1 = this.axesD[this.index1];
  101930. var axis2 = this.axesD[this.index2];
  101931. axis1.sort();
  101932. axis2.sort();
  101933. var count1 = axis1.calculateTestCount();
  101934. var count2 = axis2.calculateTestCount();
  101935. var elementsD;
  101936. var elementsS;
  101937. if (count1 <= count2) {// select the best axis
  101938. axis2 = this.axesS[this.index1];
  101939. axis2.sort();
  101940. elementsD = axis1.elements;
  101941. elementsS = axis2.elements;
  101942. } else {
  101943. axis1 = this.axesS[this.index2];
  101944. axis1.sort();
  101945. elementsD = axis2.elements;
  101946. elementsS = axis1.elements;
  101947. this.index1 ^= this.index2;
  101948. this.index2 ^= this.index1;
  101949. this.index1 ^= this.index2;
  101950. }
  101951. var activeD;
  101952. var activeS;
  101953. var p = 0;
  101954. var q = 0;
  101955. while (p < this.numElementsD) {
  101956. var e1;
  101957. var dyn;
  101958. if (q == this.numElementsS) {
  101959. e1 = elementsD[p];
  101960. dyn = true;
  101961. p++;
  101962. } else {
  101963. var d = elementsD[p];
  101964. var s = elementsS[q];
  101965. if (d.value < s.value) {
  101966. e1 = d;
  101967. dyn = true;
  101968. p++;
  101969. } else {
  101970. e1 = s;
  101971. dyn = false;
  101972. q++;
  101973. }
  101974. }
  101975. if (!e1.max) {
  101976. var s1 = e1.proxy.shape;
  101977. var min1 = e1.min1.value;
  101978. var max1 = e1.max1.value;
  101979. var min2 = e1.min2.value;
  101980. var max2 = e1.max2.value;
  101981. for (var e2 = activeD; e2 != null; e2 = e2.pair) {// test for dynamic
  101982. var s2 = e2.proxy.shape;
  101983. this.numPairChecks++;
  101984. if (min1 > e2.max1.value || max1 < e2.min1.value || min2 > e2.max2.value || max2 < e2.min2.value || !this.isAvailablePair(s1, s2)) continue;
  101985. this.addPair(s1, s2);
  101986. }
  101987. if (dyn) {
  101988. for (e2 = activeS; e2 != null; e2 = e2.pair) {// test for static
  101989. s2 = e2.proxy.shape;
  101990. this.numPairChecks++;
  101991. if (min1 > e2.max1.value || max1 < e2.min1.value || min2 > e2.max2.value || max2 < e2.min2.value || !this.isAvailablePair(s1, s2)) continue;
  101992. this.addPair(s1, s2);
  101993. }
  101994. e1.pair = activeD;
  101995. activeD = e1;
  101996. } else {
  101997. e1.pair = activeS;
  101998. activeS = e1;
  101999. }
  102000. } else {
  102001. var min = e1.pair;
  102002. if (dyn) {
  102003. if (min == activeD) {
  102004. activeD = activeD.pair;
  102005. continue;
  102006. } else {
  102007. e1 = activeD;
  102008. }
  102009. } else {
  102010. if (min == activeS) {
  102011. activeS = activeS.pair;
  102012. continue;
  102013. } else {
  102014. e1 = activeS;
  102015. }
  102016. }
  102017. do {
  102018. e2 = e1.pair;
  102019. if (e2 == min) {
  102020. e1.pair = e2.pair;
  102021. break;
  102022. }
  102023. e1 = e2;
  102024. } while (e1 != null);
  102025. }
  102026. }
  102027. this.index2 = (this.index1 | this.index2) ^ 3;
  102028. };
  102029. /**
  102030. * An element of proxies.
  102031. * @author saharan
  102032. */
  102033. OIMO.SAPElement = function (proxy, max) {
  102034. // The parent proxy
  102035. this.proxy = proxy;
  102036. // The pair element.
  102037. this.pair = null;
  102038. // The minimum element on other axis.
  102039. this.min1 = null;
  102040. // The maximum element on other axis.
  102041. this.max1 = null;
  102042. // The minimum element on other axis.
  102043. this.min2 = null;
  102044. // The maximum element on other axis.
  102045. this.max2 = null;
  102046. // Whether the element has maximum value or not.
  102047. this.max = max;
  102048. // The value of the element.
  102049. this.value = 0;
  102050. };
  102051. /**
  102052. * A proxy for sweep and prune broad-phase.
  102053. * @author saharan
  102054. * @author lo-th
  102055. */
  102056. OIMO.SAPProxy = function (sap, shape) {
  102057. OIMO.Proxy.call(this, shape);
  102058. // Type of the axis to which the proxy belongs to. [0:none, 1:dynamic, 2:static]
  102059. this.belongsTo = 0;
  102060. // The maximum elements on each axis.
  102061. this.max = [];
  102062. // The minimum elements on each axis.
  102063. this.min = [];
  102064. this.sap = sap;
  102065. this.min[0] = new OIMO.SAPElement(this, false);
  102066. this.max[0] = new OIMO.SAPElement(this, true);
  102067. this.min[1] = new OIMO.SAPElement(this, false);
  102068. this.max[1] = new OIMO.SAPElement(this, true);
  102069. this.min[2] = new OIMO.SAPElement(this, false);
  102070. this.max[2] = new OIMO.SAPElement(this, true);
  102071. this.max[0].pair = this.min[0];
  102072. this.max[1].pair = this.min[1];
  102073. this.max[2].pair = this.min[2];
  102074. this.min[0].min1 = this.min[1];
  102075. this.min[0].max1 = this.max[1];
  102076. this.min[0].min2 = this.min[2];
  102077. this.min[0].max2 = this.max[2];
  102078. this.min[1].min1 = this.min[0];
  102079. this.min[1].max1 = this.max[0];
  102080. this.min[1].min2 = this.min[2];
  102081. this.min[1].max2 = this.max[2];
  102082. this.min[2].min1 = this.min[0];
  102083. this.min[2].max1 = this.max[0];
  102084. this.min[2].min2 = this.min[1];
  102085. this.min[2].max2 = this.max[1];
  102086. };
  102087. OIMO.SAPProxy.prototype = Object.create(OIMO.Proxy.prototype);
  102088. OIMO.SAPProxy.prototype.constructor = OIMO.SAPProxy;
  102089. // Returns whether the proxy is dynamic or not.
  102090. OIMO.SAPProxy.prototype.isDynamic = function () {
  102091. var body = this.shape.parent;
  102092. return body.isDynamic && !body.sleeping;
  102093. };
  102094. OIMO.SAPProxy.prototype.update = function () {
  102095. var te = this.aabb.elements;
  102096. this.min[0].value = te[0];
  102097. this.min[1].value = te[1];
  102098. this.min[2].value = te[2];
  102099. this.max[0].value = te[3];
  102100. this.max[1].value = te[4];
  102101. this.max[2].value = te[5];
  102102. if (this.belongsTo == 1 && !this.isDynamic() || this.belongsTo == 2 && this.isDynamic()) {
  102103. this.sap.removeProxy(this);
  102104. this.sap.addProxy(this);
  102105. }
  102106. };
  102107. /**
  102108. * A dynamic bounding volume tree for the broad-phase algorithm.
  102109. * @author saharan
  102110. * @author lo-th
  102111. */
  102112. OIMO.DBVT = function () {
  102113. // The root of the tree.
  102114. this.root = null;
  102115. this.freeNodes = [];
  102116. this.freeNodes.length = 16384;
  102117. this.numFreeNodes = 0;
  102118. this.aabb = new OIMO.AABB();
  102119. };
  102120. OIMO.DBVT.prototype = {
  102121. constructor: OIMO.DBVT,
  102122. /**
  102123. * Move a leaf.
  102124. * @param leaf
  102125. */
  102126. moveLeaf: function (leaf) {
  102127. this.deleteLeaf(leaf);
  102128. this.insertLeaf(leaf);
  102129. },
  102130. /**
  102131. * Insert a leaf to the tree.
  102132. * @param node
  102133. */
  102134. insertLeaf: function (leaf) {
  102135. if (this.root == null) {
  102136. this.root = leaf;
  102137. return;
  102138. }
  102139. var lb = leaf.aabb;
  102140. var sibling = this.root;
  102141. var oldArea;
  102142. var newArea;
  102143. while (sibling.proxy == null) { // descend the node to search the best pair
  102144. var c1 = sibling.child1;
  102145. var c2 = sibling.child2;
  102146. var b = sibling.aabb;
  102147. var c1b = c1.aabb;
  102148. var c2b = c2.aabb;
  102149. oldArea = b.surfaceArea();
  102150. this.aabb.combine(lb, b);
  102151. newArea = this.aabb.surfaceArea();
  102152. var creatingCost = newArea * 2;
  102153. var incrementalCost = (newArea - oldArea) * 2; // cost of creating a new pair with the node
  102154. var discendingCost1 = incrementalCost;
  102155. this.aabb.combine(lb, c1b);
  102156. if (c1.proxy != null) {
  102157. // leaf cost = area(combined aabb)
  102158. discendingCost1 += this.aabb.surfaceArea();
  102159. } else {
  102160. // node cost = area(combined aabb) - area(old aabb)
  102161. discendingCost1 += this.aabb.surfaceArea() - c1b.surfaceArea();
  102162. }
  102163. var discendingCost2 = incrementalCost;
  102164. this.aabb.combine(lb, c2b);
  102165. if (c2.proxy != null) {
  102166. // leaf cost = area(combined aabb)
  102167. discendingCost2 += this.aabb.surfaceArea();
  102168. } else {
  102169. // node cost = area(combined aabb) - area(old aabb)
  102170. discendingCost2 += this.aabb.surfaceArea() - c2b.surfaceArea();
  102171. }
  102172. if (discendingCost1 < discendingCost2) {
  102173. if (creatingCost < discendingCost1) {
  102174. break;// stop descending
  102175. } else {
  102176. sibling = c1;// descend into first child
  102177. }
  102178. } else {
  102179. if (creatingCost < discendingCost2) {
  102180. break;// stop descending
  102181. } else {
  102182. sibling = c2;// descend into second child
  102183. }
  102184. }
  102185. }
  102186. var oldParent = sibling.parent;
  102187. var newParent;
  102188. if (this.numFreeNodes > 0) {
  102189. newParent = this.freeNodes[--this.numFreeNodes];
  102190. } else {
  102191. newParent = new OIMO.DBVTNode();
  102192. }
  102193. newParent.parent = oldParent;
  102194. newParent.child1 = leaf;
  102195. newParent.child2 = sibling;
  102196. newParent.aabb.combine(leaf.aabb, sibling.aabb);
  102197. newParent.height = sibling.height + 1;
  102198. sibling.parent = newParent;
  102199. leaf.parent = newParent;
  102200. if (sibling == this.root) {
  102201. // replace root
  102202. this.root = newParent;
  102203. } else {
  102204. // replace child
  102205. if (oldParent.child1 == sibling) {
  102206. oldParent.child1 = newParent;
  102207. } else {
  102208. oldParent.child2 = newParent;
  102209. }
  102210. }
  102211. // update whole tree
  102212. do {
  102213. newParent = this.balance(newParent);
  102214. this.fix(newParent);
  102215. newParent = newParent.parent;
  102216. } while (newParent != null);
  102217. },
  102218. getBalance: function (node) {
  102219. if (node.proxy != null) return 0;
  102220. return node.child1.height - node.child2.height;
  102221. },
  102222. /*print:function(node,indent,text){
  102223. var hasChild=node.proxy==null;
  102224. if(hasChild)text=this.print(node.child1,indent+1,text);
  102225. for(var i=indent*2;i>=0;i--){
  102226. text+=" ";
  102227. }
  102228. text+=(hasChild?this.getBalance(node):"["+node.proxy.aabb.minX+"]")+"\n";
  102229. if(hasChild)text=this.print(node.child2,indent+1,text);
  102230. return text;
  102231. },*/
  102232. /**
  102233. * Delete a leaf from the tree.
  102234. * @param node
  102235. */
  102236. deleteLeaf: function (leaf) {
  102237. if (leaf == this.root) {
  102238. this.root = null;
  102239. return;
  102240. }
  102241. var parent = leaf.parent;
  102242. var sibling;
  102243. if (parent.child1 == leaf) {
  102244. sibling = parent.child2;
  102245. } else {
  102246. sibling = parent.child1;
  102247. }
  102248. if (parent == this.root) {
  102249. this.root = sibling;
  102250. sibling.parent = null;
  102251. return;
  102252. }
  102253. var grandParent = parent.parent;
  102254. sibling.parent = grandParent;
  102255. if (grandParent.child1 == parent) {
  102256. grandParent.child1 = sibling;
  102257. } else {
  102258. grandParent.child2 = sibling;
  102259. }
  102260. if (this.numFreeNodes < 16384) {
  102261. this.freeNodes[this.numFreeNodes++] = parent;
  102262. }
  102263. do {
  102264. grandParent = this.balance(grandParent);
  102265. this.fix(grandParent);
  102266. grandParent = grandParent.parent;
  102267. } while (grandParent != null);
  102268. },
  102269. balance: function (node) {
  102270. var nh = node.height;
  102271. if (nh < 2) {
  102272. return node;
  102273. }
  102274. var p = node.parent;
  102275. var l = node.child1;
  102276. var r = node.child2;
  102277. var lh = l.height;
  102278. var rh = r.height;
  102279. var balance = lh - rh;
  102280. var t;// for bit operation
  102281. // [ N ]
  102282. // / \
  102283. // [ L ] [ R ]
  102284. // / \ / \
  102285. // [L-L] [L-R] [R-L] [R-R]
  102286. // Is the tree balanced?
  102287. if (balance > 1) {
  102288. var ll = l.child1;
  102289. var lr = l.child2;
  102290. var llh = ll.height;
  102291. var lrh = lr.height;
  102292. // Is L-L higher than L-R?
  102293. if (llh > lrh) {
  102294. // set N to L-R
  102295. l.child2 = node;
  102296. node.parent = l;
  102297. // [ L ]
  102298. // / \
  102299. // [L-L] [ N ]
  102300. // / \ / \
  102301. // [...] [...] [ L ] [ R ]
  102302. // set L-R
  102303. node.child1 = lr;
  102304. lr.parent = node;
  102305. // [ L ]
  102306. // / \
  102307. // [L-L] [ N ]
  102308. // / \ / \
  102309. // [...] [...] [L-R] [ R ]
  102310. // fix bounds and heights
  102311. node.aabb.combine(lr.aabb, r.aabb);
  102312. t = lrh - rh;
  102313. node.height = lrh - (t & t >> 31) + 1;
  102314. l.aabb.combine(ll.aabb, node.aabb);
  102315. t = llh - nh;
  102316. l.height = llh - (t & t >> 31) + 1;
  102317. } else {
  102318. // set N to L-L
  102319. l.child1 = node;
  102320. node.parent = l;
  102321. // [ L ]
  102322. // / \
  102323. // [ N ] [L-R]
  102324. // / \ / \
  102325. // [ L ] [ R ] [...] [...]
  102326. // set L-L
  102327. node.child1 = ll;
  102328. ll.parent = node;
  102329. // [ L ]
  102330. // / \
  102331. // [ N ] [L-R]
  102332. // / \ / \
  102333. // [L-L] [ R ] [...] [...]
  102334. // fix bounds and heights
  102335. node.aabb.combine(ll.aabb, r.aabb);
  102336. t = llh - rh;
  102337. node.height = llh - (t & t >> 31) + 1;
  102338. l.aabb.combine(node.aabb, lr.aabb);
  102339. t = nh - lrh;
  102340. l.height = nh - (t & t >> 31) + 1;
  102341. }
  102342. // set new parent of L
  102343. if (p != null) {
  102344. if (p.child1 == node) {
  102345. p.child1 = l;
  102346. } else {
  102347. p.child2 = l;
  102348. }
  102349. } else {
  102350. this.root = l;
  102351. }
  102352. l.parent = p;
  102353. return l;
  102354. } else if (balance < -1) {
  102355. var rl = r.child1;
  102356. var rr = r.child2;
  102357. var rlh = rl.height;
  102358. var rrh = rr.height;
  102359. // Is R-L higher than R-R?
  102360. if (rlh > rrh) {
  102361. // set N to R-R
  102362. r.child2 = node;
  102363. node.parent = r;
  102364. // [ R ]
  102365. // / \
  102366. // [R-L] [ N ]
  102367. // / \ / \
  102368. // [...] [...] [ L ] [ R ]
  102369. // set R-R
  102370. node.child2 = rr;
  102371. rr.parent = node;
  102372. // [ R ]
  102373. // / \
  102374. // [R-L] [ N ]
  102375. // / \ / \
  102376. // [...] [...] [ L ] [R-R]
  102377. // fix bounds and heights
  102378. node.aabb.combine(l.aabb, rr.aabb);
  102379. t = lh - rrh;
  102380. node.height = lh - (t & t >> 31) + 1;
  102381. r.aabb.combine(rl.aabb, node.aabb);
  102382. t = rlh - nh;
  102383. r.height = rlh - (t & t >> 31) + 1;
  102384. } else {
  102385. // set N to R-L
  102386. r.child1 = node;
  102387. node.parent = r;
  102388. // [ R ]
  102389. // / \
  102390. // [ N ] [R-R]
  102391. // / \ / \
  102392. // [ L ] [ R ] [...] [...]
  102393. // set R-L
  102394. node.child2 = rl;
  102395. rl.parent = node;
  102396. // [ R ]
  102397. // / \
  102398. // [ N ] [R-R]
  102399. // / \ / \
  102400. // [ L ] [R-L] [...] [...]
  102401. // fix bounds and heights
  102402. node.aabb.combine(l.aabb, rl.aabb);
  102403. t = lh - rlh;
  102404. node.height = lh - (t & t >> 31) + 1;
  102405. r.aabb.combine(node.aabb, rr.aabb);
  102406. t = nh - rrh;
  102407. r.height = nh - (t & t >> 31) + 1;
  102408. }
  102409. // set new parent of R
  102410. if (p != null) {
  102411. if (p.child1 == node) {
  102412. p.child1 = r;
  102413. } else {
  102414. p.child2 = r;
  102415. }
  102416. } else {
  102417. this.root = r;
  102418. }
  102419. r.parent = p;
  102420. return r;
  102421. }
  102422. return node;
  102423. },
  102424. fix: function (node) {
  102425. var c1 = node.child1;
  102426. var c2 = node.child2;
  102427. node.aabb.combine(c1.aabb, c2.aabb);
  102428. //var h1 = c1.height;
  102429. //var h2 = c2.height;
  102430. node.height = c1.height < c2.height ? c2.height + 1 : c1.height + 1;
  102431. /*if( h1 < h2 ) {
  102432. node.height = h2+1;
  102433. }else{
  102434. node.height = h1+1;
  102435. }*/
  102436. }
  102437. }
  102438. /**
  102439. * A broad-phase algorithm using dynamic bounding volume tree.
  102440. * @author saharan
  102441. * @author lo-th
  102442. */
  102443. OIMO.DBVTBroadPhase = function () {
  102444. OIMO.BroadPhase.call(this);
  102445. this.types = OIMO.BR_BOUNDING_VOLUME_TREE;
  102446. this.tree = new OIMO.DBVT();
  102447. this.stack = [];
  102448. this.leaves = [];
  102449. this.numLeaves = 0;
  102450. };
  102451. OIMO.DBVTBroadPhase.prototype = Object.create(OIMO.BroadPhase.prototype);
  102452. OIMO.DBVTBroadPhase.prototype.constructor = OIMO.DBVTBroadPhase;
  102453. OIMO.DBVTBroadPhase.prototype.createProxy = function (shape) {
  102454. return new OIMO.DBVTProxy(shape);
  102455. };
  102456. OIMO.DBVTBroadPhase.prototype.addProxy = function (proxy) {
  102457. this.tree.insertLeaf(proxy.leaf);
  102458. this.leaves.push(proxy.leaf);
  102459. this.numLeaves++;
  102460. };
  102461. OIMO.DBVTBroadPhase.prototype.removeProxy = function (proxy) {
  102462. this.tree.deleteLeaf(proxy.leaf);
  102463. var n = this.leaves.indexOf(proxy.leaf);
  102464. if (n > -1) {
  102465. this.leaves.splice(n, 1);
  102466. this.numLeaves--;
  102467. }
  102468. };
  102469. OIMO.DBVTBroadPhase.prototype.collectPairs = function () {
  102470. if (this.numLeaves < 2) return;
  102471. var leaf, margin = 0.1, i = this.numLeaves;
  102472. while (i--) {
  102473. leaf = this.leaves[i];
  102474. if (leaf.proxy.aabb.intersectTestTwo(leaf.aabb)) {
  102475. leaf.aabb.copy(leaf.proxy.aabb, margin);
  102476. this.tree.deleteLeaf(leaf);
  102477. this.tree.insertLeaf(leaf);
  102478. this.collide(leaf, this.tree.root);
  102479. }
  102480. }
  102481. };
  102482. OIMO.DBVTBroadPhase.prototype.collide = function (node1, node2) {
  102483. var stackCount = 2;
  102484. var s1, s2, n1, n2, l1, l2;
  102485. this.stack[0] = node1;
  102486. this.stack[1] = node2;
  102487. while (stackCount > 0) {
  102488. n1 = this.stack[--stackCount];
  102489. n2 = this.stack[--stackCount];
  102490. l1 = n1.proxy != null;
  102491. l2 = n2.proxy != null;
  102492. this.numPairChecks++;
  102493. if (l1 && l2) {
  102494. s1 = n1.proxy.shape;
  102495. s2 = n2.proxy.shape;
  102496. if (s1 == s2 || s1.aabb.intersectTest(s2.aabb) || !this.isAvailablePair(s1, s2)) continue;
  102497. this.addPair(s1, s2);
  102498. } else {
  102499. if (n1.aabb.intersectTest(n2.aabb)) continue;
  102500. /*if(stackCount+4>=this.maxStack){// expand the stack
  102501. //this.maxStack<<=1;
  102502. this.maxStack*=2;
  102503. var newStack = [];// vector
  102504. newStack.length = this.maxStack;
  102505. for(var i=0;i<stackCount;i++){
  102506. newStack[i] = this.stack[i];
  102507. }
  102508. this.stack = newStack;
  102509. }*/
  102510. if (l2 || !l1 && (n1.aabb.surfaceArea() > n2.aabb.surfaceArea())) {
  102511. this.stack[stackCount++] = n1.child1;
  102512. this.stack[stackCount++] = n2;
  102513. this.stack[stackCount++] = n1.child2;
  102514. this.stack[stackCount++] = n2;
  102515. } else {
  102516. this.stack[stackCount++] = n1;
  102517. this.stack[stackCount++] = n2.child1;
  102518. this.stack[stackCount++] = n1;
  102519. this.stack[stackCount++] = n2.child2;
  102520. }
  102521. }
  102522. }
  102523. };
  102524. /**
  102525. * A node of the dynamic bounding volume tree.
  102526. * @author saharan
  102527. */
  102528. OIMO.DBVTNode = function () {
  102529. // The first child node of this node.
  102530. this.child1 = null;
  102531. // The second child node of this node.
  102532. this.child2 = null;
  102533. // The parent node of this tree.
  102534. this.parent = null;
  102535. // The proxy of this node. This has no value if this node is not leaf.
  102536. this.proxy = null;
  102537. // The maximum distance from leaf nodes.
  102538. this.height = 0;
  102539. // The AABB of this node.
  102540. this.aabb = new OIMO.AABB();
  102541. };
  102542. /**
  102543. * A proxy for dynamic bounding volume tree broad-phase.
  102544. * @author saharan
  102545. */
  102546. OIMO.DBVTProxy = function (shape) {
  102547. OIMO.Proxy.call(this, shape);
  102548. // The leaf of the proxy.
  102549. this.leaf = new OIMO.DBVTNode();
  102550. this.leaf.proxy = this;
  102551. };
  102552. OIMO.DBVTProxy.prototype = Object.create(OIMO.Proxy.prototype);
  102553. OIMO.DBVTProxy.prototype.constructor = OIMO.DBVTProxy;
  102554. OIMO.DBVTProxy.prototype.update = function () {
  102555. };
  102556. OIMO.World.prototype.add = function (obj) {
  102557. obj = obj || {};
  102558. var type = obj.type || "box";
  102559. if (typeof type === 'string') type = [type];// single shape
  102560. if (type[0].substring(0, 5) == 'joint') { // is joint
  102561. if (type[0] === 'joint') type[0] = 'jointHinge';
  102562. var axe1 = obj.axe1 || [1, 0, 0];
  102563. var axe2 = obj.axe2 || [1, 0, 0];
  102564. var pos1 = obj.pos1 || [0, 0, 0];
  102565. var pos2 = obj.pos2 || [0, 0, 0];
  102566. pos1 = pos1.map(function (x) { return x * OIMO.INV_SCALE; });
  102567. pos2 = pos2.map(function (x) { return x * OIMO.INV_SCALE; });
  102568. var min, max;
  102569. if (type[0] === "jointDistance") {
  102570. min = obj.min || 0;
  102571. max = obj.max || 10;
  102572. min = min * OIMO.INV_SCALE;
  102573. max = max * OIMO.INV_SCALE;
  102574. } else {
  102575. min = obj.min || 57.29578;
  102576. max = obj.max || 0;
  102577. min = min * OIMO.degtorad;
  102578. max = max * OIMO.degtorad;
  102579. }
  102580. var limit = obj.limit || null;
  102581. var spring = obj.spring || null;
  102582. var motor = obj.motor || null;
  102583. // joint setting
  102584. var jc = new OIMO.JointConfig();
  102585. jc.allowCollision = obj.collision || false;;
  102586. jc.localAxis1.init(axe1[0], axe1[1], axe1[2]);
  102587. jc.localAxis2.init(axe2[0], axe2[1], axe2[2]);
  102588. jc.localAnchorPoint1.init(pos1[0], pos1[1], pos1[2]);
  102589. jc.localAnchorPoint2.init(pos2[0], pos2[1], pos2[2]);
  102590. if (typeof obj.body1 == 'string' || obj.body1 instanceof String) obj.body1 = this.getByName(obj.body1);
  102591. if (typeof obj.body2 == 'string' || obj.body2 instanceof String) obj.body2 = this.getByName(obj.body2);
  102592. jc.body1 = obj.body1;
  102593. jc.body2 = obj.body2;
  102594. var joint;
  102595. switch (type[0]) {
  102596. case "jointDistance": joint = new OIMO.DistanceJoint(jc, min, max);
  102597. if (spring !== null) joint.limitMotor.setSpring(spring[0], spring[1]);
  102598. if (motor !== null) joint.limitMotor.setSpring(motor[0], motor[1]);
  102599. break;
  102600. case "jointHinge": joint = new OIMO.HingeJoint(jc, min, max);
  102601. if (spring !== null) joint.limitMotor.setSpring(spring[0], spring[1]);// soften the joint ex: 100, 0.2
  102602. if (motor !== null) joint.limitMotor.setSpring(motor[0], motor[1]);
  102603. break;
  102604. case "jointPrisme": joint = new OIMO.PrismaticJoint(jc, min, max); break;
  102605. case "jointSlide": joint = new OIMO.SliderJoint(jc, min, max); break;
  102606. case "jointBall": joint = new OIMO.BallAndSocketJoint(jc); break;
  102607. case "jointWheel": joint = new OIMO.WheelJoint(jc);
  102608. if (limit !== null) joint.rotationalLimitMotor1.setLimit(limit[0], limit[1]);
  102609. if (spring !== null) joint.rotationalLimitMotor1.setSpring(spring[0], spring[1]);
  102610. if (motor !== null) joint.rotationalLimitMotor1.setSpring(motor[0], motor[1]);
  102611. break;
  102612. }
  102613. joint.name = obj.name || '';
  102614. // finaly add to physics world
  102615. this.addJoint(joint);
  102616. return joint;
  102617. } else { // is body
  102618. // I'm dynamique or not
  102619. var move = obj.move || false;
  102620. // I can sleep or not
  102621. var noSleep = obj.noSleep || false;
  102622. // My start position
  102623. var p = obj.pos || [0, 0, 0];
  102624. p = p.map(function (x) { return x * OIMO.INV_SCALE; });
  102625. // My size
  102626. var s = obj.size || [1, 1, 1];
  102627. s = s.map(function (x) { return x * OIMO.INV_SCALE; });
  102628. // My rotation in degre
  102629. var rot = obj.rot || [0, 0, 0];
  102630. rot = rot.map(function (x) { return x * OIMO.degtorad; });
  102631. var r = [];
  102632. for (var i = 0; i < rot.length / 3; i++) {
  102633. var tmp = OIMO.EulerToAxis(rot[i + 0], rot[i + 1], rot[i + 2]);
  102634. r.push(tmp[0]); r.push(tmp[1]); r.push(tmp[2]); r.push(tmp[3]);
  102635. }
  102636. // My physics setting
  102637. var sc = new OIMO.ShapeConfig();
  102638. if (obj.sc !== undefined) sc = obj.sc;
  102639. if (obj.config) {
  102640. // The density of the shape.
  102641. sc.density = obj.config[0] === undefined ? 1 : obj.config[0];
  102642. // The coefficient of friction of the shape.
  102643. sc.friction = obj.config[1] === undefined ? 0.4 : obj.config[1];
  102644. // The coefficient of restitution of the shape.
  102645. sc.restitution = obj.config[2] === undefined ? 0.2 : obj.config[2];
  102646. // The bits of the collision groups to which the shape belongs.
  102647. sc.belongsTo = obj.config[3] || 1;
  102648. //sc.belongsTo = obj.config[3] === undefined ? 1 : obj.config[3];
  102649. // The bits of the collision groups with which the shape collides.
  102650. sc.collidesWith = obj.config[4] || 0xffffffff;
  102651. //sc.collidesWith = obj.config[4] === undefined ? 0xffffffff : obj.config[4];
  102652. }
  102653. // direct physics setting
  102654. if (obj.density !== undefined) sc.density = obj.density;
  102655. if (obj.friction !== undefined) sc.friction = obj.friction;
  102656. if (obj.restitution !== undefined) sc.restitution = obj.restitution;
  102657. if (obj.belongsTo !== undefined) sc.belongsTo = obj.belongsTo;
  102658. if (obj.collidesWith !== undefined) sc.collidesWith = obj.collidesWith;
  102659. if (obj.massPos) {
  102660. obj.massPos = obj.massPos.map(function (x) { return x * OIMO.INV_SCALE; });
  102661. sc.relativePosition.init(obj.massPos[0], obj.massPos[1], obj.massPos[2]);
  102662. }
  102663. if (obj.massRot) {
  102664. obj.massRot = obj.massRot.map(function (x) { return x * OIMO.degtorad; });
  102665. sc.relativeRotation = OIMO.EulerToMatrix(obj.massRot[0], obj.massRot[1], obj.massRot[2]);
  102666. }
  102667. // My rigidbody
  102668. var body = new OIMO.RigidBody(p[0], p[1], p[2], r[0], r[1], r[2], r[3]);
  102669. // My shapes
  102670. var shapes = [];
  102671. //if( typeof type === 'string' ) type = [type];// single shape
  102672. var n, n2;
  102673. for (var i = 0; i < type.length; i++) {
  102674. n = i * 3;
  102675. n2 = i * 4;
  102676. switch (type[i]) {
  102677. case "sphere": shapes[i] = new OIMO.SphereShape(sc, s[n]); break;
  102678. case "cylinder": shapes[i] = new OIMO.CylinderShape(sc, s[n], s[n + 1]); break;
  102679. case "box": shapes[i] = new OIMO.BoxShape(sc, s[n], s[n + 1], s[n + 2]); break;
  102680. }
  102681. body.addShape(shapes[i]);
  102682. if (i > 0) {
  102683. //shapes[i].position.init(p[0]+p[n+0], p[1]+p[n+1], p[2]+p[n+2] );
  102684. shapes[i].relativePosition = new OIMO.Vec3(p[n], p[n + 1], p[n + 2]);
  102685. if (r[n2 + 0]) shapes[i].relativeRotation = [r[n2], r[n2 + 1], r[n2 + 2], r[n2 + 3]];
  102686. }
  102687. }
  102688. // I'm static or i move
  102689. if (move) {
  102690. if (obj.massPos || obj.massRot) body.setupMass(0x1, false);
  102691. else body.setupMass(0x1, true);
  102692. if (noSleep) body.allowSleep = false;
  102693. else body.allowSleep = true;
  102694. } else {
  102695. body.setupMass(0x2);
  102696. }
  102697. body.name = obj.name || ' ';
  102698. // finaly add to physics world
  102699. this.addRigidBody(body);
  102700. return body;
  102701. }
  102702. }
  102703. //UMD simplified
  102704. var root = this;
  102705. if (!root['OIMO']) {
  102706. if (true)
  102707. module.exports = OIMO;
  102708. else if (typeof define === 'function' && define.amd)
  102709. define([], function () {
  102710. return OIMO;
  102711. });
  102712. else if (typeof exports === 'object')
  102713. exports["OIMO"] = OIMO;
  102714. else {
  102715. root["OIMO"] = OIMO;
  102716. }
  102717. }
  102718. /***/ }),
  102719. /* 19 */
  102720. /***/ (function(module, exports, __webpack_require__) {
  102721. "use strict";
  102722. Object.defineProperty(exports, "__esModule", { value: true });
  102723. var babylonjs_1 = __webpack_require__(0);
  102724. var helper_1 = __webpack_require__(3);
  102725. var TemplateManager = (function () {
  102726. function TemplateManager(containerElement) {
  102727. this.containerElement = containerElement;
  102728. this.templates = {};
  102729. this.onInit = new babylonjs_1.Observable();
  102730. this.onLoaded = new babylonjs_1.Observable();
  102731. this.onStateChange = new babylonjs_1.Observable();
  102732. this.onAllLoaded = new babylonjs_1.Observable();
  102733. this.onEventTriggered = new babylonjs_1.Observable();
  102734. this.eventManager = new eventManager_1.EventManager(this);
  102735. }
  102736. TemplateManager.prototype.initTemplate = function (templates) {
  102737. var _this = this;
  102738. var internalInit = function (dependencyMap, name, parentTemplate) {
  102739. var template = _this.templates[name];
  102740. var childrenTemplates = Object.keys(dependencyMap).map(function (childName) {
  102741. return internalInit(dependencyMap[childName], childName, template);
  102742. });
  102743. var addToParent = function () {
  102744. var containingElement = parentTemplate && parentTemplate.parent.querySelector(helper_1.camelToKebab(name)) || _this.containerElement;
  102745. template.appendTo(containingElement);
  102746. _this.checkLoadedState();
  102747. };
  102748. if (parentTemplate && !parentTemplate.parent) {
  102749. parentTemplate.onAppended.add(function () {
  102750. addToParent();
  102751. });
  102752. }
  102753. else {
  102754. addToParent();
  102755. }
  102756. return template;
  102757. };
  102758. return this.buildHTMLTree(templates).then(function (htmlTree) {
  102759. if (_this.templates['main']) {
  102760. internalInit(htmlTree, 'main');
  102761. }
  102762. else {
  102763. _this.checkLoadedState();
  102764. }
  102765. return;
  102766. });
  102767. };
  102768. TemplateManager.prototype.buildHTMLTree = function (templates) {
  102769. var _this = this;
  102770. var promises = Object.keys(templates).map(function (name) {
  102771. if (!templates[name])
  102772. return Promise.resolve(false);
  102773. var template = new Template(name, templates[name]);
  102774. template.onEventTriggered.add(function (eventData) { return _this.onEventTriggered.notifyObservers(eventData); });
  102775. _this.templates[name] = template;
  102776. return template.initPromise;
  102777. });
  102778. return Promise.all(promises).then(function () {
  102779. var templateStructure = {};
  102780. var buildTree = function (parentObject, name) {
  102781. _this.templates[name].isInHtmlTree = true;
  102782. var childNodes = _this.templates[name].getChildElements().filter(function (n) { return !!_this.templates[n]; });
  102783. childNodes.forEach(function (element) {
  102784. parentObject[element] = {};
  102785. buildTree(parentObject[element], element);
  102786. });
  102787. };
  102788. if (_this.templates['main']) {
  102789. buildTree(templateStructure, "main");
  102790. }
  102791. return templateStructure;
  102792. });
  102793. };
  102794. TemplateManager.prototype.getCanvas = function () {
  102795. return this.containerElement.querySelector('canvas');
  102796. };
  102797. TemplateManager.prototype.getTemplate = function (name) {
  102798. return this.templates[name];
  102799. };
  102800. TemplateManager.prototype.checkLoadedState = function () {
  102801. var _this = this;
  102802. var done = Object.keys(this.templates).length === 0 || Object.keys(this.templates).every(function (key) {
  102803. return (_this.templates[key].isLoaded && !!_this.templates[key].parent) || !_this.templates[key].isInHtmlTree;
  102804. });
  102805. if (done) {
  102806. this.onAllLoaded.notifyObservers(this);
  102807. }
  102808. };
  102809. TemplateManager.prototype.dispose = function () {
  102810. var _this = this;
  102811. Object.keys(this.templates).forEach(function (template) {
  102812. _this.templates[template].dispose();
  102813. });
  102814. this.onInit.clear();
  102815. this.onAllLoaded.clear();
  102816. this.onEventTriggered.clear();
  102817. this.onLoaded.clear();
  102818. this.onStateChange.clear();
  102819. };
  102820. return TemplateManager;
  102821. }());
  102822. exports.TemplateManager = TemplateManager;
  102823. var Handlebars = __webpack_require__(20);
  102824. var eventManager_1 = __webpack_require__(21);
  102825. Handlebars.registerHelper('eachInMap', function (map, block) {
  102826. var out = '';
  102827. Object.keys(map).map(function (prop) {
  102828. var data = map[prop];
  102829. if (typeof data === 'object') {
  102830. data.id = data.id || prop;
  102831. out += block.fn(data);
  102832. }
  102833. else {
  102834. out += block.fn({ id: prop, value: data });
  102835. }
  102836. });
  102837. return out;
  102838. });
  102839. var Template = (function () {
  102840. function Template(name, _configuration) {
  102841. var _this = this;
  102842. this.name = name;
  102843. this._configuration = _configuration;
  102844. this.onInit = new babylonjs_1.Observable();
  102845. this.onLoaded = new babylonjs_1.Observable();
  102846. this.onAppended = new babylonjs_1.Observable();
  102847. this.onStateChange = new babylonjs_1.Observable();
  102848. this.onEventTriggered = new babylonjs_1.Observable();
  102849. this.loadRequests = [];
  102850. this.isLoaded = false;
  102851. this.isShown = false;
  102852. this.isInHtmlTree = false;
  102853. this.onInit.notifyObservers(this);
  102854. var htmlContentPromise = this.getTemplateAsHtml(_configuration);
  102855. this.initPromise = htmlContentPromise.then(function (htmlTemplate) {
  102856. if (htmlTemplate) {
  102857. _this.htmlTemplate = htmlTemplate;
  102858. var compiledTemplate = Handlebars.compile(htmlTemplate);
  102859. var config = _this._configuration.params || {};
  102860. var rawHtml = compiledTemplate(config);
  102861. _this.fragment = document.createRange().createContextualFragment(rawHtml);
  102862. _this.isLoaded = true;
  102863. _this.isShown = true;
  102864. _this.onLoaded.notifyObservers(_this);
  102865. }
  102866. return _this;
  102867. });
  102868. }
  102869. Template.prototype.updateParams = function (params) {
  102870. this._configuration.params = params;
  102871. if (this.isLoaded) {
  102872. this.dispose();
  102873. }
  102874. var compiledTemplate = Handlebars.compile(this.htmlTemplate);
  102875. var config = this._configuration.params || {};
  102876. var rawHtml = compiledTemplate(config);
  102877. this.fragment = document.createRange().createContextualFragment(rawHtml);
  102878. if (this.parent) {
  102879. this.appendTo(this.parent, true);
  102880. }
  102881. };
  102882. Object.defineProperty(Template.prototype, "configuration", {
  102883. get: function () {
  102884. return this._configuration;
  102885. },
  102886. enumerable: true,
  102887. configurable: true
  102888. });
  102889. Template.prototype.getChildElements = function () {
  102890. var childrenArray = [];
  102891. var children = this.fragment.children;
  102892. if (!children) {
  102893. children = this.fragment.querySelectorAll('*');
  102894. }
  102895. for (var i = 0; i < children.length; ++i) {
  102896. childrenArray.push(helper_1.kebabToCamel(children.item(i).nodeName.toLowerCase()));
  102897. }
  102898. return childrenArray;
  102899. };
  102900. Template.prototype.appendTo = function (parent, forceRemove) {
  102901. var _this = this;
  102902. if (this.parent) {
  102903. if (forceRemove) {
  102904. this.parent.removeChild(this.fragment);
  102905. }
  102906. else {
  102907. return;
  102908. }
  102909. }
  102910. this.parent = parent;
  102911. if (this._configuration.id) {
  102912. this.parent.id = this._configuration.id;
  102913. }
  102914. this.fragment = this.parent.appendChild(this.fragment);
  102915. setTimeout(function () {
  102916. _this.registerEvents();
  102917. _this.onAppended.notifyObservers(_this);
  102918. });
  102919. };
  102920. Template.prototype.show = function (visibilityFunction) {
  102921. var _this = this;
  102922. if (this.isHiding)
  102923. return Promise.resolve(this);
  102924. return Promise.resolve().then(function () {
  102925. _this.isShowing = true;
  102926. if (visibilityFunction) {
  102927. return visibilityFunction(_this);
  102928. }
  102929. else {
  102930. _this.parent.style.display = 'flex';
  102931. return _this;
  102932. }
  102933. }).then(function () {
  102934. _this.isShown = true;
  102935. _this.isShowing = false;
  102936. _this.onStateChange.notifyObservers(_this);
  102937. return _this;
  102938. });
  102939. };
  102940. Template.prototype.hide = function (visibilityFunction) {
  102941. var _this = this;
  102942. if (this.isShowing)
  102943. return Promise.resolve(this);
  102944. return Promise.resolve().then(function () {
  102945. _this.isHiding = true;
  102946. if (visibilityFunction) {
  102947. return visibilityFunction(_this);
  102948. }
  102949. else {
  102950. _this.parent.style.display = 'hide';
  102951. return _this;
  102952. }
  102953. }).then(function () {
  102954. _this.isShown = false;
  102955. _this.isHiding = false;
  102956. _this.onStateChange.notifyObservers(_this);
  102957. return _this;
  102958. });
  102959. };
  102960. Template.prototype.dispose = function () {
  102961. this.onAppended.clear();
  102962. this.onEventTriggered.clear();
  102963. this.onInit.clear();
  102964. this.onLoaded.clear();
  102965. this.onStateChange.clear();
  102966. this.isLoaded = false;
  102967. this.parent.removeChild(this.fragment);
  102968. this.loadRequests.forEach(function (request) {
  102969. request.abort();
  102970. });
  102971. };
  102972. Template.prototype.getTemplateAsHtml = function (templateConfig) {
  102973. var _this = this;
  102974. if (!templateConfig) {
  102975. return Promise.reject('No templateConfig provided');
  102976. }
  102977. else if (templateConfig.html !== undefined) {
  102978. return Promise.resolve(templateConfig.html);
  102979. }
  102980. else {
  102981. var location_1 = getTemplateLocation(templateConfig);
  102982. if (helper_1.isUrl(location_1)) {
  102983. return new Promise(function (resolve, reject) {
  102984. var fileRequest = babylonjs_1.Tools.LoadFile(location_1, function (data) {
  102985. resolve(data);
  102986. }, undefined, undefined, false, function (request, error) {
  102987. reject(error);
  102988. });
  102989. _this.loadRequests.push(fileRequest);
  102990. });
  102991. }
  102992. else {
  102993. location_1 = location_1.replace('#', '');
  102994. var element = document.getElementById(location_1);
  102995. if (element) {
  102996. return Promise.resolve(element.innerHTML);
  102997. }
  102998. else {
  102999. return Promise.reject('Template ID not found');
  103000. }
  103001. }
  103002. }
  103003. };
  103004. Template.prototype.registerEvents = function () {
  103005. var _this = this;
  103006. this.registeredEvents = this.registeredEvents || [];
  103007. if (this.registeredEvents.length) {
  103008. this.registeredEvents.forEach(function (evt) {
  103009. evt.htmlElement.removeEventListener(evt.eventName, evt.function);
  103010. });
  103011. }
  103012. if (this._configuration.events) {
  103013. var _loop_1 = function (eventName) {
  103014. if (this_1._configuration.events && this_1._configuration.events[eventName]) {
  103015. var functionToFire_1 = function (selector, event) {
  103016. _this.onEventTriggered.notifyObservers({ event: event, template: _this, selector: selector });
  103017. };
  103018. if (typeof this_1._configuration.events[eventName] === 'boolean') {
  103019. this_1.parent.addEventListener(eventName, functionToFire_1.bind(this_1, '#' + this_1.parent.id), false);
  103020. }
  103021. else if (typeof this_1._configuration.events[eventName] === 'object') {
  103022. var selectorsArray = Object.keys(this_1._configuration.events[eventName] || {});
  103023. var event_1 = this_1._configuration.events[eventName] || {};
  103024. selectorsArray.filter(function (selector) { return event_1[selector]; }).forEach(function (selector) {
  103025. if (selector && selector.indexOf('#') !== 0) {
  103026. selector = '#' + selector;
  103027. }
  103028. var htmlElement = _this.parent.querySelector(selector);
  103029. if (htmlElement) {
  103030. var binding = functionToFire_1.bind(_this, selector);
  103031. htmlElement.addEventListener(eventName, binding, false);
  103032. _this.registeredEvents.push({
  103033. htmlElement: htmlElement,
  103034. eventName: eventName,
  103035. function: binding
  103036. });
  103037. }
  103038. });
  103039. }
  103040. }
  103041. };
  103042. var this_1 = this;
  103043. for (var eventName in this._configuration.events) {
  103044. _loop_1(eventName);
  103045. }
  103046. }
  103047. };
  103048. return Template;
  103049. }());
  103050. exports.Template = Template;
  103051. function getTemplateLocation(templateConfig) {
  103052. if (!templateConfig || typeof templateConfig === 'string') {
  103053. return templateConfig;
  103054. }
  103055. else {
  103056. return templateConfig.location;
  103057. }
  103058. }
  103059. exports.getTemplateLocation = getTemplateLocation;
  103060. /***/ }),
  103061. /* 20 */
  103062. /***/ (function(module, exports, __webpack_require__) {
  103063. /**!
  103064. @license
  103065. handlebars v4.0.11
  103066. Copyright (C) 2011-2017 by Yehuda Katz
  103067. Permission is hereby granted, free of charge, to any person obtaining a copy
  103068. of this software and associated documentation files (the "Software"), to deal
  103069. in the Software without restriction, including without limitation the rights
  103070. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  103071. copies of the Software, and to permit persons to whom the Software is
  103072. furnished to do so, subject to the following conditions:
  103073. The above copyright notice and this permission notice shall be included in
  103074. all copies or substantial portions of the Software.
  103075. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  103076. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  103077. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  103078. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  103079. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  103080. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  103081. THE SOFTWARE.
  103082. */
  103083. !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],
  103084. 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){
  103085. 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"]}])});
  103086. /***/ }),
  103087. /* 21 */
  103088. /***/ (function(module, exports, __webpack_require__) {
  103089. "use strict";
  103090. Object.defineProperty(exports, "__esModule", { value: true });
  103091. var EventManager = (function () {
  103092. function EventManager(templateManager) {
  103093. var _this = this;
  103094. this.templateManager = templateManager;
  103095. this.callbacksContainer = {};
  103096. this.templateManager.onEventTriggered.add(function (eventData) {
  103097. _this.eventTriggered(eventData);
  103098. });
  103099. }
  103100. EventManager.prototype.registerCallback = function (templateName, callback, eventType, selector) {
  103101. if (!this.callbacksContainer[templateName]) {
  103102. this.callbacksContainer[templateName] = [];
  103103. }
  103104. this.callbacksContainer[templateName].push({
  103105. eventType: eventType,
  103106. callback: callback
  103107. });
  103108. };
  103109. EventManager.prototype.unregisterCallback = function (templateName, callback, eventType, selector) {
  103110. var callbackDefs = this.callbacksContainer[templateName] || [];
  103111. this.callbacksContainer[templateName] = callbackDefs.filter(function (callbackDef) { return (!callbackDef.eventType || callbackDef.eventType === eventType) && (!callbackDef.selector || callbackDef.selector === selector); });
  103112. };
  103113. EventManager.prototype.eventTriggered = function (data) {
  103114. var templateName = data.template.name;
  103115. var eventType = data.event.type;
  103116. var selector = data.selector;
  103117. var callbackDefs = this.callbacksContainer[templateName] || [];
  103118. callbackDefs.filter(function (callbackDef) { return (!callbackDef.eventType || callbackDef.eventType === eventType) && (!callbackDef.selector || callbackDef.selector === selector); }).forEach(function (callbackDef) {
  103119. callbackDef.callback(data);
  103120. });
  103121. };
  103122. return EventManager;
  103123. }());
  103124. exports.EventManager = EventManager;
  103125. /***/ }),
  103126. /* 22 */
  103127. /***/ (function(module, exports, __webpack_require__) {
  103128. "use strict";
  103129. Object.defineProperty(exports, "__esModule", { value: true });
  103130. var mappers_1 = __webpack_require__(1);
  103131. var types_1 = __webpack_require__(23);
  103132. var deepmerge = __webpack_require__(14);
  103133. var babylonjs_1 = __webpack_require__(0);
  103134. var ConfigurationLoader = (function () {
  103135. function ConfigurationLoader() {
  103136. this.configurationCache = {};
  103137. this.loadRequests = [];
  103138. }
  103139. ConfigurationLoader.prototype.loadConfiguration = function (initConfig, callback) {
  103140. var _this = this;
  103141. if (initConfig === void 0) { initConfig = {}; }
  103142. var loadedConfig = deepmerge({}, initConfig);
  103143. var extendedConfiguration = types_1.getConfigurationType(loadedConfig.extends || "");
  103144. loadedConfig = deepmerge(extendedConfiguration, loadedConfig);
  103145. if (loadedConfig.configuration) {
  103146. var mapperType_1 = "json";
  103147. return Promise.resolve().then(function () {
  103148. if (typeof loadedConfig.configuration === "string" || (loadedConfig.configuration && loadedConfig.configuration.url)) {
  103149. var url = '';
  103150. if (typeof loadedConfig.configuration === "string") {
  103151. url = loadedConfig.configuration;
  103152. }
  103153. if (typeof loadedConfig.configuration === "object" && loadedConfig.configuration.url) {
  103154. url = loadedConfig.configuration.url;
  103155. var type = loadedConfig.configuration.mapper;
  103156. if (!type) {
  103157. type = loadedConfig.configuration.url.split('.').pop();
  103158. }
  103159. mapperType_1 = type || mapperType_1;
  103160. }
  103161. return _this.loadFile(url);
  103162. }
  103163. else {
  103164. if (typeof loadedConfig.configuration === "object") {
  103165. mapperType_1 = loadedConfig.configuration.mapper || mapperType_1;
  103166. return loadedConfig.configuration.payload || {};
  103167. }
  103168. return {};
  103169. }
  103170. }).then(function (data) {
  103171. var mapper = mappers_1.mapperManager.getMapper(mapperType_1);
  103172. var parsed = mapper.map(data);
  103173. var merged = deepmerge(loadedConfig, parsed);
  103174. if (callback)
  103175. callback(merged);
  103176. return merged;
  103177. });
  103178. }
  103179. else {
  103180. if (callback)
  103181. callback(loadedConfig);
  103182. return Promise.resolve(loadedConfig);
  103183. }
  103184. };
  103185. ConfigurationLoader.prototype.dispose = function () {
  103186. this.loadRequests.forEach(function (request) {
  103187. request.abort();
  103188. });
  103189. };
  103190. ConfigurationLoader.prototype.loadFile = function (url) {
  103191. var _this = this;
  103192. var cacheReference = this.configurationCache;
  103193. if (cacheReference[url]) {
  103194. return Promise.resolve(cacheReference[url]);
  103195. }
  103196. return new Promise(function (resolve, reject) {
  103197. var fileRequest = babylonjs_1.Tools.LoadFile(url, resolve, undefined, undefined, false, function (request, error) {
  103198. reject(error);
  103199. });
  103200. _this.loadRequests.push(fileRequest);
  103201. });
  103202. };
  103203. return ConfigurationLoader;
  103204. }());
  103205. exports.ConfigurationLoader = ConfigurationLoader;
  103206. exports.configurationLoader = new ConfigurationLoader();
  103207. exports.default = exports.configurationLoader;
  103208. /***/ }),
  103209. /* 23 */
  103210. /***/ (function(module, exports, __webpack_require__) {
  103211. "use strict";
  103212. Object.defineProperty(exports, "__esModule", { value: true });
  103213. var minimal_1 = __webpack_require__(24);
  103214. exports.minimalConfiguration = minimal_1.minimalConfiguration;
  103215. var default_1 = __webpack_require__(25);
  103216. exports.defaultConfiguration = default_1.defaultConfiguration;
  103217. var getConfigurationType = function (type) {
  103218. switch (type) {
  103219. case 'default':
  103220. return default_1.defaultConfiguration;
  103221. case 'minimal':
  103222. return minimal_1.minimalConfiguration;
  103223. case 'none':
  103224. return {};
  103225. default:
  103226. return default_1.defaultConfiguration;
  103227. }
  103228. };
  103229. exports.getConfigurationType = getConfigurationType;
  103230. /***/ }),
  103231. /* 24 */
  103232. /***/ (function(module, exports, __webpack_require__) {
  103233. "use strict";
  103234. Object.defineProperty(exports, "__esModule", { value: true });
  103235. exports.minimalConfiguration = {
  103236. version: "0.1",
  103237. templates: {
  103238. main: {
  103239. html: __webpack_require__(7)
  103240. },
  103241. loadingScreen: {
  103242. html: __webpack_require__(8),
  103243. params: {
  103244. backgroundColor: "#000000",
  103245. loadingImage: __webpack_require__(9)
  103246. }
  103247. },
  103248. viewer: {
  103249. html: __webpack_require__(10),
  103250. },
  103251. overlay: {
  103252. html: __webpack_require__(11),
  103253. params: {
  103254. closeImage: __webpack_require__(12),
  103255. closeText: 'Close'
  103256. }
  103257. },
  103258. error: {
  103259. html: __webpack_require__(13)
  103260. }
  103261. },
  103262. engine: {
  103263. antialiasing: true
  103264. }
  103265. };
  103266. /***/ }),
  103267. /* 25 */
  103268. /***/ (function(module, exports, __webpack_require__) {
  103269. "use strict";
  103270. Object.defineProperty(exports, "__esModule", { value: true });
  103271. exports.defaultConfiguration = {
  103272. version: "3.2.0-alpha4",
  103273. templates: {
  103274. main: {
  103275. html: __webpack_require__(7)
  103276. },
  103277. loadingScreen: {
  103278. html: __webpack_require__(8),
  103279. params: {
  103280. backgroundColor: "#000000",
  103281. loadingImage: __webpack_require__(9)
  103282. }
  103283. },
  103284. viewer: {
  103285. html: __webpack_require__(10),
  103286. events: {
  103287. pointerout: true,
  103288. pointerdown: true,
  103289. pointerup: true
  103290. }
  103291. },
  103292. navBar: {
  103293. html: __webpack_require__(26),
  103294. params: {
  103295. buttons: {
  103296. "fullscreen-button": {
  103297. altText: "Fullscreen",
  103298. image: __webpack_require__(27)
  103299. }
  103300. },
  103301. visibilityTimeout: 2000
  103302. },
  103303. events: {
  103304. pointerdown: { 'fullscreen-button': true },
  103305. pointerover: true
  103306. }
  103307. },
  103308. overlay: {
  103309. html: __webpack_require__(11),
  103310. params: {
  103311. closeImage: __webpack_require__(12),
  103312. closeText: 'Close'
  103313. }
  103314. },
  103315. help: {
  103316. html: __webpack_require__(28)
  103317. },
  103318. share: {
  103319. html: __webpack_require__(29)
  103320. },
  103321. error: {
  103322. html: __webpack_require__(13)
  103323. }
  103324. },
  103325. camera: {
  103326. behaviors: {
  103327. autoRotate: 0,
  103328. framing: {
  103329. type: 2,
  103330. zoomOnBoundingInfo: true,
  103331. zoomStopsAnimation: false
  103332. }
  103333. }
  103334. },
  103335. skybox: {
  103336. pbr: true,
  103337. blur: 0.7,
  103338. infiniteDIstance: false,
  103339. },
  103340. ground: true,
  103341. engine: {
  103342. antialiasing: true
  103343. },
  103344. scene: {
  103345. imageProcessingConfiguration: {
  103346. exposure: 1.4,
  103347. contrast: 1.66,
  103348. toneMappingEnabled: true
  103349. }
  103350. }
  103351. };
  103352. /***/ }),
  103353. /* 26 */
  103354. /***/ (function(module, exports) {
  103355. module.exports = "<style>nav-bar{position:absolute;height:160px;width:100%;bottom:0;background-color:rgba(0,0,0,.3);color:#fff;transition:1s;align-items:flex-start;justify-content:space-around;display:flex;flex-direction:column}@media screen and (min-width:768px){nav-bar{align-items:center;flex-direction:row;justify-content:space-between;height:80px}}div.flex-container{display:flex;width:100%}div.thumbnail{position:relative;overflow:hidden;display:block;width:40px;height:40px;background-size:cover;background-position:center;border-radius:20px;margin:0 10px}div.title-container{flex-direction:column;display:flex;justify-content:space-between}span.model-title{font-size:125%}span.model-subtitle{font-size:90%}div.button-container{align-items:center;justify-content:flex-end}div.button{cursor:pointer;height:30px;margin:0 10px}div.button img{height:100%}</style> {{#if disableOnFullscreen}} <style>viewer:fullscreen nav-bar{display:none}viewer:-moz-full-screen nav-bar{display:none}viewer:-webkit-full-screen nav-bar{display:none}</style> {{/if}} <div class=flex-container id=model-metadata> <div class=thumbnail> </div> <div class=title-container> <span class=model-title>{{#if title}}{{title}}{{/if}}</span> <span class=model-subtitle> {{#if subtitle}}{{subtitle}} {{/if}}</span> </div> </div> <div class=\"button-container flex-container\"> {{#eachInMap buttons}} <div id={{id}} class=button> {{#if text}} <span>{{text}}</span>> {{/if}} {{#if image}} <img src={{image}} alt={{altText}}> {{/if}} </div> {{/eachInMap}} </div>";
  103356. /***/ }),
  103357. /* 27 */
  103358. /***/ (function(module, exports) {
  103359. module.exports = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwAQAAAAB/ecQqAAAAAnRSTlMAAHaTzTgAAAAeSURBVHgBY6ASsP/A/wcXZQNGhCkyAfE24HUndQAAXlkXcQ24P7gAAAAASUVORK5CYII="
  103360. /***/ }),
  103361. /* 28 */
  103362. /***/ (function(module, exports) {
  103363. module.exports = "HELP";
  103364. /***/ }),
  103365. /* 29 */
  103366. /***/ (function(module, exports) {
  103367. module.exports = "SHARE";
  103368. /***/ }),
  103369. /* 30 */
  103370. /***/ (function(module, exports, __webpack_require__) {
  103371. /* WEBPACK VAR INJECTION */(function(global) {var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  103372. var babylonDependency = (globalObject && globalObject.BABYLON) || BABYLON || ("function" !== 'undefined' && __webpack_require__(0));
  103373. var BABYLON = babylonDependency;
  103374. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  103375. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  103376. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  103377. 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;
  103378. return c > 3 && r && Object.defineProperty(target, key, r), r;
  103379. };
  103380. var __extends = (this && this.__extends) || (function () {
  103381. var extendStatics = Object.setPrototypeOf ||
  103382. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  103383. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  103384. return function (d, b) {
  103385. extendStatics(d, b);
  103386. function __() { this.constructor = d; }
  103387. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  103388. };
  103389. })();
  103390. var BABYLON;
  103391. (function (BABYLON) {
  103392. var STLFileLoader = /** @class */ (function () {
  103393. function STLFileLoader() {
  103394. this.solidPattern = /solid (\S*)([\S\s]*)endsolid[ ]*(\S*)/g;
  103395. this.facetsPattern = /facet([\s\S]*?)endfacet/g;
  103396. 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;
  103397. 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;
  103398. this.name = "stl";
  103399. // force data to come in as an ArrayBuffer
  103400. // we'll convert to string if it looks like it's an ASCII .stl
  103401. this.extensions = {
  103402. ".stl": { isBinary: true },
  103403. };
  103404. }
  103405. STLFileLoader.prototype.importMesh = function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  103406. var matches;
  103407. if (this.isBinary(data)) {
  103408. // binary .stl
  103409. var babylonMesh = new BABYLON.Mesh("stlmesh", scene);
  103410. this.parseBinary(babylonMesh, data);
  103411. if (meshes) {
  103412. meshes.push(babylonMesh);
  103413. }
  103414. return true;
  103415. }
  103416. // ASCII .stl
  103417. // convert to string
  103418. var array_buffer = new Uint8Array(data);
  103419. var str = '';
  103420. for (var i = 0; i < data.byteLength; i++) {
  103421. str += String.fromCharCode(array_buffer[i]); // implicitly assumes little-endian
  103422. }
  103423. data = str;
  103424. while (matches = this.solidPattern.exec(data)) {
  103425. var meshName = matches[1];
  103426. var meshNameFromEnd = matches[3];
  103427. if (meshName != meshNameFromEnd) {
  103428. BABYLON.Tools.Error("Error in STL, solid name != endsolid name");
  103429. return false;
  103430. }
  103431. // check meshesNames
  103432. if (meshesNames && meshName) {
  103433. if (meshesNames instanceof Array) {
  103434. if (!meshesNames.indexOf(meshName)) {
  103435. continue;
  103436. }
  103437. }
  103438. else {
  103439. if (meshName !== meshesNames) {
  103440. continue;
  103441. }
  103442. }
  103443. }
  103444. // stl mesh name can be empty as well
  103445. meshName = meshName || "stlmesh";
  103446. var babylonMesh = new BABYLON.Mesh(meshName, scene);
  103447. this.parseASCII(babylonMesh, matches[2]);
  103448. if (meshes) {
  103449. meshes.push(babylonMesh);
  103450. }
  103451. }
  103452. return true;
  103453. };
  103454. STLFileLoader.prototype.load = function (scene, data, rootUrl) {
  103455. var result = this.importMesh(null, scene, data, rootUrl, null, null, null);
  103456. if (result) {
  103457. scene.createDefaultCameraOrLight();
  103458. }
  103459. return result;
  103460. };
  103461. STLFileLoader.prototype.loadAssetContainer = function (scene, data, rootUrl, onError) {
  103462. var container = new BABYLON.AssetContainer(scene);
  103463. this.importMesh(null, scene, data, rootUrl, container.meshes, null, null);
  103464. container.removeAllFromScene();
  103465. return container;
  103466. };
  103467. STLFileLoader.prototype.isBinary = function (data) {
  103468. // check if file size is correct for binary stl
  103469. var faceSize, nFaces, reader;
  103470. reader = new DataView(data);
  103471. faceSize = (32 / 8 * 3) + ((32 / 8 * 3) * 3) + (16 / 8);
  103472. nFaces = reader.getUint32(80, true);
  103473. if (80 + (32 / 8) + (nFaces * faceSize) === reader.byteLength) {
  103474. return true;
  103475. }
  103476. // check characters higher than ASCII to confirm binary
  103477. var fileLength = reader.byteLength;
  103478. for (var index = 0; index < fileLength; index++) {
  103479. if (reader.getUint8(index) > 127) {
  103480. return true;
  103481. }
  103482. }
  103483. return false;
  103484. };
  103485. STLFileLoader.prototype.parseBinary = function (mesh, data) {
  103486. var reader = new DataView(data);
  103487. var faces = reader.getUint32(80, true);
  103488. var dataOffset = 84;
  103489. var faceLength = 12 * 4 + 2;
  103490. var offset = 0;
  103491. var positions = new Float32Array(faces * 3 * 3);
  103492. var normals = new Float32Array(faces * 3 * 3);
  103493. var indices = new Uint32Array(faces * 3);
  103494. var indicesCount = 0;
  103495. for (var face = 0; face < faces; face++) {
  103496. var start = dataOffset + face * faceLength;
  103497. var normalX = reader.getFloat32(start, true);
  103498. var normalY = reader.getFloat32(start + 4, true);
  103499. var normalZ = reader.getFloat32(start + 8, true);
  103500. for (var i = 1; i <= 3; i++) {
  103501. var vertexstart = start + i * 12;
  103502. // ordering is intentional to match ascii import
  103503. positions[offset] = reader.getFloat32(vertexstart, true);
  103504. positions[offset + 2] = reader.getFloat32(vertexstart + 4, true);
  103505. positions[offset + 1] = reader.getFloat32(vertexstart + 8, true);
  103506. normals[offset] = normalX;
  103507. normals[offset + 2] = normalY;
  103508. normals[offset + 1] = normalZ;
  103509. offset += 3;
  103510. }
  103511. indices[indicesCount] = indicesCount++;
  103512. indices[indicesCount] = indicesCount++;
  103513. indices[indicesCount] = indicesCount++;
  103514. }
  103515. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  103516. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  103517. mesh.setIndices(indices);
  103518. mesh.computeWorldMatrix(true);
  103519. };
  103520. STLFileLoader.prototype.parseASCII = function (mesh, solidData) {
  103521. var positions = [];
  103522. var normals = [];
  103523. var indices = [];
  103524. var indicesCount = 0;
  103525. //load facets, ignoring loop as the standard doesn't define it can contain more than vertices
  103526. var matches;
  103527. while (matches = this.facetsPattern.exec(solidData)) {
  103528. var facet = matches[1];
  103529. //one normal per face
  103530. var normalMatches = this.normalPattern.exec(facet);
  103531. this.normalPattern.lastIndex = 0;
  103532. if (!normalMatches) {
  103533. continue;
  103534. }
  103535. var normal = [Number(normalMatches[1]), Number(normalMatches[5]), Number(normalMatches[3])];
  103536. var vertexMatch;
  103537. while (vertexMatch = this.vertexPattern.exec(facet)) {
  103538. positions.push(Number(vertexMatch[1]), Number(vertexMatch[5]), Number(vertexMatch[3]));
  103539. normals.push(normal[0], normal[1], normal[2]);
  103540. }
  103541. indices.push(indicesCount++, indicesCount++, indicesCount++);
  103542. this.vertexPattern.lastIndex = 0;
  103543. }
  103544. this.facetsPattern.lastIndex = 0;
  103545. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  103546. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  103547. mesh.setIndices(indices);
  103548. mesh.computeWorldMatrix(true);
  103549. };
  103550. return STLFileLoader;
  103551. }());
  103552. BABYLON.STLFileLoader = STLFileLoader;
  103553. if (BABYLON.SceneLoader) {
  103554. BABYLON.SceneLoader.RegisterPlugin(new STLFileLoader());
  103555. }
  103556. })(BABYLON || (BABYLON = {}));
  103557. //# sourceMappingURL=babylon.stlFileLoader.js.map
  103558. var BABYLON;
  103559. (function (BABYLON) {
  103560. /**
  103561. * Class reading and parsing the MTL file bundled with the obj file.
  103562. */
  103563. var MTLFileLoader = /** @class */ (function () {
  103564. function MTLFileLoader() {
  103565. // All material loaded from the mtl will be set here
  103566. this.materials = [];
  103567. }
  103568. /**
  103569. * This function will read the mtl file and create each material described inside
  103570. * This function could be improve by adding :
  103571. * -some component missing (Ni, Tf...)
  103572. * -including the specific options available
  103573. *
  103574. * @param scene
  103575. * @param data
  103576. * @param rootUrl
  103577. */
  103578. MTLFileLoader.prototype.parseMTL = function (scene, data, rootUrl) {
  103579. //Split the lines from the file
  103580. var lines = data.split('\n');
  103581. //Space char
  103582. var delimiter_pattern = /\s+/;
  103583. //Array with RGB colors
  103584. var color;
  103585. //New material
  103586. var material = null;
  103587. //Look at each line
  103588. for (var i = 0; i < lines.length; i++) {
  103589. var line = lines[i].trim();
  103590. // Blank line or comment
  103591. if (line.length === 0 || line.charAt(0) === '#') {
  103592. continue;
  103593. }
  103594. //Get the first parameter (keyword)
  103595. var pos = line.indexOf(' ');
  103596. var key = (pos >= 0) ? line.substring(0, pos) : line;
  103597. key = key.toLowerCase();
  103598. //Get the data following the key
  103599. var value = (pos >= 0) ? line.substring(pos + 1).trim() : "";
  103600. //This mtl keyword will create the new material
  103601. if (key === "newmtl") {
  103602. //Check if it is the first material.
  103603. // Materials specifications are described after this keyword.
  103604. if (material) {
  103605. //Add the previous material in the material array.
  103606. this.materials.push(material);
  103607. }
  103608. //Create a new material.
  103609. // value is the name of the material read in the mtl file
  103610. material = new BABYLON.StandardMaterial(value, scene);
  103611. }
  103612. else if (key === "kd" && material) {
  103613. // Diffuse color (color under white light) using RGB values
  103614. //value = "r g b"
  103615. color = value.split(delimiter_pattern, 3).map(parseFloat);
  103616. //color = [r,g,b]
  103617. //Set tghe color into the material
  103618. material.diffuseColor = BABYLON.Color3.FromArray(color);
  103619. }
  103620. else if (key === "ka" && material) {
  103621. // Ambient color (color under shadow) using RGB values
  103622. //value = "r g b"
  103623. color = value.split(delimiter_pattern, 3).map(parseFloat);
  103624. //color = [r,g,b]
  103625. //Set tghe color into the material
  103626. material.ambientColor = BABYLON.Color3.FromArray(color);
  103627. }
  103628. else if (key === "ks" && material) {
  103629. // Specular color (color when light is reflected from shiny surface) using RGB values
  103630. //value = "r g b"
  103631. color = value.split(delimiter_pattern, 3).map(parseFloat);
  103632. //color = [r,g,b]
  103633. //Set the color into the material
  103634. material.specularColor = BABYLON.Color3.FromArray(color);
  103635. }
  103636. else if (key === "ke" && material) {
  103637. // Emissive color using RGB values
  103638. color = value.split(delimiter_pattern, 3).map(parseFloat);
  103639. material.emissiveColor = BABYLON.Color3.FromArray(color);
  103640. }
  103641. else if (key === "ns" && material) {
  103642. //value = "Integer"
  103643. material.specularPower = parseFloat(value);
  103644. }
  103645. else if (key === "d" && material) {
  103646. //d is dissolve for current material. It mean alpha for BABYLON
  103647. material.alpha = parseFloat(value);
  103648. //Texture
  103649. //This part can be improved by adding the possible options of texture
  103650. }
  103651. else if (key === "map_ka" && material) {
  103652. // ambient texture map with a loaded image
  103653. //We must first get the folder of the image
  103654. material.ambientTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  103655. }
  103656. else if (key === "map_kd" && material) {
  103657. // Diffuse texture map with a loaded image
  103658. material.diffuseTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  103659. }
  103660. else if (key === "map_ks" && material) {
  103661. // Specular texture map with a loaded image
  103662. //We must first get the folder of the image
  103663. material.specularTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  103664. }
  103665. else if (key === "map_ns") {
  103666. //Specular
  103667. //Specular highlight component
  103668. //We must first get the folder of the image
  103669. //
  103670. //Not supported by BABYLON
  103671. //
  103672. // continue;
  103673. }
  103674. else if (key === "map_bump" && material) {
  103675. //The bump texture
  103676. material.bumpTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  103677. }
  103678. else if (key === "map_d" && material) {
  103679. // The dissolve of the material
  103680. material.opacityTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  103681. //Options for illumination
  103682. }
  103683. else if (key === "illum") {
  103684. //Illumination
  103685. if (value === "0") {
  103686. //That mean Kd == Kd
  103687. }
  103688. else if (value === "1") {
  103689. //Color on and Ambient on
  103690. }
  103691. else if (value === "2") {
  103692. //Highlight on
  103693. }
  103694. else if (value === "3") {
  103695. //Reflection on and Ray trace on
  103696. }
  103697. else if (value === "4") {
  103698. //Transparency: Glass on, Reflection: Ray trace on
  103699. }
  103700. else if (value === "5") {
  103701. //Reflection: Fresnel on and Ray trace on
  103702. }
  103703. else if (value === "6") {
  103704. //Transparency: Refraction on, Reflection: Fresnel off and Ray trace on
  103705. }
  103706. else if (value === "7") {
  103707. //Transparency: Refraction on, Reflection: Fresnel on and Ray trace on
  103708. }
  103709. else if (value === "8") {
  103710. //Reflection on and Ray trace off
  103711. }
  103712. else if (value === "9") {
  103713. //Transparency: Glass on, Reflection: Ray trace off
  103714. }
  103715. else if (value === "10") {
  103716. //Casts shadows onto invisible surfaces
  103717. }
  103718. }
  103719. else {
  103720. // console.log("Unhandled expression at line : " + i +'\n' + "with value : " + line);
  103721. }
  103722. }
  103723. //At the end of the file, add the last material
  103724. if (material) {
  103725. this.materials.push(material);
  103726. }
  103727. };
  103728. /**
  103729. * Gets the texture for the material.
  103730. *
  103731. * If the material is imported from input file,
  103732. * We sanitize the url to ensure it takes the textre from aside the material.
  103733. *
  103734. * @param rootUrl The root url to load from
  103735. * @param value The value stored in the mtl
  103736. * @return The Texture
  103737. */
  103738. MTLFileLoader._getTexture = function (rootUrl, value, scene) {
  103739. if (!value) {
  103740. return null;
  103741. }
  103742. var url = rootUrl;
  103743. // Load from input file.
  103744. if (rootUrl === "file:") {
  103745. var lastDelimiter = value.lastIndexOf("\\");
  103746. if (lastDelimiter === -1) {
  103747. lastDelimiter = value.lastIndexOf("/");
  103748. }
  103749. if (lastDelimiter > -1) {
  103750. url += value.substr(lastDelimiter + 1);
  103751. }
  103752. else {
  103753. url += value;
  103754. }
  103755. }
  103756. else {
  103757. url += value;
  103758. }
  103759. return new BABYLON.Texture(url, scene);
  103760. };
  103761. return MTLFileLoader;
  103762. }());
  103763. BABYLON.MTLFileLoader = MTLFileLoader;
  103764. var OBJFileLoader = /** @class */ (function () {
  103765. function OBJFileLoader() {
  103766. this.name = "obj";
  103767. this.extensions = ".obj";
  103768. this.obj = /^o/;
  103769. this.group = /^g/;
  103770. this.mtllib = /^mtllib /;
  103771. this.usemtl = /^usemtl /;
  103772. this.smooth = /^s /;
  103773. this.vertexPattern = /v( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/;
  103774. // vn float float float
  103775. this.normalPattern = /vn( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/;
  103776. // vt float float
  103777. this.uvPattern = /vt( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/;
  103778. // f vertex vertex vertex ...
  103779. this.facePattern1 = /f\s+(([\d]{1,}[\s]?){3,})+/;
  103780. // f vertex/uvs vertex/uvs vertex/uvs ...
  103781. this.facePattern2 = /f\s+((([\d]{1,}\/[\d]{1,}[\s]?){3,})+)/;
  103782. // f vertex/uvs/normal vertex/uvs/normal vertex/uvs/normal ...
  103783. this.facePattern3 = /f\s+((([\d]{1,}\/[\d]{1,}\/[\d]{1,}[\s]?){3,})+)/;
  103784. // f vertex//normal vertex//normal vertex//normal ...
  103785. this.facePattern4 = /f\s+((([\d]{1,}\/\/[\d]{1,}[\s]?){3,})+)/;
  103786. }
  103787. /**
  103788. * Calls synchronously the MTL file attached to this obj.
  103789. * Load function or importMesh function don't enable to load 2 files in the same time asynchronously.
  103790. * Without this function materials are not displayed in the first frame (but displayed after).
  103791. * In consequence it is impossible to get material information in your HTML file
  103792. *
  103793. * @param url The URL of the MTL file
  103794. * @param rootUrl
  103795. * @param onSuccess Callback function to be called when the MTL file is loaded
  103796. * @private
  103797. */
  103798. OBJFileLoader.prototype._loadMTL = function (url, rootUrl, onSuccess) {
  103799. //The complete path to the mtl file
  103800. var pathOfFile = BABYLON.Tools.BaseUrl + rootUrl + url;
  103801. // Loads through the babylon tools to allow fileInput search.
  103802. BABYLON.Tools.LoadFile(pathOfFile, onSuccess, undefined, undefined, false, function () { console.warn("Error - Unable to load " + pathOfFile); });
  103803. };
  103804. OBJFileLoader.prototype.importMesh = function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  103805. //get the meshes from OBJ file
  103806. var loadedMeshes = this._parseSolid(meshesNames, scene, data, rootUrl);
  103807. //Push meshes from OBJ file into the variable mesh of this function
  103808. if (meshes) {
  103809. loadedMeshes.forEach(function (mesh) {
  103810. meshes.push(mesh);
  103811. });
  103812. }
  103813. return true;
  103814. };
  103815. OBJFileLoader.prototype.load = function (scene, data, rootUrl) {
  103816. //Get the 3D model
  103817. return this.importMesh(null, scene, data, rootUrl, null, null, null);
  103818. };
  103819. OBJFileLoader.prototype.loadAssetContainer = function (scene, data, rootUrl, onError) {
  103820. var container = new BABYLON.AssetContainer(scene);
  103821. this.importMesh(null, scene, data, rootUrl, container.meshes, null, null);
  103822. container.removeAllFromScene();
  103823. return container;
  103824. };
  103825. /**
  103826. * Read the OBJ file and create an Array of meshes.
  103827. * Each mesh contains all information given by the OBJ and the MTL file.
  103828. * i.e. vertices positions and indices, optional normals values, optional UV values, optional material
  103829. *
  103830. * @param meshesNames
  103831. * @param scene BABYLON.Scene The scene where are displayed the data
  103832. * @param data String The content of the obj file
  103833. * @param rootUrl String The path to the folder
  103834. * @returns Array<AbstractMesh>
  103835. * @private
  103836. */
  103837. OBJFileLoader.prototype._parseSolid = function (meshesNames, scene, data, rootUrl) {
  103838. var positions = []; //values for the positions of vertices
  103839. var normals = []; //Values for the normals
  103840. var uvs = []; //Values for the textures
  103841. var meshesFromObj = []; //[mesh] Contains all the obj meshes
  103842. var handledMesh; //The current mesh of meshes array
  103843. var indicesForBabylon = []; //The list of indices for VertexData
  103844. var wrappedPositionForBabylon = []; //The list of position in vectors
  103845. var wrappedUvsForBabylon = []; //Array with all value of uvs to match with the indices
  103846. var wrappedNormalsForBabylon = []; //Array with all value of normals to match with the indices
  103847. var tuplePosNorm = []; //Create a tuple with indice of Position, Normal, UV [pos, norm, uvs]
  103848. var curPositionInIndices = 0;
  103849. var hasMeshes = false; //Meshes are defined in the file
  103850. var unwrappedPositionsForBabylon = []; //Value of positionForBabylon w/o Vector3() [x,y,z]
  103851. var unwrappedNormalsForBabylon = []; //Value of normalsForBabylon w/o Vector3() [x,y,z]
  103852. var unwrappedUVForBabylon = []; //Value of uvsForBabylon w/o Vector3() [x,y,z]
  103853. var triangles = []; //Indices from new triangles coming from polygons
  103854. var materialNameFromObj = ""; //The name of the current material
  103855. var fileToLoad = ""; //The name of the mtlFile to load
  103856. var materialsFromMTLFile = new MTLFileLoader();
  103857. var objMeshName = ""; //The name of the current obj mesh
  103858. var increment = 1; //Id for meshes created by the multimaterial
  103859. var isFirstMaterial = true;
  103860. /**
  103861. * Search for obj in the given array.
  103862. * This function is called to check if a couple of data already exists in an array.
  103863. *
  103864. * If found, returns the index of the founded tuple index. Returns -1 if not found
  103865. * @param arr Array<{ normals: Array<number>, idx: Array<number> }>
  103866. * @param obj Array<number>
  103867. * @returns {boolean}
  103868. */
  103869. var isInArray = function (arr, obj) {
  103870. if (!arr[obj[0]])
  103871. arr[obj[0]] = { normals: [], idx: [] };
  103872. var idx = arr[obj[0]].normals.indexOf(obj[1]);
  103873. return idx === -1 ? -1 : arr[obj[0]].idx[idx];
  103874. };
  103875. var isInArrayUV = function (arr, obj) {
  103876. if (!arr[obj[0]])
  103877. arr[obj[0]] = { normals: [], idx: [], uv: [] };
  103878. var idx = arr[obj[0]].normals.indexOf(obj[1]);
  103879. if (idx != 1 && (obj[2] == arr[obj[0]].uv[idx])) {
  103880. return arr[obj[0]].idx[idx];
  103881. }
  103882. return -1;
  103883. };
  103884. /**
  103885. * This function set the data for each triangle.
  103886. * Data are position, normals and uvs
  103887. * If a tuple of (position, normal) is not set, add the data into the corresponding array
  103888. * If the tuple already exist, add only their indice
  103889. *
  103890. * @param indicePositionFromObj Integer The index in positions array
  103891. * @param indiceUvsFromObj Integer The index in uvs array
  103892. * @param indiceNormalFromObj Integer The index in normals array
  103893. * @param positionVectorFromOBJ Vector3 The value of position at index objIndice
  103894. * @param textureVectorFromOBJ Vector3 The value of uvs
  103895. * @param normalsVectorFromOBJ Vector3 The value of normals at index objNormale
  103896. */
  103897. var setData = function (indicePositionFromObj, indiceUvsFromObj, indiceNormalFromObj, positionVectorFromOBJ, textureVectorFromOBJ, normalsVectorFromOBJ) {
  103898. //Check if this tuple already exists in the list of tuples
  103899. var _index;
  103900. if (OBJFileLoader.OPTIMIZE_WITH_UV) {
  103901. _index = isInArrayUV(tuplePosNorm, [
  103902. indicePositionFromObj,
  103903. indiceNormalFromObj,
  103904. indiceUvsFromObj
  103905. ]);
  103906. }
  103907. else {
  103908. _index = isInArray(tuplePosNorm, [
  103909. indicePositionFromObj,
  103910. indiceNormalFromObj
  103911. ]);
  103912. }
  103913. //If it not exists
  103914. if (_index == -1) {
  103915. //Add an new indice.
  103916. //The array of indices is only an array with his length equal to the number of triangles - 1.
  103917. //We add vertices data in this order
  103918. indicesForBabylon.push(wrappedPositionForBabylon.length);
  103919. //Push the position of vertice for Babylon
  103920. //Each element is a BABYLON.Vector3(x,y,z)
  103921. wrappedPositionForBabylon.push(positionVectorFromOBJ);
  103922. //Push the uvs for Babylon
  103923. //Each element is a BABYLON.Vector3(u,v)
  103924. wrappedUvsForBabylon.push(textureVectorFromOBJ);
  103925. //Push the normals for Babylon
  103926. //Each element is a BABYLON.Vector3(x,y,z)
  103927. wrappedNormalsForBabylon.push(normalsVectorFromOBJ);
  103928. //Add the tuple in the comparison list
  103929. tuplePosNorm[indicePositionFromObj].normals.push(indiceNormalFromObj);
  103930. tuplePosNorm[indicePositionFromObj].idx.push(curPositionInIndices++);
  103931. if (OBJFileLoader.OPTIMIZE_WITH_UV)
  103932. tuplePosNorm[indicePositionFromObj].uv.push(indiceUvsFromObj);
  103933. }
  103934. else {
  103935. //The tuple already exists
  103936. //Add the index of the already existing tuple
  103937. //At this index we can get the value of position, normal and uvs of vertex
  103938. indicesForBabylon.push(_index);
  103939. }
  103940. };
  103941. /**
  103942. * Transform BABYLON.Vector() object onto 3 digits in an array
  103943. */
  103944. var unwrapData = function () {
  103945. //Every array has the same length
  103946. for (var l = 0; l < wrappedPositionForBabylon.length; l++) {
  103947. //Push the x, y, z values of each element in the unwrapped array
  103948. unwrappedPositionsForBabylon.push(wrappedPositionForBabylon[l].x, wrappedPositionForBabylon[l].y, wrappedPositionForBabylon[l].z);
  103949. unwrappedNormalsForBabylon.push(wrappedNormalsForBabylon[l].x, wrappedNormalsForBabylon[l].y, wrappedNormalsForBabylon[l].z);
  103950. unwrappedUVForBabylon.push(wrappedUvsForBabylon[l].x, wrappedUvsForBabylon[l].y); //z is an optional value not supported by BABYLON
  103951. }
  103952. // Reset arrays for the next new meshes
  103953. wrappedPositionForBabylon = [];
  103954. wrappedNormalsForBabylon = [];
  103955. wrappedUvsForBabylon = [];
  103956. tuplePosNorm = [];
  103957. curPositionInIndices = 0;
  103958. };
  103959. /**
  103960. * Create triangles from polygons by recursion
  103961. * The best to understand how it works is to draw it in the same time you get the recursion.
  103962. * It is important to notice that a triangle is a polygon
  103963. * We get 4 patterns of face defined in OBJ File :
  103964. * facePattern1 = ["1","2","3","4","5","6"]
  103965. * facePattern2 = ["1/1","2/2","3/3","4/4","5/5","6/6"]
  103966. * facePattern3 = ["1/1/1","2/2/2","3/3/3","4/4/4","5/5/5","6/6/6"]
  103967. * facePattern4 = ["1//1","2//2","3//3","4//4","5//5","6//6"]
  103968. * Each pattern is divided by the same method
  103969. * @param face Array[String] The indices of elements
  103970. * @param v Integer The variable to increment
  103971. */
  103972. var getTriangles = function (face, v) {
  103973. //Work for each element of the array
  103974. if (v + 1 < face.length) {
  103975. //Add on the triangle variable the indexes to obtain triangles
  103976. triangles.push(face[0], face[v], face[v + 1]);
  103977. //Incrementation for recursion
  103978. v += 1;
  103979. //Recursion
  103980. getTriangles(face, v);
  103981. }
  103982. //Result obtained after 2 iterations:
  103983. //Pattern1 => triangle = ["1","2","3","1","3","4"];
  103984. //Pattern2 => triangle = ["1/1","2/2","3/3","1/1","3/3","4/4"];
  103985. //Pattern3 => triangle = ["1/1/1","2/2/2","3/3/3","1/1/1","3/3/3","4/4/4"];
  103986. //Pattern4 => triangle = ["1//1","2//2","3//3","1//1","3//3","4//4"];
  103987. };
  103988. /**
  103989. * Create triangles and push the data for each polygon for the pattern 1
  103990. * In this pattern we get vertice positions
  103991. * @param face
  103992. * @param v
  103993. */
  103994. var setDataForCurrentFaceWithPattern1 = function (face, v) {
  103995. //Get the indices of triangles for each polygon
  103996. getTriangles(face, v);
  103997. //For each element in the triangles array.
  103998. //This var could contains 1 to an infinity of triangles
  103999. for (var k = 0; k < triangles.length; k++) {
  104000. // Set position indice
  104001. var indicePositionFromObj = parseInt(triangles[k]) - 1;
  104002. setData(indicePositionFromObj, 0, 0, //In the pattern 1, normals and uvs are not defined
  104003. positions[indicePositionFromObj], //Get the vectors data
  104004. BABYLON.Vector2.Zero(), BABYLON.Vector3.Up() //Create default vectors
  104005. );
  104006. }
  104007. //Reset variable for the next line
  104008. triangles = [];
  104009. };
  104010. /**
  104011. * Create triangles and push the data for each polygon for the pattern 2
  104012. * In this pattern we get vertice positions and uvsu
  104013. * @param face
  104014. * @param v
  104015. */
  104016. var setDataForCurrentFaceWithPattern2 = function (face, v) {
  104017. //Get the indices of triangles for each polygon
  104018. getTriangles(face, v);
  104019. for (var k = 0; k < triangles.length; k++) {
  104020. //triangle[k] = "1/1"
  104021. //Split the data for getting position and uv
  104022. var point = triangles[k].split("/"); // ["1", "1"]
  104023. //Set position indice
  104024. var indicePositionFromObj = parseInt(point[0]) - 1;
  104025. //Set uv indice
  104026. var indiceUvsFromObj = parseInt(point[1]) - 1;
  104027. setData(indicePositionFromObj, indiceUvsFromObj, 0, //Default value for normals
  104028. positions[indicePositionFromObj], //Get the values for each element
  104029. uvs[indiceUvsFromObj], BABYLON.Vector3.Up() //Default value for normals
  104030. );
  104031. }
  104032. //Reset variable for the next line
  104033. triangles = [];
  104034. };
  104035. /**
  104036. * Create triangles and push the data for each polygon for the pattern 3
  104037. * In this pattern we get vertice positions, uvs and normals
  104038. * @param face
  104039. * @param v
  104040. */
  104041. var setDataForCurrentFaceWithPattern3 = function (face, v) {
  104042. //Get the indices of triangles for each polygon
  104043. getTriangles(face, v);
  104044. for (var k = 0; k < triangles.length; k++) {
  104045. //triangle[k] = "1/1/1"
  104046. //Split the data for getting position, uv, and normals
  104047. var point = triangles[k].split("/"); // ["1", "1", "1"]
  104048. // Set position indice
  104049. var indicePositionFromObj = parseInt(point[0]) - 1;
  104050. // Set uv indice
  104051. var indiceUvsFromObj = parseInt(point[1]) - 1;
  104052. // Set normal indice
  104053. var indiceNormalFromObj = parseInt(point[2]) - 1;
  104054. setData(indicePositionFromObj, indiceUvsFromObj, indiceNormalFromObj, positions[indicePositionFromObj], uvs[indiceUvsFromObj], normals[indiceNormalFromObj] //Set the vector for each component
  104055. );
  104056. }
  104057. //Reset variable for the next line
  104058. triangles = [];
  104059. };
  104060. /**
  104061. * Create triangles and push the data for each polygon for the pattern 4
  104062. * In this pattern we get vertice positions and normals
  104063. * @param face
  104064. * @param v
  104065. */
  104066. var setDataForCurrentFaceWithPattern4 = function (face, v) {
  104067. getTriangles(face, v);
  104068. for (var k = 0; k < triangles.length; k++) {
  104069. //triangle[k] = "1//1"
  104070. //Split the data for getting position and normals
  104071. var point = triangles[k].split("//"); // ["1", "1"]
  104072. // We check indices, and normals
  104073. var indicePositionFromObj = parseInt(point[0]) - 1;
  104074. var indiceNormalFromObj = parseInt(point[1]) - 1;
  104075. setData(indicePositionFromObj, 1, //Default value for uv
  104076. indiceNormalFromObj, positions[indicePositionFromObj], //Get each vector of data
  104077. BABYLON.Vector2.Zero(), normals[indiceNormalFromObj]);
  104078. }
  104079. //Reset variable for the next line
  104080. triangles = [];
  104081. };
  104082. var addPreviousObjMesh = function () {
  104083. //Check if it is not the first mesh. Otherwise we don't have data.
  104084. if (meshesFromObj.length > 0) {
  104085. //Get the previous mesh for applying the data about the faces
  104086. //=> in obj file, faces definition append after the name of the mesh
  104087. handledMesh = meshesFromObj[meshesFromObj.length - 1];
  104088. //Set the data into Array for the mesh
  104089. unwrapData();
  104090. // Reverse tab. Otherwise face are displayed in the wrong sens
  104091. indicesForBabylon.reverse();
  104092. //Set the information for the mesh
  104093. //Slice the array to avoid rewriting because of the fact this is the same var which be rewrited
  104094. handledMesh.indices = indicesForBabylon.slice();
  104095. handledMesh.positions = unwrappedPositionsForBabylon.slice();
  104096. handledMesh.normals = unwrappedNormalsForBabylon.slice();
  104097. handledMesh.uvs = unwrappedUVForBabylon.slice();
  104098. //Reset the array for the next mesh
  104099. indicesForBabylon = [];
  104100. unwrappedPositionsForBabylon = [];
  104101. unwrappedNormalsForBabylon = [];
  104102. unwrappedUVForBabylon = [];
  104103. }
  104104. };
  104105. //Main function
  104106. //Split the file into lines
  104107. var lines = data.split('\n');
  104108. //Look at each line
  104109. for (var i = 0; i < lines.length; i++) {
  104110. var line = lines[i].trim();
  104111. var result;
  104112. //Comment or newLine
  104113. if (line.length === 0 || line.charAt(0) === '#') {
  104114. continue;
  104115. //Get information about one position possible for the vertices
  104116. }
  104117. else if ((result = this.vertexPattern.exec(line)) !== null) {
  104118. //Create a Vector3 with the position x, y, z
  104119. //Value of result:
  104120. // ["v 1.0 2.0 3.0", "1.0", "2.0", "3.0"]
  104121. //Add the Vector in the list of positions
  104122. positions.push(new BABYLON.Vector3(parseFloat(result[1]), parseFloat(result[2]), parseFloat(result[3])));
  104123. }
  104124. else if ((result = this.normalPattern.exec(line)) !== null) {
  104125. //Create a Vector3 with the normals x, y, z
  104126. //Value of result
  104127. // ["vn 1.0 2.0 3.0", "1.0", "2.0", "3.0"]
  104128. //Add the Vector in the list of normals
  104129. normals.push(new BABYLON.Vector3(parseFloat(result[1]), parseFloat(result[2]), parseFloat(result[3])));
  104130. }
  104131. else if ((result = this.uvPattern.exec(line)) !== null) {
  104132. //Create a Vector2 with the normals u, v
  104133. //Value of result
  104134. // ["vt 0.1 0.2 0.3", "0.1", "0.2"]
  104135. //Add the Vector in the list of uvs
  104136. uvs.push(new BABYLON.Vector2(parseFloat(result[1]), parseFloat(result[2])));
  104137. //Identify patterns of faces
  104138. //Face could be defined in different type of pattern
  104139. }
  104140. else if ((result = this.facePattern3.exec(line)) !== null) {
  104141. //Value of result:
  104142. //["f 1/1/1 2/2/2 3/3/3", "1/1/1 2/2/2 3/3/3"...]
  104143. //Set the data for this face
  104144. setDataForCurrentFaceWithPattern3(result[1].trim().split(" "), // ["1/1/1", "2/2/2", "3/3/3"]
  104145. 1);
  104146. }
  104147. else if ((result = this.facePattern4.exec(line)) !== null) {
  104148. //Value of result:
  104149. //["f 1//1 2//2 3//3", "1//1 2//2 3//3"...]
  104150. //Set the data for this face
  104151. setDataForCurrentFaceWithPattern4(result[1].trim().split(" "), // ["1//1", "2//2", "3//3"]
  104152. 1);
  104153. }
  104154. else if ((result = this.facePattern2.exec(line)) !== null) {
  104155. //Value of result:
  104156. //["f 1/1 2/2 3/3", "1/1 2/2 3/3"...]
  104157. //Set the data for this face
  104158. setDataForCurrentFaceWithPattern2(result[1].trim().split(" "), // ["1/1", "2/2", "3/3"]
  104159. 1);
  104160. }
  104161. else if ((result = this.facePattern1.exec(line)) !== null) {
  104162. //Value of result
  104163. //["f 1 2 3", "1 2 3"...]
  104164. //Set the data for this face
  104165. setDataForCurrentFaceWithPattern1(result[1].trim().split(" "), // ["1", "2", "3"]
  104166. 1);
  104167. //Define a mesh or an object
  104168. //Each time this keyword is analysed, create a new Object with all data for creating a babylonMesh
  104169. }
  104170. else if (this.group.test(line) || this.obj.test(line)) {
  104171. //Create a new mesh corresponding to the name of the group.
  104172. //Definition of the mesh
  104173. var objMesh =
  104174. //Set the name of the current obj mesh
  104175. {
  104176. name: line.substring(2).trim(),
  104177. indices: undefined,
  104178. positions: undefined,
  104179. normals: undefined,
  104180. uvs: undefined,
  104181. materialName: ""
  104182. };
  104183. addPreviousObjMesh();
  104184. //Push the last mesh created with only the name
  104185. meshesFromObj.push(objMesh);
  104186. //Set this variable to indicate that now meshesFromObj has objects defined inside
  104187. hasMeshes = true;
  104188. isFirstMaterial = true;
  104189. increment = 1;
  104190. //Keyword for applying a material
  104191. }
  104192. else if (this.usemtl.test(line)) {
  104193. //Get the name of the material
  104194. materialNameFromObj = line.substring(7).trim();
  104195. //If this new material is in the same mesh
  104196. if (!isFirstMaterial) {
  104197. //Set the data for the previous mesh
  104198. addPreviousObjMesh();
  104199. //Create a new mesh
  104200. var objMesh =
  104201. //Set the name of the current obj mesh
  104202. {
  104203. name: objMeshName + "_mm" + increment.toString(),
  104204. indices: undefined,
  104205. positions: undefined,
  104206. normals: undefined,
  104207. uvs: undefined,
  104208. materialName: materialNameFromObj
  104209. };
  104210. increment++;
  104211. //If meshes are already defined
  104212. meshesFromObj.push(objMesh);
  104213. }
  104214. //Set the material name if the previous line define a mesh
  104215. if (hasMeshes && isFirstMaterial) {
  104216. //Set the material name to the previous mesh (1 material per mesh)
  104217. meshesFromObj[meshesFromObj.length - 1].materialName = materialNameFromObj;
  104218. isFirstMaterial = false;
  104219. }
  104220. //Keyword for loading the mtl file
  104221. }
  104222. else if (this.mtllib.test(line)) {
  104223. //Get the name of mtl file
  104224. fileToLoad = line.substring(7).trim();
  104225. //Apply smoothing
  104226. }
  104227. else if (this.smooth.test(line)) {
  104228. // smooth shading => apply smoothing
  104229. //Toda y I don't know it work with babylon and with obj.
  104230. //With the obj file an integer is set
  104231. }
  104232. else {
  104233. //If there is another possibility
  104234. console.log("Unhandled expression at line : " + line);
  104235. }
  104236. }
  104237. //At the end of the file, add the last mesh into the meshesFromObj array
  104238. if (hasMeshes) {
  104239. //Set the data for the last mesh
  104240. handledMesh = meshesFromObj[meshesFromObj.length - 1];
  104241. //Reverse indices for displaying faces in the good sens
  104242. indicesForBabylon.reverse();
  104243. //Get the good array
  104244. unwrapData();
  104245. //Set array
  104246. handledMesh.indices = indicesForBabylon;
  104247. handledMesh.positions = unwrappedPositionsForBabylon;
  104248. handledMesh.normals = unwrappedNormalsForBabylon;
  104249. handledMesh.uvs = unwrappedUVForBabylon;
  104250. }
  104251. //If any o or g keyword found, create a mesj with a random id
  104252. if (!hasMeshes) {
  104253. // reverse tab of indices
  104254. indicesForBabylon.reverse();
  104255. //Get positions normals uvs
  104256. unwrapData();
  104257. //Set data for one mesh
  104258. meshesFromObj.push({
  104259. name: BABYLON.Geometry.RandomId(),
  104260. indices: indicesForBabylon,
  104261. positions: unwrappedPositionsForBabylon,
  104262. normals: unwrappedNormalsForBabylon,
  104263. uvs: unwrappedUVForBabylon,
  104264. materialName: materialNameFromObj
  104265. });
  104266. }
  104267. //Create a BABYLON.Mesh list
  104268. var babylonMeshesArray = []; //The mesh for babylon
  104269. var materialToUse = new Array();
  104270. //Set data for each mesh
  104271. for (var j = 0; j < meshesFromObj.length; j++) {
  104272. //check meshesNames (stlFileLoader)
  104273. if (meshesNames && meshesFromObj[j].name) {
  104274. if (meshesNames instanceof Array) {
  104275. if (meshesNames.indexOf(meshesFromObj[j].name) == -1) {
  104276. continue;
  104277. }
  104278. }
  104279. else {
  104280. if (meshesFromObj[j].name !== meshesNames) {
  104281. continue;
  104282. }
  104283. }
  104284. }
  104285. //Get the current mesh
  104286. //Set the data with VertexBuffer for each mesh
  104287. handledMesh = meshesFromObj[j];
  104288. //Create a BABYLON.Mesh with the name of the obj mesh
  104289. var babylonMesh = new BABYLON.Mesh(meshesFromObj[j].name, scene);
  104290. //Push the name of the material to an array
  104291. //This is indispensable for the importMesh function
  104292. materialToUse.push(meshesFromObj[j].materialName);
  104293. var vertexData = new BABYLON.VertexData(); //The container for the values
  104294. //Set the data for the babylonMesh
  104295. vertexData.positions = handledMesh.positions;
  104296. vertexData.normals = handledMesh.normals;
  104297. vertexData.uvs = handledMesh.uvs;
  104298. vertexData.indices = handledMesh.indices;
  104299. //Set the data from the VertexBuffer to the current BABYLON.Mesh
  104300. vertexData.applyToMesh(babylonMesh);
  104301. //Push the mesh into an array
  104302. babylonMeshesArray.push(babylonMesh);
  104303. }
  104304. //load the materials
  104305. //Check if we have a file to load
  104306. if (fileToLoad !== "") {
  104307. //Load the file synchronously
  104308. this._loadMTL(fileToLoad, rootUrl, function (dataLoaded) {
  104309. //Create materials thanks MTLLoader function
  104310. materialsFromMTLFile.parseMTL(scene, dataLoaded, rootUrl);
  104311. //Look at each material loaded in the mtl file
  104312. for (var n = 0; n < materialsFromMTLFile.materials.length; n++) {
  104313. //Three variables to get all meshes with the same material
  104314. var startIndex = 0;
  104315. var _indices = [];
  104316. var _index;
  104317. //The material from MTL file is used in the meshes loaded
  104318. //Push the indice in an array
  104319. //Check if the material is not used for another mesh
  104320. while ((_index = materialToUse.indexOf(materialsFromMTLFile.materials[n].name, startIndex)) > -1) {
  104321. _indices.push(_index);
  104322. startIndex = _index + 1;
  104323. }
  104324. //If the material is not used dispose it
  104325. if (_index == -1 && _indices.length == 0) {
  104326. //If the material is not needed, remove it
  104327. materialsFromMTLFile.materials[n].dispose();
  104328. }
  104329. else {
  104330. for (var o = 0; o < _indices.length; o++) {
  104331. //Apply the material to the BABYLON.Mesh for each mesh with the material
  104332. babylonMeshesArray[_indices[o]].material = materialsFromMTLFile.materials[n];
  104333. }
  104334. }
  104335. }
  104336. });
  104337. }
  104338. //Return an array with all BABYLON.Mesh
  104339. return babylonMeshesArray;
  104340. };
  104341. OBJFileLoader.OPTIMIZE_WITH_UV = false;
  104342. return OBJFileLoader;
  104343. }());
  104344. BABYLON.OBJFileLoader = OBJFileLoader;
  104345. if (BABYLON.SceneLoader) {
  104346. //Add this loader into the register plugin
  104347. BABYLON.SceneLoader.RegisterPlugin(new OBJFileLoader());
  104348. }
  104349. })(BABYLON || (BABYLON = {}));
  104350. //# sourceMappingURL=babylon.objFileLoader.js.map
  104351. var BABYLON;
  104352. (function (BABYLON) {
  104353. var GLTFLoaderCoordinateSystemMode;
  104354. (function (GLTFLoaderCoordinateSystemMode) {
  104355. /**
  104356. * Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene.
  104357. */
  104358. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["AUTO"] = 0] = "AUTO";
  104359. /**
  104360. * Sets the useRightHandedSystem flag on the scene.
  104361. */
  104362. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["FORCE_RIGHT_HANDED"] = 1] = "FORCE_RIGHT_HANDED";
  104363. })(GLTFLoaderCoordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode || (BABYLON.GLTFLoaderCoordinateSystemMode = {}));
  104364. var GLTFLoaderAnimationStartMode;
  104365. (function (GLTFLoaderAnimationStartMode) {
  104366. /**
  104367. * No animation will start.
  104368. */
  104369. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["NONE"] = 0] = "NONE";
  104370. /**
  104371. * The first animation will start.
  104372. */
  104373. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["FIRST"] = 1] = "FIRST";
  104374. /**
  104375. * All animations will start.
  104376. */
  104377. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["ALL"] = 2] = "ALL";
  104378. })(GLTFLoaderAnimationStartMode = BABYLON.GLTFLoaderAnimationStartMode || (BABYLON.GLTFLoaderAnimationStartMode = {}));
  104379. var GLTFLoaderState;
  104380. (function (GLTFLoaderState) {
  104381. GLTFLoaderState[GLTFLoaderState["Loading"] = 0] = "Loading";
  104382. GLTFLoaderState[GLTFLoaderState["Ready"] = 1] = "Ready";
  104383. GLTFLoaderState[GLTFLoaderState["Complete"] = 2] = "Complete";
  104384. })(GLTFLoaderState = BABYLON.GLTFLoaderState || (BABYLON.GLTFLoaderState = {}));
  104385. var GLTFFileLoader = /** @class */ (function () {
  104386. function GLTFFileLoader() {
  104387. // #region Common options
  104388. /**
  104389. * Raised when the asset has been parsed.
  104390. * The data.json property stores the glTF JSON.
  104391. * The data.bin property stores the BIN chunk from a glTF binary or null if the input is not a glTF binary.
  104392. */
  104393. this.onParsedObservable = new BABYLON.Observable();
  104394. // #endregion
  104395. // #region V2 options
  104396. /**
  104397. * The coordinate system mode (AUTO, FORCE_RIGHT_HANDED).
  104398. */
  104399. this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;
  104400. /**
  104401. * The animation start mode (NONE, FIRST, ALL).
  104402. */
  104403. this.animationStartMode = GLTFLoaderAnimationStartMode.FIRST;
  104404. /**
  104405. * Set to true to compile materials before raising the success callback.
  104406. */
  104407. this.compileMaterials = false;
  104408. /**
  104409. * Set to true to also compile materials with clip planes.
  104410. */
  104411. this.useClipPlane = false;
  104412. /**
  104413. * Set to true to compile shadow generators before raising the success callback.
  104414. */
  104415. this.compileShadowGenerators = false;
  104416. /**
  104417. * Raised when the loader creates a mesh after parsing the glTF properties of the mesh.
  104418. */
  104419. this.onMeshLoadedObservable = new BABYLON.Observable();
  104420. /**
  104421. * Raised when the loader creates a texture after parsing the glTF properties of the texture.
  104422. */
  104423. this.onTextureLoadedObservable = new BABYLON.Observable();
  104424. /**
  104425. * Raised when the loader creates a material after parsing the glTF properties of the material.
  104426. */
  104427. this.onMaterialLoadedObservable = new BABYLON.Observable();
  104428. /**
  104429. * Raised when the asset is completely loaded, immediately before the loader is disposed.
  104430. * For assets with LODs, raised when all of the LODs are complete.
  104431. * For assets without LODs, raised when the model is complete, immediately after onSuccess.
  104432. */
  104433. this.onCompleteObservable = new BABYLON.Observable();
  104434. /**
  104435. * Raised when the loader is disposed.
  104436. */
  104437. this.onDisposeObservable = new BABYLON.Observable();
  104438. /**
  104439. * Raised after a loader extension is created.
  104440. * Set additional options for a loader extension in this event.
  104441. */
  104442. this.onExtensionLoadedObservable = new BABYLON.Observable();
  104443. // #endregion
  104444. this._loader = null;
  104445. this.name = "gltf";
  104446. this.extensions = {
  104447. ".gltf": { isBinary: false },
  104448. ".glb": { isBinary: true }
  104449. };
  104450. }
  104451. Object.defineProperty(GLTFFileLoader.prototype, "onParsed", {
  104452. set: function (callback) {
  104453. if (this._onParsedObserver) {
  104454. this.onParsedObservable.remove(this._onParsedObserver);
  104455. }
  104456. this._onParsedObserver = this.onParsedObservable.add(callback);
  104457. },
  104458. enumerable: true,
  104459. configurable: true
  104460. });
  104461. Object.defineProperty(GLTFFileLoader.prototype, "onMeshLoaded", {
  104462. set: function (callback) {
  104463. if (this._onMeshLoadedObserver) {
  104464. this.onMeshLoadedObservable.remove(this._onMeshLoadedObserver);
  104465. }
  104466. this._onMeshLoadedObserver = this.onMeshLoadedObservable.add(callback);
  104467. },
  104468. enumerable: true,
  104469. configurable: true
  104470. });
  104471. Object.defineProperty(GLTFFileLoader.prototype, "onTextureLoaded", {
  104472. set: function (callback) {
  104473. if (this._onTextureLoadedObserver) {
  104474. this.onTextureLoadedObservable.remove(this._onTextureLoadedObserver);
  104475. }
  104476. this._onTextureLoadedObserver = this.onTextureLoadedObservable.add(callback);
  104477. },
  104478. enumerable: true,
  104479. configurable: true
  104480. });
  104481. Object.defineProperty(GLTFFileLoader.prototype, "onMaterialLoaded", {
  104482. set: function (callback) {
  104483. if (this._onMaterialLoadedObserver) {
  104484. this.onMaterialLoadedObservable.remove(this._onMaterialLoadedObserver);
  104485. }
  104486. this._onMaterialLoadedObserver = this.onMaterialLoadedObservable.add(callback);
  104487. },
  104488. enumerable: true,
  104489. configurable: true
  104490. });
  104491. Object.defineProperty(GLTFFileLoader.prototype, "onComplete", {
  104492. set: function (callback) {
  104493. if (this._onCompleteObserver) {
  104494. this.onCompleteObservable.remove(this._onCompleteObserver);
  104495. }
  104496. this._onCompleteObserver = this.onCompleteObservable.add(callback);
  104497. },
  104498. enumerable: true,
  104499. configurable: true
  104500. });
  104501. Object.defineProperty(GLTFFileLoader.prototype, "onDispose", {
  104502. set: function (callback) {
  104503. if (this._onDisposeObserver) {
  104504. this.onDisposeObservable.remove(this._onDisposeObserver);
  104505. }
  104506. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  104507. },
  104508. enumerable: true,
  104509. configurable: true
  104510. });
  104511. Object.defineProperty(GLTFFileLoader.prototype, "onExtensionLoaded", {
  104512. set: function (callback) {
  104513. if (this._onExtensionLoadedObserver) {
  104514. this.onExtensionLoadedObservable.remove(this._onExtensionLoadedObserver);
  104515. }
  104516. this._onExtensionLoadedObserver = this.onExtensionLoadedObservable.add(callback);
  104517. },
  104518. enumerable: true,
  104519. configurable: true
  104520. });
  104521. Object.defineProperty(GLTFFileLoader.prototype, "loaderState", {
  104522. /**
  104523. * The loader state or null if not active.
  104524. */
  104525. get: function () {
  104526. return this._loader ? this._loader.state : null;
  104527. },
  104528. enumerable: true,
  104529. configurable: true
  104530. });
  104531. /**
  104532. * Disposes the loader, releases resources during load, and cancels any outstanding requests.
  104533. */
  104534. GLTFFileLoader.prototype.dispose = function () {
  104535. if (this._loader) {
  104536. this._loader.dispose();
  104537. this._loader = null;
  104538. }
  104539. this.onMeshLoadedObservable.clear();
  104540. this.onTextureLoadedObservable.clear();
  104541. this.onMaterialLoadedObservable.clear();
  104542. this.onDisposeObservable.notifyObservers(this);
  104543. this.onDisposeObservable.clear();
  104544. };
  104545. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  104546. var _this = this;
  104547. return Promise.resolve().then(function () {
  104548. var loaderData = _this._parse(data);
  104549. _this._loader = _this._getLoader(loaderData);
  104550. return _this._loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onProgress);
  104551. });
  104552. };
  104553. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  104554. var _this = this;
  104555. return Promise.resolve().then(function () {
  104556. var loaderData = _this._parse(data);
  104557. _this._loader = _this._getLoader(loaderData);
  104558. return _this._loader.loadAsync(scene, loaderData, rootUrl, onProgress);
  104559. });
  104560. };
  104561. GLTFFileLoader.prototype.loadAssetContainerAsync = function (scene, data, rootUrl, onProgress) {
  104562. var _this = this;
  104563. return Promise.resolve().then(function () {
  104564. var loaderData = _this._parse(data);
  104565. _this._loader = _this._getLoader(loaderData);
  104566. return _this._loader.importMeshAsync(null, scene, loaderData, rootUrl, onProgress).then(function (result) {
  104567. var container = new BABYLON.AssetContainer(scene);
  104568. Array.prototype.push.apply(container.meshes, result.meshes);
  104569. Array.prototype.push.apply(container.particleSystems, result.particleSystems);
  104570. Array.prototype.push.apply(container.skeletons, result.skeletons);
  104571. container.removeAllFromScene();
  104572. return container;
  104573. });
  104574. });
  104575. };
  104576. GLTFFileLoader.prototype.canDirectLoad = function (data) {
  104577. return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
  104578. };
  104579. GLTFFileLoader.prototype.createPlugin = function () {
  104580. return new GLTFFileLoader();
  104581. };
  104582. GLTFFileLoader.prototype._parse = function (data) {
  104583. var parsedData;
  104584. if (data instanceof ArrayBuffer) {
  104585. parsedData = GLTFFileLoader._parseBinary(data);
  104586. }
  104587. else {
  104588. parsedData = {
  104589. json: JSON.parse(data),
  104590. bin: null
  104591. };
  104592. }
  104593. this.onParsedObservable.notifyObservers(parsedData);
  104594. this.onParsedObservable.clear();
  104595. return parsedData;
  104596. };
  104597. GLTFFileLoader.prototype._getLoader = function (loaderData) {
  104598. var _this = this;
  104599. var loaderVersion = { major: 2, minor: 0 };
  104600. var asset = loaderData.json.asset || {};
  104601. var version = GLTFFileLoader._parseVersion(asset.version);
  104602. if (!version) {
  104603. throw new Error("Invalid version: " + asset.version);
  104604. }
  104605. if (asset.minVersion !== undefined) {
  104606. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  104607. if (!minVersion) {
  104608. throw new Error("Invalid minimum version: " + asset.minVersion);
  104609. }
  104610. if (GLTFFileLoader._compareVersion(minVersion, loaderVersion) > 0) {
  104611. throw new Error("Incompatible minimum version: " + asset.minVersion);
  104612. }
  104613. }
  104614. var createLoaders = {
  104615. 1: GLTFFileLoader.CreateGLTFLoaderV1,
  104616. 2: GLTFFileLoader.CreateGLTFLoaderV2
  104617. };
  104618. var createLoader = createLoaders[version.major];
  104619. if (!createLoader) {
  104620. throw new Error("Unsupported version: " + asset.version);
  104621. }
  104622. var loader = createLoader();
  104623. loader.coordinateSystemMode = this.coordinateSystemMode;
  104624. loader.animationStartMode = this.animationStartMode;
  104625. loader.compileMaterials = this.compileMaterials;
  104626. loader.useClipPlane = this.useClipPlane;
  104627. loader.compileShadowGenerators = this.compileShadowGenerators;
  104628. loader.onMeshLoadedObservable.add(function (mesh) { return _this.onMeshLoadedObservable.notifyObservers(mesh); });
  104629. loader.onTextureLoadedObservable.add(function (texture) { return _this.onTextureLoadedObservable.notifyObservers(texture); });
  104630. loader.onMaterialLoadedObservable.add(function (material) { return _this.onMaterialLoadedObservable.notifyObservers(material); });
  104631. loader.onExtensionLoadedObservable.add(function (extension) { return _this.onExtensionLoadedObservable.notifyObservers(extension); });
  104632. loader.onCompleteObservable.add(function () {
  104633. _this.onMeshLoadedObservable.clear();
  104634. _this.onTextureLoadedObservable.clear();
  104635. _this.onMaterialLoadedObservable.clear();
  104636. _this.onCompleteObservable.notifyObservers(_this);
  104637. _this.onCompleteObservable.clear();
  104638. });
  104639. return loader;
  104640. };
  104641. GLTFFileLoader._parseBinary = function (data) {
  104642. var Binary = {
  104643. Magic: 0x46546C67
  104644. };
  104645. var binaryReader = new BinaryReader(data);
  104646. var magic = binaryReader.readUint32();
  104647. if (magic !== Binary.Magic) {
  104648. throw new Error("Unexpected magic: " + magic);
  104649. }
  104650. var version = binaryReader.readUint32();
  104651. switch (version) {
  104652. case 1: return GLTFFileLoader._parseV1(binaryReader);
  104653. case 2: return GLTFFileLoader._parseV2(binaryReader);
  104654. }
  104655. throw new Error("Unsupported version: " + version);
  104656. };
  104657. GLTFFileLoader._parseV1 = function (binaryReader) {
  104658. var ContentFormat = {
  104659. JSON: 0
  104660. };
  104661. var length = binaryReader.readUint32();
  104662. if (length != binaryReader.getLength()) {
  104663. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  104664. }
  104665. var contentLength = binaryReader.readUint32();
  104666. var contentFormat = binaryReader.readUint32();
  104667. var content;
  104668. switch (contentFormat) {
  104669. case ContentFormat.JSON: {
  104670. content = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength)));
  104671. break;
  104672. }
  104673. default: {
  104674. throw new Error("Unexpected content format: " + contentFormat);
  104675. }
  104676. }
  104677. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  104678. var body = binaryReader.readUint8Array(bytesRemaining);
  104679. return {
  104680. json: content,
  104681. bin: body
  104682. };
  104683. };
  104684. GLTFFileLoader._parseV2 = function (binaryReader) {
  104685. var ChunkFormat = {
  104686. JSON: 0x4E4F534A,
  104687. BIN: 0x004E4942
  104688. };
  104689. var length = binaryReader.readUint32();
  104690. if (length !== binaryReader.getLength()) {
  104691. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  104692. }
  104693. // JSON chunk
  104694. var chunkLength = binaryReader.readUint32();
  104695. var chunkFormat = binaryReader.readUint32();
  104696. if (chunkFormat !== ChunkFormat.JSON) {
  104697. throw new Error("First chunk format is not JSON");
  104698. }
  104699. var json = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength)));
  104700. // Look for BIN chunk
  104701. var bin = null;
  104702. while (binaryReader.getPosition() < binaryReader.getLength()) {
  104703. var chunkLength_1 = binaryReader.readUint32();
  104704. var chunkFormat_1 = binaryReader.readUint32();
  104705. switch (chunkFormat_1) {
  104706. case ChunkFormat.JSON: {
  104707. throw new Error("Unexpected JSON chunk");
  104708. }
  104709. case ChunkFormat.BIN: {
  104710. bin = binaryReader.readUint8Array(chunkLength_1);
  104711. break;
  104712. }
  104713. default: {
  104714. // ignore unrecognized chunkFormat
  104715. binaryReader.skipBytes(chunkLength_1);
  104716. break;
  104717. }
  104718. }
  104719. }
  104720. return {
  104721. json: json,
  104722. bin: bin
  104723. };
  104724. };
  104725. GLTFFileLoader._parseVersion = function (version) {
  104726. if (version === "1.0" || version === "1.0.1") {
  104727. return {
  104728. major: 1,
  104729. minor: 0
  104730. };
  104731. }
  104732. var match = (version + "").match(/^(\d+)\.(\d+)/);
  104733. if (!match) {
  104734. return null;
  104735. }
  104736. return {
  104737. major: parseInt(match[1]),
  104738. minor: parseInt(match[2])
  104739. };
  104740. };
  104741. GLTFFileLoader._compareVersion = function (a, b) {
  104742. if (a.major > b.major)
  104743. return 1;
  104744. if (a.major < b.major)
  104745. return -1;
  104746. if (a.minor > b.minor)
  104747. return 1;
  104748. if (a.minor < b.minor)
  104749. return -1;
  104750. return 0;
  104751. };
  104752. GLTFFileLoader._decodeBufferToText = function (buffer) {
  104753. var result = "";
  104754. var length = buffer.byteLength;
  104755. for (var i = 0; i < length; i++) {
  104756. result += String.fromCharCode(buffer[i]);
  104757. }
  104758. return result;
  104759. };
  104760. // #endregion
  104761. // #region V1 options
  104762. GLTFFileLoader.IncrementalLoading = true;
  104763. GLTFFileLoader.HomogeneousCoordinates = false;
  104764. return GLTFFileLoader;
  104765. }());
  104766. BABYLON.GLTFFileLoader = GLTFFileLoader;
  104767. var BinaryReader = /** @class */ (function () {
  104768. function BinaryReader(arrayBuffer) {
  104769. this._arrayBuffer = arrayBuffer;
  104770. this._dataView = new DataView(arrayBuffer);
  104771. this._byteOffset = 0;
  104772. }
  104773. BinaryReader.prototype.getPosition = function () {
  104774. return this._byteOffset;
  104775. };
  104776. BinaryReader.prototype.getLength = function () {
  104777. return this._arrayBuffer.byteLength;
  104778. };
  104779. BinaryReader.prototype.readUint32 = function () {
  104780. var value = this._dataView.getUint32(this._byteOffset, true);
  104781. this._byteOffset += 4;
  104782. return value;
  104783. };
  104784. BinaryReader.prototype.readUint8Array = function (length) {
  104785. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  104786. this._byteOffset += length;
  104787. return value;
  104788. };
  104789. BinaryReader.prototype.skipBytes = function (length) {
  104790. this._byteOffset += length;
  104791. };
  104792. return BinaryReader;
  104793. }());
  104794. if (BABYLON.SceneLoader) {
  104795. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  104796. }
  104797. })(BABYLON || (BABYLON = {}));
  104798. //# sourceMappingURL=babylon.glTFFileLoader.js.map
  104799. var BABYLON;
  104800. (function (BABYLON) {
  104801. var GLTF1;
  104802. (function (GLTF1) {
  104803. /**
  104804. * Enums
  104805. */
  104806. var EComponentType;
  104807. (function (EComponentType) {
  104808. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  104809. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  104810. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  104811. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  104812. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  104813. })(EComponentType = GLTF1.EComponentType || (GLTF1.EComponentType = {}));
  104814. var EShaderType;
  104815. (function (EShaderType) {
  104816. EShaderType[EShaderType["FRAGMENT"] = 35632] = "FRAGMENT";
  104817. EShaderType[EShaderType["VERTEX"] = 35633] = "VERTEX";
  104818. })(EShaderType = GLTF1.EShaderType || (GLTF1.EShaderType = {}));
  104819. var EParameterType;
  104820. (function (EParameterType) {
  104821. EParameterType[EParameterType["BYTE"] = 5120] = "BYTE";
  104822. EParameterType[EParameterType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  104823. EParameterType[EParameterType["SHORT"] = 5122] = "SHORT";
  104824. EParameterType[EParameterType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  104825. EParameterType[EParameterType["INT"] = 5124] = "INT";
  104826. EParameterType[EParameterType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  104827. EParameterType[EParameterType["FLOAT"] = 5126] = "FLOAT";
  104828. EParameterType[EParameterType["FLOAT_VEC2"] = 35664] = "FLOAT_VEC2";
  104829. EParameterType[EParameterType["FLOAT_VEC3"] = 35665] = "FLOAT_VEC3";
  104830. EParameterType[EParameterType["FLOAT_VEC4"] = 35666] = "FLOAT_VEC4";
  104831. EParameterType[EParameterType["INT_VEC2"] = 35667] = "INT_VEC2";
  104832. EParameterType[EParameterType["INT_VEC3"] = 35668] = "INT_VEC3";
  104833. EParameterType[EParameterType["INT_VEC4"] = 35669] = "INT_VEC4";
  104834. EParameterType[EParameterType["BOOL"] = 35670] = "BOOL";
  104835. EParameterType[EParameterType["BOOL_VEC2"] = 35671] = "BOOL_VEC2";
  104836. EParameterType[EParameterType["BOOL_VEC3"] = 35672] = "BOOL_VEC3";
  104837. EParameterType[EParameterType["BOOL_VEC4"] = 35673] = "BOOL_VEC4";
  104838. EParameterType[EParameterType["FLOAT_MAT2"] = 35674] = "FLOAT_MAT2";
  104839. EParameterType[EParameterType["FLOAT_MAT3"] = 35675] = "FLOAT_MAT3";
  104840. EParameterType[EParameterType["FLOAT_MAT4"] = 35676] = "FLOAT_MAT4";
  104841. EParameterType[EParameterType["SAMPLER_2D"] = 35678] = "SAMPLER_2D";
  104842. })(EParameterType = GLTF1.EParameterType || (GLTF1.EParameterType = {}));
  104843. var ETextureWrapMode;
  104844. (function (ETextureWrapMode) {
  104845. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  104846. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  104847. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  104848. })(ETextureWrapMode = GLTF1.ETextureWrapMode || (GLTF1.ETextureWrapMode = {}));
  104849. var ETextureFilterType;
  104850. (function (ETextureFilterType) {
  104851. ETextureFilterType[ETextureFilterType["NEAREST"] = 9728] = "NEAREST";
  104852. ETextureFilterType[ETextureFilterType["LINEAR"] = 9728] = "LINEAR";
  104853. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  104854. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  104855. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  104856. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  104857. })(ETextureFilterType = GLTF1.ETextureFilterType || (GLTF1.ETextureFilterType = {}));
  104858. var ETextureFormat;
  104859. (function (ETextureFormat) {
  104860. ETextureFormat[ETextureFormat["ALPHA"] = 6406] = "ALPHA";
  104861. ETextureFormat[ETextureFormat["RGB"] = 6407] = "RGB";
  104862. ETextureFormat[ETextureFormat["RGBA"] = 6408] = "RGBA";
  104863. ETextureFormat[ETextureFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  104864. ETextureFormat[ETextureFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  104865. })(ETextureFormat = GLTF1.ETextureFormat || (GLTF1.ETextureFormat = {}));
  104866. var ECullingType;
  104867. (function (ECullingType) {
  104868. ECullingType[ECullingType["FRONT"] = 1028] = "FRONT";
  104869. ECullingType[ECullingType["BACK"] = 1029] = "BACK";
  104870. ECullingType[ECullingType["FRONT_AND_BACK"] = 1032] = "FRONT_AND_BACK";
  104871. })(ECullingType = GLTF1.ECullingType || (GLTF1.ECullingType = {}));
  104872. var EBlendingFunction;
  104873. (function (EBlendingFunction) {
  104874. EBlendingFunction[EBlendingFunction["ZERO"] = 0] = "ZERO";
  104875. EBlendingFunction[EBlendingFunction["ONE"] = 1] = "ONE";
  104876. EBlendingFunction[EBlendingFunction["SRC_COLOR"] = 768] = "SRC_COLOR";
  104877. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_COLOR"] = 769] = "ONE_MINUS_SRC_COLOR";
  104878. EBlendingFunction[EBlendingFunction["DST_COLOR"] = 774] = "DST_COLOR";
  104879. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_COLOR"] = 775] = "ONE_MINUS_DST_COLOR";
  104880. EBlendingFunction[EBlendingFunction["SRC_ALPHA"] = 770] = "SRC_ALPHA";
  104881. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_ALPHA"] = 771] = "ONE_MINUS_SRC_ALPHA";
  104882. EBlendingFunction[EBlendingFunction["DST_ALPHA"] = 772] = "DST_ALPHA";
  104883. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_ALPHA"] = 773] = "ONE_MINUS_DST_ALPHA";
  104884. EBlendingFunction[EBlendingFunction["CONSTANT_COLOR"] = 32769] = "CONSTANT_COLOR";
  104885. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_COLOR"] = 32770] = "ONE_MINUS_CONSTANT_COLOR";
  104886. EBlendingFunction[EBlendingFunction["CONSTANT_ALPHA"] = 32771] = "CONSTANT_ALPHA";
  104887. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_ALPHA"] = 32772] = "ONE_MINUS_CONSTANT_ALPHA";
  104888. EBlendingFunction[EBlendingFunction["SRC_ALPHA_SATURATE"] = 776] = "SRC_ALPHA_SATURATE";
  104889. })(EBlendingFunction = GLTF1.EBlendingFunction || (GLTF1.EBlendingFunction = {}));
  104890. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  104891. })(BABYLON || (BABYLON = {}));
  104892. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  104893. var BABYLON;
  104894. (function (BABYLON) {
  104895. var GLTF1;
  104896. (function (GLTF1) {
  104897. /**
  104898. * Tokenizer. Used for shaders compatibility
  104899. * Automatically map world, view, projection, worldViewProjection, attributes and so on
  104900. */
  104901. var ETokenType;
  104902. (function (ETokenType) {
  104903. ETokenType[ETokenType["IDENTIFIER"] = 1] = "IDENTIFIER";
  104904. ETokenType[ETokenType["UNKNOWN"] = 2] = "UNKNOWN";
  104905. ETokenType[ETokenType["END_OF_INPUT"] = 3] = "END_OF_INPUT";
  104906. })(ETokenType || (ETokenType = {}));
  104907. var Tokenizer = /** @class */ (function () {
  104908. function Tokenizer(toParse) {
  104909. this._pos = 0;
  104910. this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;
  104911. this._toParse = toParse;
  104912. this._maxPos = toParse.length;
  104913. }
  104914. Tokenizer.prototype.getNextToken = function () {
  104915. if (this.isEnd())
  104916. return ETokenType.END_OF_INPUT;
  104917. this.currentString = this.read();
  104918. this.currentToken = ETokenType.UNKNOWN;
  104919. if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
  104920. this.currentToken = ETokenType.IDENTIFIER;
  104921. this.currentIdentifier = this.currentString;
  104922. while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_")) {
  104923. this.currentIdentifier += this.currentString;
  104924. this.forward();
  104925. }
  104926. }
  104927. return this.currentToken;
  104928. };
  104929. Tokenizer.prototype.peek = function () {
  104930. return this._toParse[this._pos];
  104931. };
  104932. Tokenizer.prototype.read = function () {
  104933. return this._toParse[this._pos++];
  104934. };
  104935. Tokenizer.prototype.forward = function () {
  104936. this._pos++;
  104937. };
  104938. Tokenizer.prototype.isEnd = function () {
  104939. return this._pos >= this._maxPos;
  104940. };
  104941. return Tokenizer;
  104942. }());
  104943. /**
  104944. * Values
  104945. */
  104946. var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
  104947. var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
  104948. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  104949. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  104950. /**
  104951. * Parse
  104952. */
  104953. var parseBuffers = function (parsedBuffers, gltfRuntime) {
  104954. for (var buf in parsedBuffers) {
  104955. var parsedBuffer = parsedBuffers[buf];
  104956. gltfRuntime.buffers[buf] = parsedBuffer;
  104957. gltfRuntime.buffersCount++;
  104958. }
  104959. };
  104960. var parseShaders = function (parsedShaders, gltfRuntime) {
  104961. for (var sha in parsedShaders) {
  104962. var parsedShader = parsedShaders[sha];
  104963. gltfRuntime.shaders[sha] = parsedShader;
  104964. gltfRuntime.shaderscount++;
  104965. }
  104966. };
  104967. var parseObject = function (parsedObjects, runtimeProperty, gltfRuntime) {
  104968. for (var object in parsedObjects) {
  104969. var parsedObject = parsedObjects[object];
  104970. gltfRuntime[runtimeProperty][object] = parsedObject;
  104971. }
  104972. };
  104973. /**
  104974. * Utils
  104975. */
  104976. var normalizeUVs = function (buffer) {
  104977. if (!buffer) {
  104978. return;
  104979. }
  104980. for (var i = 0; i < buffer.length / 2; i++) {
  104981. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  104982. }
  104983. };
  104984. var getAttribute = function (attributeParameter) {
  104985. if (attributeParameter.semantic === "NORMAL") {
  104986. return "normal";
  104987. }
  104988. else if (attributeParameter.semantic === "POSITION") {
  104989. return "position";
  104990. }
  104991. else if (attributeParameter.semantic === "JOINT") {
  104992. return "matricesIndices";
  104993. }
  104994. else if (attributeParameter.semantic === "WEIGHT") {
  104995. return "matricesWeights";
  104996. }
  104997. else if (attributeParameter.semantic === "COLOR") {
  104998. return "color";
  104999. }
  105000. else if (attributeParameter.semantic && attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
  105001. var channel = Number(attributeParameter.semantic.split("_")[1]);
  105002. return "uv" + (channel === 0 ? "" : channel + 1);
  105003. }
  105004. return null;
  105005. };
  105006. /**
  105007. * Loads and creates animations
  105008. */
  105009. var loadAnimations = function (gltfRuntime) {
  105010. for (var anim in gltfRuntime.animations) {
  105011. var animation = gltfRuntime.animations[anim];
  105012. if (!animation.channels || !animation.samplers) {
  105013. continue;
  105014. }
  105015. var lastAnimation = null;
  105016. for (var i = 0; i < animation.channels.length; i++) {
  105017. // Get parameters and load buffers
  105018. var channel = animation.channels[i];
  105019. var sampler = animation.samplers[channel.sampler];
  105020. if (!sampler) {
  105021. continue;
  105022. }
  105023. var inputData = null;
  105024. var outputData = null;
  105025. if (animation.parameters) {
  105026. inputData = animation.parameters[sampler.input];
  105027. outputData = animation.parameters[sampler.output];
  105028. }
  105029. else {
  105030. inputData = sampler.input;
  105031. outputData = sampler.output;
  105032. }
  105033. var bufferInput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
  105034. var bufferOutput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
  105035. var targetID = channel.target.id;
  105036. var targetNode = gltfRuntime.scene.getNodeByID(targetID);
  105037. if (targetNode === null) {
  105038. targetNode = gltfRuntime.scene.getNodeByName(targetID);
  105039. }
  105040. if (targetNode === null) {
  105041. BABYLON.Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to");
  105042. continue;
  105043. }
  105044. var isBone = targetNode instanceof BABYLON.Bone;
  105045. // Get target path (position, rotation or scaling)
  105046. var targetPath = channel.target.path;
  105047. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  105048. if (targetPathIndex !== -1) {
  105049. targetPath = babylonAnimationPaths[targetPathIndex];
  105050. }
  105051. // Determine animation type
  105052. var animationType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  105053. if (!isBone) {
  105054. if (targetPath === "rotationQuaternion") {
  105055. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  105056. targetNode.rotationQuaternion = new BABYLON.Quaternion();
  105057. }
  105058. else {
  105059. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  105060. }
  105061. }
  105062. // Create animation and key frames
  105063. var babylonAnimation = null;
  105064. var keys = [];
  105065. var arrayOffset = 0;
  105066. var modifyKey = false;
  105067. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  105068. babylonAnimation = lastAnimation;
  105069. modifyKey = true;
  105070. }
  105071. if (!modifyKey) {
  105072. babylonAnimation = new BABYLON.Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  105073. }
  105074. // For each frame
  105075. for (var j = 0; j < bufferInput.length; j++) {
  105076. var value = null;
  105077. if (targetPath === "rotationQuaternion") {
  105078. value = BABYLON.Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  105079. arrayOffset += 4;
  105080. }
  105081. else {
  105082. value = BABYLON.Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  105083. arrayOffset += 3;
  105084. }
  105085. if (isBone) {
  105086. var bone = targetNode;
  105087. var translation = BABYLON.Vector3.Zero();
  105088. var rotationQuaternion = new BABYLON.Quaternion();
  105089. var scaling = BABYLON.Vector3.Zero();
  105090. // Warning on decompose
  105091. var mat = bone.getBaseMatrix();
  105092. if (modifyKey && lastAnimation) {
  105093. mat = lastAnimation.getKeys()[j].value;
  105094. }
  105095. mat.decompose(scaling, rotationQuaternion, translation);
  105096. if (targetPath === "position") {
  105097. translation = value;
  105098. }
  105099. else if (targetPath === "rotationQuaternion") {
  105100. rotationQuaternion = value;
  105101. }
  105102. else {
  105103. scaling = value;
  105104. }
  105105. value = BABYLON.Matrix.Compose(scaling, rotationQuaternion, translation);
  105106. }
  105107. if (!modifyKey) {
  105108. keys.push({
  105109. frame: bufferInput[j],
  105110. value: value
  105111. });
  105112. }
  105113. else if (lastAnimation) {
  105114. lastAnimation.getKeys()[j].value = value;
  105115. }
  105116. }
  105117. // Finish
  105118. if (!modifyKey && babylonAnimation) {
  105119. babylonAnimation.setKeys(keys);
  105120. targetNode.animations.push(babylonAnimation);
  105121. }
  105122. lastAnimation = babylonAnimation;
  105123. gltfRuntime.scene.stopAnimation(targetNode);
  105124. gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  105125. }
  105126. }
  105127. };
  105128. /**
  105129. * Returns the bones transformation matrix
  105130. */
  105131. var configureBoneTransformation = function (node) {
  105132. var mat = null;
  105133. if (node.translation || node.rotation || node.scale) {
  105134. var scale = BABYLON.Vector3.FromArray(node.scale || [1, 1, 1]);
  105135. var rotation = BABYLON.Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
  105136. var position = BABYLON.Vector3.FromArray(node.translation || [0, 0, 0]);
  105137. mat = BABYLON.Matrix.Compose(scale, rotation, position);
  105138. }
  105139. else {
  105140. mat = BABYLON.Matrix.FromArray(node.matrix);
  105141. }
  105142. return mat;
  105143. };
  105144. /**
  105145. * Returns the parent bone
  105146. */
  105147. var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) {
  105148. // Try to find
  105149. for (var i = 0; i < newSkeleton.bones.length; i++) {
  105150. if (newSkeleton.bones[i].name === jointName) {
  105151. return newSkeleton.bones[i];
  105152. }
  105153. }
  105154. // Not found, search in gltf nodes
  105155. var nodes = gltfRuntime.nodes;
  105156. for (var nde in nodes) {
  105157. var node = nodes[nde];
  105158. if (!node.jointName) {
  105159. continue;
  105160. }
  105161. var children = node.children;
  105162. for (var i = 0; i < children.length; i++) {
  105163. var child = gltfRuntime.nodes[children[i]];
  105164. if (!child.jointName) {
  105165. continue;
  105166. }
  105167. if (child.jointName === jointName) {
  105168. var mat = configureBoneTransformation(node);
  105169. var bone = new BABYLON.Bone(node.name || "", newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
  105170. bone.id = nde;
  105171. return bone;
  105172. }
  105173. }
  105174. }
  105175. return null;
  105176. };
  105177. /**
  105178. * Returns the appropriate root node
  105179. */
  105180. var getNodeToRoot = function (nodesToRoot, id) {
  105181. for (var i = 0; i < nodesToRoot.length; i++) {
  105182. var nodeToRoot = nodesToRoot[i];
  105183. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  105184. var child = nodeToRoot.node.children[j];
  105185. if (child === id) {
  105186. return nodeToRoot.bone;
  105187. }
  105188. }
  105189. }
  105190. return null;
  105191. };
  105192. /**
  105193. * Returns the node with the joint name
  105194. */
  105195. var getJointNode = function (gltfRuntime, jointName) {
  105196. var nodes = gltfRuntime.nodes;
  105197. var node = nodes[jointName];
  105198. if (node) {
  105199. return {
  105200. node: node,
  105201. id: jointName
  105202. };
  105203. }
  105204. for (var nde in nodes) {
  105205. node = nodes[nde];
  105206. if (node.jointName === jointName) {
  105207. return {
  105208. node: node,
  105209. id: nde
  105210. };
  105211. }
  105212. }
  105213. return null;
  105214. };
  105215. /**
  105216. * Checks if a nodes is in joints
  105217. */
  105218. var nodeIsInJoints = function (skins, id) {
  105219. for (var i = 0; i < skins.jointNames.length; i++) {
  105220. if (skins.jointNames[i] === id) {
  105221. return true;
  105222. }
  105223. }
  105224. return false;
  105225. };
  105226. /**
  105227. * Fills the nodes to root for bones and builds hierarchy
  105228. */
  105229. var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) {
  105230. // Creates nodes for root
  105231. for (var nde in gltfRuntime.nodes) {
  105232. var node = gltfRuntime.nodes[nde];
  105233. var id = nde;
  105234. if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
  105235. continue;
  105236. }
  105237. // Create node to root bone
  105238. var mat = configureBoneTransformation(node);
  105239. var bone = new BABYLON.Bone(node.name || "", newSkeleton, null, mat);
  105240. bone.id = id;
  105241. nodesToRoot.push({ bone: bone, node: node, id: id });
  105242. }
  105243. // Parenting
  105244. for (var i = 0; i < nodesToRoot.length; i++) {
  105245. var nodeToRoot = nodesToRoot[i];
  105246. var children = nodeToRoot.node.children;
  105247. for (var j = 0; j < children.length; j++) {
  105248. var child = null;
  105249. for (var k = 0; k < nodesToRoot.length; k++) {
  105250. if (nodesToRoot[k].id === children[j]) {
  105251. child = nodesToRoot[k];
  105252. break;
  105253. }
  105254. }
  105255. if (child) {
  105256. child.bone._parent = nodeToRoot.bone;
  105257. nodeToRoot.bone.children.push(child.bone);
  105258. }
  105259. }
  105260. }
  105261. };
  105262. /**
  105263. * Imports a skeleton
  105264. */
  105265. var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton, id) {
  105266. if (!newSkeleton) {
  105267. newSkeleton = new BABYLON.Skeleton(skins.name || "", "", gltfRuntime.scene);
  105268. }
  105269. if (!skins.babylonSkeleton) {
  105270. return newSkeleton;
  105271. }
  105272. // Find the root bones
  105273. var nodesToRoot = [];
  105274. var nodesToRootToAdd = [];
  105275. getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
  105276. newSkeleton.bones = [];
  105277. // Joints
  105278. for (var i = 0; i < skins.jointNames.length; i++) {
  105279. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  105280. if (!jointNode) {
  105281. continue;
  105282. }
  105283. var node = jointNode.node;
  105284. if (!node) {
  105285. BABYLON.Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
  105286. continue;
  105287. }
  105288. var id = jointNode.id;
  105289. // Optimize, if the bone already exists...
  105290. var existingBone = gltfRuntime.scene.getBoneByID(id);
  105291. if (existingBone) {
  105292. newSkeleton.bones.push(existingBone);
  105293. continue;
  105294. }
  105295. // Search for parent bone
  105296. var foundBone = false;
  105297. var parentBone = null;
  105298. for (var j = 0; j < i; j++) {
  105299. var jointNode_1 = getJointNode(gltfRuntime, skins.jointNames[j]);
  105300. if (!jointNode_1) {
  105301. continue;
  105302. }
  105303. var joint = jointNode_1.node;
  105304. if (!joint) {
  105305. BABYLON.Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
  105306. continue;
  105307. }
  105308. var children = joint.children;
  105309. if (!children) {
  105310. continue;
  105311. }
  105312. foundBone = false;
  105313. for (var k = 0; k < children.length; k++) {
  105314. if (children[k] === id) {
  105315. parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
  105316. foundBone = true;
  105317. break;
  105318. }
  105319. }
  105320. if (foundBone) {
  105321. break;
  105322. }
  105323. }
  105324. // Create bone
  105325. var mat = configureBoneTransformation(node);
  105326. if (!parentBone && nodesToRoot.length > 0) {
  105327. parentBone = getNodeToRoot(nodesToRoot, id);
  105328. if (parentBone) {
  105329. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  105330. nodesToRootToAdd.push(parentBone);
  105331. }
  105332. }
  105333. }
  105334. var bone = new BABYLON.Bone(node.jointName || "", newSkeleton, parentBone, mat);
  105335. bone.id = id;
  105336. }
  105337. // Polish
  105338. var bones = newSkeleton.bones;
  105339. newSkeleton.bones = [];
  105340. for (var i = 0; i < skins.jointNames.length; i++) {
  105341. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  105342. if (!jointNode) {
  105343. continue;
  105344. }
  105345. for (var j = 0; j < bones.length; j++) {
  105346. if (bones[j].id === jointNode.id) {
  105347. newSkeleton.bones.push(bones[j]);
  105348. break;
  105349. }
  105350. }
  105351. }
  105352. newSkeleton.prepare();
  105353. // Finish
  105354. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  105355. newSkeleton.bones.push(nodesToRootToAdd[i]);
  105356. }
  105357. return newSkeleton;
  105358. };
  105359. /**
  105360. * Imports a mesh and its geometries
  105361. */
  105362. var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {
  105363. if (!newMesh) {
  105364. newMesh = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  105365. newMesh.id = id;
  105366. }
  105367. if (!node.babylonNode) {
  105368. return newMesh;
  105369. }
  105370. var subMaterials = [];
  105371. var vertexData = null;
  105372. var verticesStarts = new Array();
  105373. var verticesCounts = new Array();
  105374. var indexStarts = new Array();
  105375. var indexCounts = new Array();
  105376. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  105377. var meshID = meshes[meshIndex];
  105378. var mesh = gltfRuntime.meshes[meshID];
  105379. if (!mesh) {
  105380. continue;
  105381. }
  105382. // Positions, normals and UVs
  105383. for (var i = 0; i < mesh.primitives.length; i++) {
  105384. // Temporary vertex data
  105385. var tempVertexData = new BABYLON.VertexData();
  105386. var primitive = mesh.primitives[i];
  105387. if (primitive.mode !== 4) {
  105388. // continue;
  105389. }
  105390. var attributes = primitive.attributes;
  105391. var accessor = null;
  105392. var buffer = null;
  105393. // Set positions, normal and uvs
  105394. for (var semantic in attributes) {
  105395. // Link accessor and buffer view
  105396. accessor = gltfRuntime.accessors[attributes[semantic]];
  105397. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  105398. if (semantic === "NORMAL") {
  105399. tempVertexData.normals = new Float32Array(buffer.length);
  105400. tempVertexData.normals.set(buffer);
  105401. }
  105402. else if (semantic === "POSITION") {
  105403. if (BABYLON.GLTFFileLoader.HomogeneousCoordinates) {
  105404. tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
  105405. for (var j = 0; j < buffer.length; j += 4) {
  105406. tempVertexData.positions[j] = buffer[j];
  105407. tempVertexData.positions[j + 1] = buffer[j + 1];
  105408. tempVertexData.positions[j + 2] = buffer[j + 2];
  105409. }
  105410. }
  105411. else {
  105412. tempVertexData.positions = new Float32Array(buffer.length);
  105413. tempVertexData.positions.set(buffer);
  105414. }
  105415. verticesCounts.push(tempVertexData.positions.length);
  105416. }
  105417. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  105418. var channel = Number(semantic.split("_")[1]);
  105419. var uvKind = BABYLON.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  105420. var uvs = new Float32Array(buffer.length);
  105421. uvs.set(buffer);
  105422. normalizeUVs(uvs);
  105423. tempVertexData.set(uvs, uvKind);
  105424. }
  105425. else if (semantic === "JOINT") {
  105426. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  105427. tempVertexData.matricesIndices.set(buffer);
  105428. }
  105429. else if (semantic === "WEIGHT") {
  105430. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  105431. tempVertexData.matricesWeights.set(buffer);
  105432. }
  105433. else if (semantic === "COLOR") {
  105434. tempVertexData.colors = new Float32Array(buffer.length);
  105435. tempVertexData.colors.set(buffer);
  105436. }
  105437. }
  105438. // Indices
  105439. accessor = gltfRuntime.accessors[primitive.indices];
  105440. if (accessor) {
  105441. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  105442. tempVertexData.indices = new Int32Array(buffer.length);
  105443. tempVertexData.indices.set(buffer);
  105444. indexCounts.push(tempVertexData.indices.length);
  105445. }
  105446. else {
  105447. // Set indices on the fly
  105448. var indices = [];
  105449. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  105450. indices.push(j);
  105451. }
  105452. tempVertexData.indices = new Int32Array(indices);
  105453. indexCounts.push(tempVertexData.indices.length);
  105454. }
  105455. if (!vertexData) {
  105456. vertexData = tempVertexData;
  105457. }
  105458. else {
  105459. vertexData.merge(tempVertexData);
  105460. }
  105461. // Sub material
  105462. var material_1 = gltfRuntime.scene.getMaterialByID(primitive.material);
  105463. subMaterials.push(material_1 === null ? GLTF1.GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material_1);
  105464. // Update vertices start and index start
  105465. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  105466. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  105467. }
  105468. }
  105469. var material;
  105470. if (subMaterials.length > 1) {
  105471. material = new BABYLON.MultiMaterial("multimat" + id, gltfRuntime.scene);
  105472. material.subMaterials = subMaterials;
  105473. }
  105474. else {
  105475. material = new BABYLON.StandardMaterial("multimat" + id, gltfRuntime.scene);
  105476. }
  105477. if (subMaterials.length === 1) {
  105478. material = subMaterials[0];
  105479. }
  105480. if (!newMesh.material) {
  105481. newMesh.material = material;
  105482. }
  105483. // Apply geometry
  105484. new BABYLON.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  105485. newMesh.computeWorldMatrix(true);
  105486. // Apply submeshes
  105487. newMesh.subMeshes = [];
  105488. var index = 0;
  105489. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  105490. var meshID = meshes[meshIndex];
  105491. var mesh = gltfRuntime.meshes[meshID];
  105492. if (!mesh) {
  105493. continue;
  105494. }
  105495. for (var i = 0; i < mesh.primitives.length; i++) {
  105496. if (mesh.primitives[i].mode !== 4) {
  105497. //continue;
  105498. }
  105499. BABYLON.SubMesh.AddToMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  105500. index++;
  105501. }
  105502. }
  105503. // Finish
  105504. return newMesh;
  105505. };
  105506. /**
  105507. * Configure node transformation from position, rotation and scaling
  105508. */
  105509. var configureNode = function (newNode, position, rotation, scaling) {
  105510. if (newNode.position) {
  105511. newNode.position = position;
  105512. }
  105513. if (newNode.rotationQuaternion || newNode.rotation) {
  105514. newNode.rotationQuaternion = rotation;
  105515. }
  105516. if (newNode.scaling) {
  105517. newNode.scaling = scaling;
  105518. }
  105519. };
  105520. /**
  105521. * Configures node from transformation matrix
  105522. */
  105523. var configureNodeFromMatrix = function (newNode, node, parent) {
  105524. if (node.matrix) {
  105525. var position = new BABYLON.Vector3(0, 0, 0);
  105526. var rotation = new BABYLON.Quaternion();
  105527. var scaling = new BABYLON.Vector3(0, 0, 0);
  105528. var mat = BABYLON.Matrix.FromArray(node.matrix);
  105529. mat.decompose(scaling, rotation, position);
  105530. configureNode(newNode, position, rotation, scaling);
  105531. }
  105532. else if (node.translation && node.rotation && node.scale) {
  105533. configureNode(newNode, BABYLON.Vector3.FromArray(node.translation), BABYLON.Quaternion.FromArray(node.rotation), BABYLON.Vector3.FromArray(node.scale));
  105534. }
  105535. newNode.computeWorldMatrix(true);
  105536. };
  105537. /**
  105538. * Imports a node
  105539. */
  105540. var importNode = function (gltfRuntime, node, id, parent) {
  105541. var lastNode = null;
  105542. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  105543. if (gltfRuntime.importMeshesNames && gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name || "") === -1) {
  105544. return null;
  105545. }
  105546. }
  105547. // Meshes
  105548. if (node.skin) {
  105549. if (node.meshes) {
  105550. var skin = gltfRuntime.skins[node.skin];
  105551. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
  105552. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  105553. if (newMesh.skeleton === null) {
  105554. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  105555. if (!skin.babylonSkeleton) {
  105556. skin.babylonSkeleton = newMesh.skeleton;
  105557. }
  105558. }
  105559. lastNode = newMesh;
  105560. }
  105561. }
  105562. else if (node.meshes) {
  105563. /**
  105564. * Improve meshes property
  105565. */
  105566. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
  105567. lastNode = newMesh;
  105568. }
  105569. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  105570. var light = gltfRuntime.lights[node.light];
  105571. if (light) {
  105572. if (light.type === "ambient") {
  105573. var ambienLight = light[light.type];
  105574. var hemiLight = new BABYLON.HemisphericLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  105575. hemiLight.name = node.name || "";
  105576. if (ambienLight.color) {
  105577. hemiLight.diffuse = BABYLON.Color3.FromArray(ambienLight.color);
  105578. }
  105579. lastNode = hemiLight;
  105580. }
  105581. else if (light.type === "directional") {
  105582. var directionalLight = light[light.type];
  105583. var dirLight = new BABYLON.DirectionalLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  105584. dirLight.name = node.name || "";
  105585. if (directionalLight.color) {
  105586. dirLight.diffuse = BABYLON.Color3.FromArray(directionalLight.color);
  105587. }
  105588. lastNode = dirLight;
  105589. }
  105590. else if (light.type === "point") {
  105591. var pointLight = light[light.type];
  105592. var ptLight = new BABYLON.PointLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  105593. ptLight.name = node.name || "";
  105594. if (pointLight.color) {
  105595. ptLight.diffuse = BABYLON.Color3.FromArray(pointLight.color);
  105596. }
  105597. lastNode = ptLight;
  105598. }
  105599. else if (light.type === "spot") {
  105600. var spotLight = light[light.type];
  105601. var spLight = new BABYLON.SpotLight(node.light, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, gltfRuntime.scene);
  105602. spLight.name = node.name || "";
  105603. if (spotLight.color) {
  105604. spLight.diffuse = BABYLON.Color3.FromArray(spotLight.color);
  105605. }
  105606. if (spotLight.fallOfAngle) {
  105607. spLight.angle = spotLight.fallOfAngle;
  105608. }
  105609. if (spotLight.fallOffExponent) {
  105610. spLight.exponent = spotLight.fallOffExponent;
  105611. }
  105612. lastNode = spLight;
  105613. }
  105614. }
  105615. }
  105616. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  105617. var camera = gltfRuntime.cameras[node.camera];
  105618. if (camera) {
  105619. if (camera.type === "orthographic") {
  105620. var orthoCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  105621. orthoCamera.name = node.name || "";
  105622. orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  105623. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  105624. lastNode = orthoCamera;
  105625. }
  105626. else if (camera.type === "perspective") {
  105627. var perspectiveCamera = camera[camera.type];
  105628. var persCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  105629. persCamera.name = node.name || "";
  105630. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  105631. if (!perspectiveCamera.aspectRatio) {
  105632. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  105633. }
  105634. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  105635. persCamera.maxZ = perspectiveCamera.zfar;
  105636. persCamera.minZ = perspectiveCamera.znear;
  105637. }
  105638. lastNode = persCamera;
  105639. }
  105640. }
  105641. }
  105642. // Empty node
  105643. if (!node.jointName) {
  105644. if (node.babylonNode) {
  105645. return node.babylonNode;
  105646. }
  105647. else if (lastNode === null) {
  105648. var dummy = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  105649. node.babylonNode = dummy;
  105650. lastNode = dummy;
  105651. }
  105652. }
  105653. if (lastNode !== null) {
  105654. if (node.matrix && lastNode instanceof BABYLON.Mesh) {
  105655. configureNodeFromMatrix(lastNode, node, parent);
  105656. }
  105657. else {
  105658. var translation = node.translation || [0, 0, 0];
  105659. var rotation = node.rotation || [0, 0, 0, 1];
  105660. var scale = node.scale || [1, 1, 1];
  105661. configureNode(lastNode, BABYLON.Vector3.FromArray(translation), BABYLON.Quaternion.FromArray(rotation), BABYLON.Vector3.FromArray(scale));
  105662. }
  105663. lastNode.updateCache(true);
  105664. node.babylonNode = lastNode;
  105665. }
  105666. return lastNode;
  105667. };
  105668. /**
  105669. * Traverses nodes and creates them
  105670. */
  105671. var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
  105672. if (meshIncluded === void 0) { meshIncluded = false; }
  105673. var node = gltfRuntime.nodes[id];
  105674. var newNode = null;
  105675. if (gltfRuntime.importOnlyMeshes && !meshIncluded && gltfRuntime.importMeshesNames) {
  105676. if (gltfRuntime.importMeshesNames.indexOf(node.name || "") !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  105677. meshIncluded = true;
  105678. }
  105679. else {
  105680. meshIncluded = false;
  105681. }
  105682. }
  105683. else {
  105684. meshIncluded = true;
  105685. }
  105686. if (!node.jointName && meshIncluded) {
  105687. newNode = importNode(gltfRuntime, node, id, parent);
  105688. if (newNode !== null) {
  105689. newNode.id = id;
  105690. newNode.parent = parent;
  105691. }
  105692. }
  105693. if (node.children) {
  105694. for (var i = 0; i < node.children.length; i++) {
  105695. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  105696. }
  105697. }
  105698. };
  105699. /**
  105700. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  105701. */
  105702. var postLoad = function (gltfRuntime) {
  105703. // Nodes
  105704. var currentScene = gltfRuntime.currentScene;
  105705. if (currentScene) {
  105706. for (var i = 0; i < currentScene.nodes.length; i++) {
  105707. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  105708. }
  105709. }
  105710. else {
  105711. for (var thing in gltfRuntime.scenes) {
  105712. currentScene = gltfRuntime.scenes[thing];
  105713. for (var i = 0; i < currentScene.nodes.length; i++) {
  105714. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  105715. }
  105716. }
  105717. }
  105718. // Set animations
  105719. loadAnimations(gltfRuntime);
  105720. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  105721. var skeleton = gltfRuntime.scene.skeletons[i];
  105722. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  105723. }
  105724. };
  105725. /**
  105726. * onBind shaderrs callback to set uniforms and matrices
  105727. */
  105728. var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
  105729. var materialValues = material.values || technique.parameters;
  105730. for (var unif in unTreatedUniforms) {
  105731. var uniform = unTreatedUniforms[unif];
  105732. var type = uniform.type;
  105733. if (type === GLTF1.EParameterType.FLOAT_MAT2 || type === GLTF1.EParameterType.FLOAT_MAT3 || type === GLTF1.EParameterType.FLOAT_MAT4) {
  105734. if (uniform.semantic && !uniform.source && !uniform.node) {
  105735. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  105736. }
  105737. else if (uniform.semantic && (uniform.source || uniform.node)) {
  105738. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node || "");
  105739. if (source === null) {
  105740. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node || "");
  105741. }
  105742. if (source === null) {
  105743. continue;
  105744. }
  105745. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  105746. }
  105747. }
  105748. else {
  105749. var value = materialValues[technique.uniforms[unif]];
  105750. if (!value) {
  105751. continue;
  105752. }
  105753. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  105754. var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
  105755. if (texture === null || texture === undefined) {
  105756. continue;
  105757. }
  105758. shaderMaterial.getEffect().setTexture(unif, texture);
  105759. }
  105760. else {
  105761. GLTF1.GLTFUtils.SetUniform((shaderMaterial.getEffect()), unif, value, type);
  105762. }
  105763. }
  105764. }
  105765. onSuccess(shaderMaterial);
  105766. };
  105767. /**
  105768. * Prepare uniforms to send the only one time
  105769. * Loads the appropriate textures
  105770. */
  105771. var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
  105772. var materialValues = material.values || technique.parameters;
  105773. var techniqueUniforms = technique.uniforms;
  105774. /**
  105775. * Prepare values here (not matrices)
  105776. */
  105777. for (var unif in unTreatedUniforms) {
  105778. var uniform = unTreatedUniforms[unif];
  105779. var type = uniform.type;
  105780. var value = materialValues[techniqueUniforms[unif]];
  105781. if (value === undefined) {
  105782. // In case the value is the same for all materials
  105783. value = uniform.value;
  105784. }
  105785. if (!value) {
  105786. continue;
  105787. }
  105788. var onLoadTexture = function (uniformName) {
  105789. return function (texture) {
  105790. if (uniform.value && uniformName) {
  105791. // Static uniform
  105792. shaderMaterial.setTexture(uniformName, texture);
  105793. delete unTreatedUniforms[uniformName];
  105794. }
  105795. };
  105796. };
  105797. // Texture (sampler2D)
  105798. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  105799. GLTF1.GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); });
  105800. }
  105801. else {
  105802. if (uniform.value && GLTF1.GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
  105803. // Static uniform
  105804. delete unTreatedUniforms[unif];
  105805. }
  105806. }
  105807. }
  105808. };
  105809. /**
  105810. * Shader compilation failed
  105811. */
  105812. var onShaderCompileError = function (program, shaderMaterial, onError) {
  105813. return function (effect, error) {
  105814. shaderMaterial.dispose(true);
  105815. onError("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  105816. };
  105817. };
  105818. /**
  105819. * Shader compilation success
  105820. */
  105821. var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
  105822. return function (_) {
  105823. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  105824. shaderMaterial.onBind = function (mesh) {
  105825. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  105826. };
  105827. };
  105828. };
  105829. /**
  105830. * Returns the appropriate uniform if already handled by babylon
  105831. */
  105832. var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
  105833. for (var unif in technique.uniforms) {
  105834. var uniform = technique.uniforms[unif];
  105835. var uniformParameter = technique.parameters[uniform];
  105836. if (tokenizer.currentIdentifier === unif) {
  105837. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  105838. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  105839. if (transformIndex !== -1) {
  105840. delete unTreatedUniforms[unif];
  105841. return babylonTransforms[transformIndex];
  105842. }
  105843. }
  105844. }
  105845. }
  105846. return tokenizer.currentIdentifier;
  105847. };
  105848. /**
  105849. * All shaders loaded. Create materials one by one
  105850. */
  105851. var importMaterials = function (gltfRuntime) {
  105852. // Create materials
  105853. for (var mat in gltfRuntime.materials) {
  105854. GLTF1.GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });
  105855. }
  105856. };
  105857. /**
  105858. * Implementation of the base glTF spec
  105859. */
  105860. var GLTFLoaderBase = /** @class */ (function () {
  105861. function GLTFLoaderBase() {
  105862. }
  105863. GLTFLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
  105864. var gltfRuntime = {
  105865. extensions: {},
  105866. accessors: {},
  105867. buffers: {},
  105868. bufferViews: {},
  105869. meshes: {},
  105870. lights: {},
  105871. cameras: {},
  105872. nodes: {},
  105873. images: {},
  105874. textures: {},
  105875. shaders: {},
  105876. programs: {},
  105877. samplers: {},
  105878. techniques: {},
  105879. materials: {},
  105880. animations: {},
  105881. skins: {},
  105882. extensionsUsed: [],
  105883. scenes: {},
  105884. buffersCount: 0,
  105885. shaderscount: 0,
  105886. scene: scene,
  105887. rootUrl: rootUrl,
  105888. loadedBufferCount: 0,
  105889. loadedBufferViews: {},
  105890. loadedShaderCount: 0,
  105891. importOnlyMeshes: false,
  105892. dummyNodes: []
  105893. };
  105894. // Parse
  105895. if (parsedData.extensions) {
  105896. parseObject(parsedData.extensions, "extensions", gltfRuntime);
  105897. }
  105898. if (parsedData.extensionsUsed) {
  105899. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  105900. }
  105901. if (parsedData.buffers) {
  105902. parseBuffers(parsedData.buffers, gltfRuntime);
  105903. }
  105904. if (parsedData.bufferViews) {
  105905. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  105906. }
  105907. if (parsedData.accessors) {
  105908. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  105909. }
  105910. if (parsedData.meshes) {
  105911. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  105912. }
  105913. if (parsedData.lights) {
  105914. parseObject(parsedData.lights, "lights", gltfRuntime);
  105915. }
  105916. if (parsedData.cameras) {
  105917. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  105918. }
  105919. if (parsedData.nodes) {
  105920. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  105921. }
  105922. if (parsedData.images) {
  105923. parseObject(parsedData.images, "images", gltfRuntime);
  105924. }
  105925. if (parsedData.textures) {
  105926. parseObject(parsedData.textures, "textures", gltfRuntime);
  105927. }
  105928. if (parsedData.shaders) {
  105929. parseShaders(parsedData.shaders, gltfRuntime);
  105930. }
  105931. if (parsedData.programs) {
  105932. parseObject(parsedData.programs, "programs", gltfRuntime);
  105933. }
  105934. if (parsedData.samplers) {
  105935. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  105936. }
  105937. if (parsedData.techniques) {
  105938. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  105939. }
  105940. if (parsedData.materials) {
  105941. parseObject(parsedData.materials, "materials", gltfRuntime);
  105942. }
  105943. if (parsedData.animations) {
  105944. parseObject(parsedData.animations, "animations", gltfRuntime);
  105945. }
  105946. if (parsedData.skins) {
  105947. parseObject(parsedData.skins, "skins", gltfRuntime);
  105948. }
  105949. if (parsedData.scenes) {
  105950. gltfRuntime.scenes = parsedData.scenes;
  105951. }
  105952. if (parsedData.scene && parsedData.scenes) {
  105953. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  105954. }
  105955. return gltfRuntime;
  105956. };
  105957. GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  105958. var buffer = gltfRuntime.buffers[id];
  105959. if (BABYLON.Tools.IsBase64(buffer.uri)) {
  105960. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(buffer.uri))); });
  105961. }
  105962. else {
  105963. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, undefined, true, function (request) {
  105964. if (request) {
  105965. onError(request.status + " " + request.statusText);
  105966. }
  105967. });
  105968. }
  105969. };
  105970. GLTFLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  105971. var texture = gltfRuntime.textures[id];
  105972. if (!texture || !texture.source) {
  105973. onError("");
  105974. return;
  105975. }
  105976. if (texture.babylonTexture) {
  105977. onSuccess(null);
  105978. return;
  105979. }
  105980. var source = gltfRuntime.images[texture.source];
  105981. if (BABYLON.Tools.IsBase64(source.uri)) {
  105982. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(source.uri))); });
  105983. }
  105984. else {
  105985. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, undefined, undefined, true, function (request) {
  105986. if (request) {
  105987. onError(request.status + " " + request.statusText);
  105988. }
  105989. });
  105990. }
  105991. };
  105992. GLTFLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  105993. var texture = gltfRuntime.textures[id];
  105994. if (texture.babylonTexture) {
  105995. onSuccess(texture.babylonTexture);
  105996. return;
  105997. }
  105998. var sampler = gltfRuntime.samplers[texture.sampler];
  105999. var createMipMaps = (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  106000. (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  106001. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  106002. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  106003. var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  106004. var blob = new Blob([buffer]);
  106005. var blobURL = URL.createObjectURL(blob);
  106006. var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
  106007. var newTexture = new BABYLON.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  106008. if (sampler.wrapS !== undefined) {
  106009. newTexture.wrapU = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapS);
  106010. }
  106011. if (sampler.wrapT !== undefined) {
  106012. newTexture.wrapV = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapT);
  106013. }
  106014. newTexture.name = id;
  106015. texture.babylonTexture = newTexture;
  106016. onSuccess(newTexture);
  106017. };
  106018. GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  106019. var shader = gltfRuntime.shaders[id];
  106020. if (BABYLON.Tools.IsBase64(shader.uri)) {
  106021. var shaderString = atob(shader.uri.split(",")[1]);
  106022. onSuccess(shaderString);
  106023. }
  106024. else {
  106025. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, undefined, undefined, false, function (request) {
  106026. if (request) {
  106027. onError(request.status + " " + request.statusText);
  106028. }
  106029. });
  106030. }
  106031. };
  106032. GLTFLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  106033. var material = gltfRuntime.materials[id];
  106034. if (!material.technique) {
  106035. if (onError) {
  106036. onError("No technique found.");
  106037. }
  106038. return;
  106039. }
  106040. var technique = gltfRuntime.techniques[material.technique];
  106041. if (!technique) {
  106042. var defaultMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  106043. defaultMaterial.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  106044. defaultMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  106045. onSuccess(defaultMaterial);
  106046. return;
  106047. }
  106048. var program = gltfRuntime.programs[technique.program];
  106049. var states = technique.states;
  106050. var vertexShader = BABYLON.Effect.ShadersStore[program.vertexShader + "VertexShader"];
  106051. var pixelShader = BABYLON.Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  106052. var newVertexShader = "";
  106053. var newPixelShader = "";
  106054. var vertexTokenizer = new Tokenizer(vertexShader);
  106055. var pixelTokenizer = new Tokenizer(pixelShader);
  106056. var unTreatedUniforms = {};
  106057. var uniforms = [];
  106058. var attributes = [];
  106059. var samplers = [];
  106060. // Fill uniform, sampler2D and attributes
  106061. for (var unif in technique.uniforms) {
  106062. var uniform = technique.uniforms[unif];
  106063. var uniformParameter = technique.parameters[uniform];
  106064. unTreatedUniforms[unif] = uniformParameter;
  106065. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  106066. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  106067. if (transformIndex !== -1) {
  106068. uniforms.push(babylonTransforms[transformIndex]);
  106069. delete unTreatedUniforms[unif];
  106070. }
  106071. else {
  106072. uniforms.push(unif);
  106073. }
  106074. }
  106075. else if (uniformParameter.type === GLTF1.EParameterType.SAMPLER_2D) {
  106076. samplers.push(unif);
  106077. }
  106078. else {
  106079. uniforms.push(unif);
  106080. }
  106081. }
  106082. for (var attr in technique.attributes) {
  106083. var attribute = technique.attributes[attr];
  106084. var attributeParameter = technique.parameters[attribute];
  106085. if (attributeParameter.semantic) {
  106086. attributes.push(getAttribute(attributeParameter));
  106087. }
  106088. }
  106089. // Configure vertex shader
  106090. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  106091. var tokenType = vertexTokenizer.currentToken;
  106092. if (tokenType !== ETokenType.IDENTIFIER) {
  106093. newVertexShader += vertexTokenizer.currentString;
  106094. continue;
  106095. }
  106096. var foundAttribute = false;
  106097. for (var attr in technique.attributes) {
  106098. var attribute = technique.attributes[attr];
  106099. var attributeParameter = technique.parameters[attribute];
  106100. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  106101. newVertexShader += getAttribute(attributeParameter);
  106102. foundAttribute = true;
  106103. break;
  106104. }
  106105. }
  106106. if (foundAttribute) {
  106107. continue;
  106108. }
  106109. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  106110. }
  106111. // Configure pixel shader
  106112. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  106113. var tokenType = pixelTokenizer.currentToken;
  106114. if (tokenType !== ETokenType.IDENTIFIER) {
  106115. newPixelShader += pixelTokenizer.currentString;
  106116. continue;
  106117. }
  106118. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  106119. }
  106120. // Create shader material
  106121. var shaderPath = {
  106122. vertex: program.vertexShader + id,
  106123. fragment: program.fragmentShader + id
  106124. };
  106125. var options = {
  106126. attributes: attributes,
  106127. uniforms: uniforms,
  106128. samplers: samplers,
  106129. needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1
  106130. };
  106131. BABYLON.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  106132. BABYLON.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  106133. var shaderMaterial = new BABYLON.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  106134. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  106135. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  106136. shaderMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  106137. if (states && states.functions) {
  106138. var functions = states.functions;
  106139. if (functions.cullFace && functions.cullFace[0] !== GLTF1.ECullingType.BACK) {
  106140. shaderMaterial.backFaceCulling = false;
  106141. }
  106142. var blendFunc = functions.blendFuncSeparate;
  106143. if (blendFunc) {
  106144. if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE_MINUS_SRC_ALPHA && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  106145. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  106146. }
  106147. else if (blendFunc[0] === GLTF1.EBlendingFunction.ONE && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  106148. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  106149. }
  106150. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  106151. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ADD;
  106152. }
  106153. else if (blendFunc[0] === GLTF1.EBlendingFunction.ZERO && blendFunc[1] === GLTF1.EBlendingFunction.ONE_MINUS_SRC_COLOR && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  106154. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_SUBTRACT;
  106155. }
  106156. else if (blendFunc[0] === GLTF1.EBlendingFunction.DST_COLOR && blendFunc[1] === GLTF1.EBlendingFunction.ZERO && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  106157. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MULTIPLY;
  106158. }
  106159. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE_MINUS_SRC_COLOR && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  106160. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MAXIMIZED;
  106161. }
  106162. }
  106163. }
  106164. };
  106165. return GLTFLoaderBase;
  106166. }());
  106167. GLTF1.GLTFLoaderBase = GLTFLoaderBase;
  106168. /**
  106169. * glTF V1 Loader
  106170. */
  106171. var GLTFLoader = /** @class */ (function () {
  106172. function GLTFLoader() {
  106173. // #region Stubs for IGLTFLoader interface
  106174. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  106175. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  106176. this.compileMaterials = false;
  106177. this.useClipPlane = false;
  106178. this.compileShadowGenerators = false;
  106179. this.onDisposeObservable = new BABYLON.Observable();
  106180. this.onMeshLoadedObservable = new BABYLON.Observable();
  106181. this.onTextureLoadedObservable = new BABYLON.Observable();
  106182. this.onMaterialLoadedObservable = new BABYLON.Observable();
  106183. this.onCompleteObservable = new BABYLON.Observable();
  106184. this.onExtensionLoadedObservable = new BABYLON.Observable();
  106185. this.state = null;
  106186. }
  106187. GLTFLoader.RegisterExtension = function (extension) {
  106188. if (GLTFLoader.Extensions[extension.name]) {
  106189. BABYLON.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  106190. return;
  106191. }
  106192. GLTFLoader.Extensions[extension.name] = extension;
  106193. };
  106194. GLTFLoader.prototype.dispose = function () { };
  106195. // #endregion
  106196. GLTFLoader.prototype._importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  106197. var _this = this;
  106198. scene.useRightHandedSystem = true;
  106199. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  106200. gltfRuntime.importOnlyMeshes = true;
  106201. if (meshesNames === "") {
  106202. gltfRuntime.importMeshesNames = [];
  106203. }
  106204. else if (typeof meshesNames === "string") {
  106205. gltfRuntime.importMeshesNames = [meshesNames];
  106206. }
  106207. else if (meshesNames && !(meshesNames instanceof Array)) {
  106208. gltfRuntime.importMeshesNames = [meshesNames];
  106209. }
  106210. else {
  106211. gltfRuntime.importMeshesNames = [];
  106212. BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]");
  106213. }
  106214. // Create nodes
  106215. _this._createNodes(gltfRuntime);
  106216. var meshes = new Array();
  106217. var skeletons = new Array();
  106218. // Fill arrays of meshes and skeletons
  106219. for (var nde in gltfRuntime.nodes) {
  106220. var node = gltfRuntime.nodes[nde];
  106221. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  106222. meshes.push(node.babylonNode);
  106223. }
  106224. }
  106225. for (var skl in gltfRuntime.skins) {
  106226. var skin = gltfRuntime.skins[skl];
  106227. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  106228. skeletons.push(skin.babylonSkeleton);
  106229. }
  106230. }
  106231. // Load buffers, shaders, materials, etc.
  106232. _this._loadBuffersAsync(gltfRuntime, function () {
  106233. _this._loadShadersAsync(gltfRuntime, function () {
  106234. importMaterials(gltfRuntime);
  106235. postLoad(gltfRuntime);
  106236. if (!BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  106237. onSuccess(meshes, [], skeletons);
  106238. }
  106239. });
  106240. }, onProgress);
  106241. if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  106242. onSuccess(meshes, [], skeletons);
  106243. }
  106244. }, onError);
  106245. return true;
  106246. };
  106247. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  106248. var _this = this;
  106249. return new Promise(function (resolve, reject) {
  106250. _this._importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  106251. resolve({
  106252. meshes: meshes,
  106253. particleSystems: particleSystems,
  106254. skeletons: skeletons
  106255. });
  106256. }, onProgress, function (message) {
  106257. reject(new Error(message));
  106258. });
  106259. });
  106260. };
  106261. GLTFLoader.prototype._loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  106262. var _this = this;
  106263. scene.useRightHandedSystem = true;
  106264. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  106265. // Load runtime extensios
  106266. GLTF1.GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () {
  106267. // Create nodes
  106268. _this._createNodes(gltfRuntime);
  106269. // Load buffers, shaders, materials, etc.
  106270. _this._loadBuffersAsync(gltfRuntime, function () {
  106271. _this._loadShadersAsync(gltfRuntime, function () {
  106272. importMaterials(gltfRuntime);
  106273. postLoad(gltfRuntime);
  106274. if (!BABYLON.GLTFFileLoader.IncrementalLoading) {
  106275. onSuccess();
  106276. }
  106277. });
  106278. });
  106279. if (BABYLON.GLTFFileLoader.IncrementalLoading) {
  106280. onSuccess();
  106281. }
  106282. }, onError);
  106283. }, onError);
  106284. };
  106285. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  106286. var _this = this;
  106287. return new Promise(function (resolve, reject) {
  106288. _this._loadAsync(scene, data, rootUrl, function () {
  106289. resolve();
  106290. }, onProgress, function (message) {
  106291. reject(new Error(message));
  106292. });
  106293. });
  106294. };
  106295. GLTFLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
  106296. var hasShaders = false;
  106297. var processShader = function (sha, shader) {
  106298. GLTF1.GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
  106299. gltfRuntime.loadedShaderCount++;
  106300. if (shaderString) {
  106301. BABYLON.Effect.ShadersStore[sha + (shader.type === GLTF1.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  106302. }
  106303. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  106304. onload();
  106305. }
  106306. }, function () {
  106307. BABYLON.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  106308. });
  106309. };
  106310. for (var sha in gltfRuntime.shaders) {
  106311. hasShaders = true;
  106312. var shader = gltfRuntime.shaders[sha];
  106313. if (shader) {
  106314. processShader.bind(this, sha, shader)();
  106315. }
  106316. else {
  106317. BABYLON.Tools.Error("No shader named: " + sha);
  106318. }
  106319. }
  106320. if (!hasShaders) {
  106321. onload();
  106322. }
  106323. };
  106324. ;
  106325. GLTFLoader.prototype._loadBuffersAsync = function (gltfRuntime, onLoad, onProgress) {
  106326. var hasBuffers = false;
  106327. var processBuffer = function (buf, buffer) {
  106328. GLTF1.GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
  106329. gltfRuntime.loadedBufferCount++;
  106330. if (bufferView) {
  106331. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  106332. BABYLON.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  106333. }
  106334. gltfRuntime.loadedBufferViews[buf] = bufferView;
  106335. }
  106336. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  106337. onLoad();
  106338. }
  106339. }, function () {
  106340. BABYLON.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  106341. });
  106342. };
  106343. for (var buf in gltfRuntime.buffers) {
  106344. hasBuffers = true;
  106345. var buffer = gltfRuntime.buffers[buf];
  106346. if (buffer) {
  106347. processBuffer.bind(this, buf, buffer)();
  106348. }
  106349. else {
  106350. BABYLON.Tools.Error("No buffer named: " + buf);
  106351. }
  106352. }
  106353. if (!hasBuffers) {
  106354. onLoad();
  106355. }
  106356. };
  106357. GLTFLoader.prototype._createNodes = function (gltfRuntime) {
  106358. var currentScene = gltfRuntime.currentScene;
  106359. if (currentScene) {
  106360. // Only one scene even if multiple scenes are defined
  106361. for (var i = 0; i < currentScene.nodes.length; i++) {
  106362. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  106363. }
  106364. }
  106365. else {
  106366. // Load all scenes
  106367. for (var thing in gltfRuntime.scenes) {
  106368. currentScene = gltfRuntime.scenes[thing];
  106369. for (var i = 0; i < currentScene.nodes.length; i++) {
  106370. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  106371. }
  106372. }
  106373. }
  106374. };
  106375. GLTFLoader.Extensions = {};
  106376. return GLTFLoader;
  106377. }());
  106378. GLTF1.GLTFLoader = GLTFLoader;
  106379. ;
  106380. BABYLON.GLTFFileLoader.CreateGLTFLoaderV1 = function () { return new GLTFLoader(); };
  106381. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  106382. })(BABYLON || (BABYLON = {}));
  106383. //# sourceMappingURL=babylon.glTFLoader.js.map
  106384. var BABYLON;
  106385. (function (BABYLON) {
  106386. var GLTF1;
  106387. (function (GLTF1) {
  106388. /**
  106389. * Utils functions for GLTF
  106390. */
  106391. var GLTFUtils = /** @class */ (function () {
  106392. function GLTFUtils() {
  106393. }
  106394. /**
  106395. * Sets the given "parameter" matrix
  106396. * @param scene: the {BABYLON.Scene} object
  106397. * @param source: the source node where to pick the matrix
  106398. * @param parameter: the GLTF technique parameter
  106399. * @param uniformName: the name of the shader's uniform
  106400. * @param shaderMaterial: the shader material
  106401. */
  106402. GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {
  106403. var mat = null;
  106404. if (parameter.semantic === "MODEL") {
  106405. mat = source.getWorldMatrix();
  106406. }
  106407. else if (parameter.semantic === "PROJECTION") {
  106408. mat = scene.getProjectionMatrix();
  106409. }
  106410. else if (parameter.semantic === "VIEW") {
  106411. mat = scene.getViewMatrix();
  106412. }
  106413. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  106414. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  106415. }
  106416. else if (parameter.semantic === "MODELVIEW") {
  106417. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  106418. }
  106419. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  106420. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  106421. }
  106422. else if (parameter.semantic === "MODELINVERSE") {
  106423. mat = source.getWorldMatrix().invert();
  106424. }
  106425. else if (parameter.semantic === "VIEWINVERSE") {
  106426. mat = scene.getViewMatrix().invert();
  106427. }
  106428. else if (parameter.semantic === "PROJECTIONINVERSE") {
  106429. mat = scene.getProjectionMatrix().invert();
  106430. }
  106431. else if (parameter.semantic === "MODELVIEWINVERSE") {
  106432. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  106433. }
  106434. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  106435. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  106436. }
  106437. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  106438. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().invert());
  106439. }
  106440. else {
  106441. debugger;
  106442. }
  106443. if (mat) {
  106444. switch (parameter.type) {
  106445. case GLTF1.EParameterType.FLOAT_MAT2:
  106446. shaderMaterial.setMatrix2x2(uniformName, BABYLON.Matrix.GetAsMatrix2x2(mat));
  106447. break;
  106448. case GLTF1.EParameterType.FLOAT_MAT3:
  106449. shaderMaterial.setMatrix3x3(uniformName, BABYLON.Matrix.GetAsMatrix3x3(mat));
  106450. break;
  106451. case GLTF1.EParameterType.FLOAT_MAT4:
  106452. shaderMaterial.setMatrix(uniformName, mat);
  106453. break;
  106454. default: break;
  106455. }
  106456. }
  106457. };
  106458. /**
  106459. * Sets the given "parameter" matrix
  106460. * @param shaderMaterial: the shader material
  106461. * @param uniform: the name of the shader's uniform
  106462. * @param value: the value of the uniform
  106463. * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)
  106464. */
  106465. GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {
  106466. switch (type) {
  106467. case GLTF1.EParameterType.FLOAT:
  106468. shaderMaterial.setFloat(uniform, value);
  106469. return true;
  106470. case GLTF1.EParameterType.FLOAT_VEC2:
  106471. shaderMaterial.setVector2(uniform, BABYLON.Vector2.FromArray(value));
  106472. return true;
  106473. case GLTF1.EParameterType.FLOAT_VEC3:
  106474. shaderMaterial.setVector3(uniform, BABYLON.Vector3.FromArray(value));
  106475. return true;
  106476. case GLTF1.EParameterType.FLOAT_VEC4:
  106477. shaderMaterial.setVector4(uniform, BABYLON.Vector4.FromArray(value));
  106478. return true;
  106479. default: return false;
  106480. }
  106481. };
  106482. /**
  106483. * Returns the wrap mode of the texture
  106484. * @param mode: the mode value
  106485. */
  106486. GLTFUtils.GetWrapMode = function (mode) {
  106487. switch (mode) {
  106488. case GLTF1.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  106489. case GLTF1.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  106490. case GLTF1.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  106491. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  106492. }
  106493. };
  106494. /**
  106495. * Returns the byte stride giving an accessor
  106496. * @param accessor: the GLTF accessor objet
  106497. */
  106498. GLTFUtils.GetByteStrideFromType = function (accessor) {
  106499. // Needs this function since "byteStride" isn't requiered in glTF format
  106500. var type = accessor.type;
  106501. switch (type) {
  106502. case "VEC2": return 2;
  106503. case "VEC3": return 3;
  106504. case "VEC4": return 4;
  106505. case "MAT2": return 4;
  106506. case "MAT3": return 9;
  106507. case "MAT4": return 16;
  106508. default: return 1;
  106509. }
  106510. };
  106511. /**
  106512. * Returns the texture filter mode giving a mode value
  106513. * @param mode: the filter mode value
  106514. */
  106515. GLTFUtils.GetTextureFilterMode = function (mode) {
  106516. switch (mode) {
  106517. case GLTF1.ETextureFilterType.LINEAR:
  106518. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  106519. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  106520. case GLTF1.ETextureFilterType.NEAREST:
  106521. case GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  106522. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  106523. }
  106524. };
  106525. GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) {
  106526. var byteOffset = bufferView.byteOffset + byteOffset;
  106527. var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];
  106528. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  106529. throw new Error("Buffer access is out of range");
  106530. }
  106531. var buffer = loadedBufferView.buffer;
  106532. byteOffset += loadedBufferView.byteOffset;
  106533. switch (componentType) {
  106534. case GLTF1.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  106535. case GLTF1.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  106536. case GLTF1.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  106537. case GLTF1.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  106538. default: return new Float32Array(buffer, byteOffset, byteLength);
  106539. }
  106540. };
  106541. /**
  106542. * Returns a buffer from its accessor
  106543. * @param gltfRuntime: the GLTF runtime
  106544. * @param accessor: the GLTF accessor
  106545. */
  106546. GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {
  106547. var bufferView = gltfRuntime.bufferViews[accessor.bufferView];
  106548. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  106549. return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  106550. };
  106551. /**
  106552. * Decodes a buffer view into a string
  106553. * @param view: the buffer view
  106554. */
  106555. GLTFUtils.DecodeBufferToText = function (view) {
  106556. var result = "";
  106557. var length = view.byteLength;
  106558. for (var i = 0; i < length; ++i) {
  106559. result += String.fromCharCode(view[i]);
  106560. }
  106561. return result;
  106562. };
  106563. /**
  106564. * Returns the default material of gltf. Related to
  106565. * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material
  106566. * @param scene: the Babylon.js scene
  106567. */
  106568. GLTFUtils.GetDefaultMaterial = function (scene) {
  106569. if (!GLTFUtils._DefaultMaterial) {
  106570. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialVertexShader"] = [
  106571. "precision highp float;",
  106572. "",
  106573. "uniform mat4 worldView;",
  106574. "uniform mat4 projection;",
  106575. "",
  106576. "attribute vec3 position;",
  106577. "",
  106578. "void main(void)",
  106579. "{",
  106580. " gl_Position = projection * worldView * vec4(position, 1.0);",
  106581. "}"
  106582. ].join("\n");
  106583. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialPixelShader"] = [
  106584. "precision highp float;",
  106585. "",
  106586. "uniform vec4 u_emission;",
  106587. "",
  106588. "void main(void)",
  106589. "{",
  106590. " gl_FragColor = u_emission;",
  106591. "}"
  106592. ].join("\n");
  106593. var shaderPath = {
  106594. vertex: "GLTFDefaultMaterial",
  106595. fragment: "GLTFDefaultMaterial"
  106596. };
  106597. var options = {
  106598. attributes: ["position"],
  106599. uniforms: ["worldView", "projection", "u_emission"],
  106600. samplers: new Array(),
  106601. needAlphaBlending: false
  106602. };
  106603. GLTFUtils._DefaultMaterial = new BABYLON.ShaderMaterial("GLTFDefaultMaterial", scene, shaderPath, options);
  106604. GLTFUtils._DefaultMaterial.setColor4("u_emission", new BABYLON.Color4(0.5, 0.5, 0.5, 1.0));
  106605. }
  106606. return GLTFUtils._DefaultMaterial;
  106607. };
  106608. // The GLTF default material
  106609. GLTFUtils._DefaultMaterial = null;
  106610. return GLTFUtils;
  106611. }());
  106612. GLTF1.GLTFUtils = GLTFUtils;
  106613. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  106614. })(BABYLON || (BABYLON = {}));
  106615. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  106616. var BABYLON;
  106617. (function (BABYLON) {
  106618. var GLTF1;
  106619. (function (GLTF1) {
  106620. var GLTFLoaderExtension = /** @class */ (function () {
  106621. function GLTFLoaderExtension(name) {
  106622. this._name = name;
  106623. }
  106624. Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
  106625. get: function () {
  106626. return this._name;
  106627. },
  106628. enumerable: true,
  106629. configurable: true
  106630. });
  106631. /**
  106632. * Defines an override for loading the runtime
  106633. * Return true to stop further extensions from loading the runtime
  106634. */
  106635. GLTFLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  106636. return false;
  106637. };
  106638. /**
  106639. * Defines an onverride for creating gltf runtime
  106640. * Return true to stop further extensions from creating the runtime
  106641. */
  106642. GLTFLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  106643. return false;
  106644. };
  106645. /**
  106646. * Defines an override for loading buffers
  106647. * Return true to stop further extensions from loading this buffer
  106648. */
  106649. GLTFLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  106650. return false;
  106651. };
  106652. /**
  106653. * Defines an override for loading texture buffers
  106654. * Return true to stop further extensions from loading this texture data
  106655. */
  106656. GLTFLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  106657. return false;
  106658. };
  106659. /**
  106660. * Defines an override for creating textures
  106661. * Return true to stop further extensions from loading this texture
  106662. */
  106663. GLTFLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  106664. return false;
  106665. };
  106666. /**
  106667. * Defines an override for loading shader strings
  106668. * Return true to stop further extensions from loading this shader data
  106669. */
  106670. GLTFLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  106671. return false;
  106672. };
  106673. /**
  106674. * Defines an override for loading materials
  106675. * Return true to stop further extensions from loading this material
  106676. */
  106677. GLTFLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  106678. return false;
  106679. };
  106680. // ---------
  106681. // Utilities
  106682. // ---------
  106683. GLTFLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  106684. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  106685. return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
  106686. }, function () {
  106687. setTimeout(function () {
  106688. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  106689. });
  106690. });
  106691. };
  106692. GLTFLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  106693. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  106694. return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);
  106695. }, function () {
  106696. setTimeout(function () {
  106697. onSuccess();
  106698. });
  106699. });
  106700. };
  106701. GLTFLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  106702. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  106703. return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  106704. }, function () {
  106705. GLTF1.GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  106706. });
  106707. };
  106708. GLTFLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
  106709. GLTFLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) { return GLTFLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError); }, onError);
  106710. };
  106711. GLTFLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  106712. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  106713. return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  106714. }, function () {
  106715. GLTF1.GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  106716. });
  106717. };
  106718. GLTFLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  106719. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  106720. return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  106721. }, function () {
  106722. GLTF1.GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  106723. });
  106724. };
  106725. GLTFLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  106726. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  106727. return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  106728. }, function () {
  106729. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  106730. });
  106731. };
  106732. GLTFLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  106733. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  106734. return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  106735. }, function () {
  106736. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  106737. });
  106738. };
  106739. GLTFLoaderExtension.ApplyExtensions = function (func, defaultFunc) {
  106740. for (var extensionName in GLTF1.GLTFLoader.Extensions) {
  106741. var loaderExtension = GLTF1.GLTFLoader.Extensions[extensionName];
  106742. if (func(loaderExtension)) {
  106743. return;
  106744. }
  106745. }
  106746. defaultFunc();
  106747. };
  106748. return GLTFLoaderExtension;
  106749. }());
  106750. GLTF1.GLTFLoaderExtension = GLTFLoaderExtension;
  106751. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  106752. })(BABYLON || (BABYLON = {}));
  106753. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  106754. var BABYLON;
  106755. (function (BABYLON) {
  106756. var GLTF1;
  106757. (function (GLTF1) {
  106758. var BinaryExtensionBufferName = "binary_glTF";
  106759. ;
  106760. ;
  106761. var GLTFBinaryExtension = /** @class */ (function (_super) {
  106762. __extends(GLTFBinaryExtension, _super);
  106763. function GLTFBinaryExtension() {
  106764. return _super.call(this, "KHR_binary_glTF") || this;
  106765. }
  106766. GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  106767. var extensionsUsed = data.json.extensionsUsed;
  106768. if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1 || !data.bin) {
  106769. return false;
  106770. }
  106771. this._bin = data.bin;
  106772. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  106773. return true;
  106774. };
  106775. GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  106776. if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {
  106777. return false;
  106778. }
  106779. if (id !== BinaryExtensionBufferName) {
  106780. return false;
  106781. }
  106782. onSuccess(this._bin);
  106783. return true;
  106784. };
  106785. GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  106786. var texture = gltfRuntime.textures[id];
  106787. var source = gltfRuntime.images[texture.source];
  106788. if (!source.extensions || !(this.name in source.extensions)) {
  106789. return false;
  106790. }
  106791. var sourceExt = source.extensions[this.name];
  106792. var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];
  106793. var buffer = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  106794. onSuccess(buffer);
  106795. return true;
  106796. };
  106797. GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  106798. var shader = gltfRuntime.shaders[id];
  106799. if (!shader.extensions || !(this.name in shader.extensions)) {
  106800. return false;
  106801. }
  106802. var binaryExtensionShader = shader.extensions[this.name];
  106803. var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];
  106804. var shaderBytes = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  106805. setTimeout(function () {
  106806. var shaderString = GLTF1.GLTFUtils.DecodeBufferToText(shaderBytes);
  106807. onSuccess(shaderString);
  106808. });
  106809. return true;
  106810. };
  106811. return GLTFBinaryExtension;
  106812. }(GLTF1.GLTFLoaderExtension));
  106813. GLTF1.GLTFBinaryExtension = GLTFBinaryExtension;
  106814. GLTF1.GLTFLoader.RegisterExtension(new GLTFBinaryExtension());
  106815. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  106816. })(BABYLON || (BABYLON = {}));
  106817. //# sourceMappingURL=babylon.glTFBinaryExtension.js.map
  106818. var BABYLON;
  106819. (function (BABYLON) {
  106820. var GLTF1;
  106821. (function (GLTF1) {
  106822. ;
  106823. ;
  106824. ;
  106825. var GLTFMaterialsCommonExtension = /** @class */ (function (_super) {
  106826. __extends(GLTFMaterialsCommonExtension, _super);
  106827. function GLTFMaterialsCommonExtension() {
  106828. return _super.call(this, "KHR_materials_common") || this;
  106829. }
  106830. GLTFMaterialsCommonExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  106831. if (!gltfRuntime.extensions)
  106832. return false;
  106833. var extension = gltfRuntime.extensions[this.name];
  106834. if (!extension)
  106835. return false;
  106836. // Create lights
  106837. var lights = extension.lights;
  106838. if (lights) {
  106839. for (var thing in lights) {
  106840. var light = lights[thing];
  106841. switch (light.type) {
  106842. case "ambient":
  106843. var ambientLight = new BABYLON.HemisphericLight(light.name, new BABYLON.Vector3(0, 1, 0), gltfRuntime.scene);
  106844. var ambient = light.ambient;
  106845. if (ambient) {
  106846. ambientLight.diffuse = BABYLON.Color3.FromArray(ambient.color || [1, 1, 1]);
  106847. }
  106848. break;
  106849. case "point":
  106850. var pointLight = new BABYLON.PointLight(light.name, new BABYLON.Vector3(10, 10, 10), gltfRuntime.scene);
  106851. var point = light.point;
  106852. if (point) {
  106853. pointLight.diffuse = BABYLON.Color3.FromArray(point.color || [1, 1, 1]);
  106854. }
  106855. break;
  106856. case "directional":
  106857. var dirLight = new BABYLON.DirectionalLight(light.name, new BABYLON.Vector3(0, -1, 0), gltfRuntime.scene);
  106858. var directional = light.directional;
  106859. if (directional) {
  106860. dirLight.diffuse = BABYLON.Color3.FromArray(directional.color || [1, 1, 1]);
  106861. }
  106862. break;
  106863. case "spot":
  106864. var spot = light.spot;
  106865. if (spot) {
  106866. var spotLight = new BABYLON.SpotLight(light.name, new BABYLON.Vector3(0, 10, 0), new BABYLON.Vector3(0, -1, 0), spot.fallOffAngle || Math.PI, spot.fallOffExponent || 0.0, gltfRuntime.scene);
  106867. spotLight.diffuse = BABYLON.Color3.FromArray(spot.color || [1, 1, 1]);
  106868. }
  106869. break;
  106870. default:
  106871. BABYLON.Tools.Warn("GLTF Material Common extension: light type \"" + light.type + "\” not supported");
  106872. break;
  106873. }
  106874. }
  106875. }
  106876. return false;
  106877. };
  106878. GLTFMaterialsCommonExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  106879. var material = gltfRuntime.materials[id];
  106880. if (!material || !material.extensions)
  106881. return false;
  106882. var extension = material.extensions[this.name];
  106883. if (!extension)
  106884. return false;
  106885. var standardMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  106886. standardMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  106887. if (extension.technique === "CONSTANT") {
  106888. standardMaterial.disableLighting = true;
  106889. }
  106890. standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided;
  106891. standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency;
  106892. standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess;
  106893. // Ambient
  106894. if (typeof extension.values.ambient === "string") {
  106895. this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, "ambientTexture", onError);
  106896. }
  106897. else {
  106898. standardMaterial.ambientColor = BABYLON.Color3.FromArray(extension.values.ambient || [0, 0, 0]);
  106899. }
  106900. // Diffuse
  106901. if (typeof extension.values.diffuse === "string") {
  106902. this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, "diffuseTexture", onError);
  106903. }
  106904. else {
  106905. standardMaterial.diffuseColor = BABYLON.Color3.FromArray(extension.values.diffuse || [0, 0, 0]);
  106906. }
  106907. // Emission
  106908. if (typeof extension.values.emission === "string") {
  106909. this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, "emissiveTexture", onError);
  106910. }
  106911. else {
  106912. standardMaterial.emissiveColor = BABYLON.Color3.FromArray(extension.values.emission || [0, 0, 0]);
  106913. }
  106914. // Specular
  106915. if (typeof extension.values.specular === "string") {
  106916. this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, "specularTexture", onError);
  106917. }
  106918. else {
  106919. standardMaterial.specularColor = BABYLON.Color3.FromArray(extension.values.specular || [0, 0, 0]);
  106920. }
  106921. return true;
  106922. };
  106923. GLTFMaterialsCommonExtension.prototype._loadTexture = function (gltfRuntime, id, material, propertyPath, onError) {
  106924. // Create buffer from texture url
  106925. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  106926. // Create texture from buffer
  106927. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, function (texture) { return material[propertyPath] = texture; }, onError);
  106928. }, onError);
  106929. };
  106930. return GLTFMaterialsCommonExtension;
  106931. }(GLTF1.GLTFLoaderExtension));
  106932. GLTF1.GLTFMaterialsCommonExtension = GLTFMaterialsCommonExtension;
  106933. GLTF1.GLTFLoader.RegisterExtension(new GLTFMaterialsCommonExtension());
  106934. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  106935. })(BABYLON || (BABYLON = {}));
  106936. //# sourceMappingURL=babylon.glTFMaterialsCommonExtension.js.map
  106937. var BABYLON;
  106938. (function (BABYLON) {
  106939. var GLTF2;
  106940. (function (GLTF2) {
  106941. var ArrayItem = /** @class */ (function () {
  106942. function ArrayItem() {
  106943. }
  106944. ArrayItem.Assign = function (values) {
  106945. if (values) {
  106946. for (var index = 0; index < values.length; index++) {
  106947. values[index]._index = index;
  106948. }
  106949. }
  106950. };
  106951. return ArrayItem;
  106952. }());
  106953. GLTF2.ArrayItem = ArrayItem;
  106954. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  106955. })(BABYLON || (BABYLON = {}));
  106956. //# sourceMappingURL=babylon.glTFLoaderUtilities.js.map
  106957. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  106958. var BABYLON;
  106959. (function (BABYLON) {
  106960. var GLTF2;
  106961. (function (GLTF2) {
  106962. var GLTFLoader = /** @class */ (function () {
  106963. function GLTFLoader() {
  106964. this._completePromises = new Array();
  106965. this._disposed = false;
  106966. this._state = null;
  106967. this._extensions = {};
  106968. this._defaultSampler = {};
  106969. this._requests = new Array();
  106970. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  106971. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  106972. this.compileMaterials = false;
  106973. this.useClipPlane = false;
  106974. this.compileShadowGenerators = false;
  106975. this.onDisposeObservable = new BABYLON.Observable();
  106976. this.onMeshLoadedObservable = new BABYLON.Observable();
  106977. this.onTextureLoadedObservable = new BABYLON.Observable();
  106978. this.onMaterialLoadedObservable = new BABYLON.Observable();
  106979. this.onExtensionLoadedObservable = new BABYLON.Observable();
  106980. this.onCompleteObservable = new BABYLON.Observable();
  106981. }
  106982. GLTFLoader._Register = function (name, factory) {
  106983. if (GLTFLoader._Factories[name]) {
  106984. BABYLON.Tools.Error("Extension with the name '" + name + "' already exists");
  106985. return;
  106986. }
  106987. GLTFLoader._Factories[name] = factory;
  106988. // Keep the order of registration so that extensions registered first are called first.
  106989. GLTFLoader._Names.push(name);
  106990. };
  106991. Object.defineProperty(GLTFLoader.prototype, "state", {
  106992. get: function () {
  106993. return this._state;
  106994. },
  106995. enumerable: true,
  106996. configurable: true
  106997. });
  106998. GLTFLoader.prototype.dispose = function () {
  106999. if (this._disposed) {
  107000. return;
  107001. }
  107002. this._disposed = true;
  107003. this.onDisposeObservable.notifyObservers(this);
  107004. this.onDisposeObservable.clear();
  107005. this._clear();
  107006. };
  107007. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  107008. var _this = this;
  107009. return Promise.resolve().then(function () {
  107010. var nodes = null;
  107011. if (meshesNames) {
  107012. var nodeMap_1 = {};
  107013. if (_this._gltf.nodes) {
  107014. for (var _i = 0, _a = _this._gltf.nodes; _i < _a.length; _i++) {
  107015. var node = _a[_i];
  107016. if (node.name) {
  107017. nodeMap_1[node.name] = node;
  107018. }
  107019. }
  107020. }
  107021. var names = (meshesNames instanceof Array) ? meshesNames : [meshesNames];
  107022. nodes = names.map(function (name) {
  107023. var node = nodeMap_1[name];
  107024. if (!node) {
  107025. throw new Error("Failed to find node " + name);
  107026. }
  107027. return node;
  107028. });
  107029. }
  107030. return _this._loadAsync(nodes, scene, data, rootUrl, onProgress).then(function () {
  107031. return {
  107032. meshes: _this._getMeshes(),
  107033. particleSystems: [],
  107034. skeletons: _this._getSkeletons(),
  107035. };
  107036. });
  107037. });
  107038. };
  107039. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  107040. return this._loadAsync(null, scene, data, rootUrl, onProgress);
  107041. };
  107042. GLTFLoader.prototype._loadAsync = function (nodes, scene, data, rootUrl, onProgress) {
  107043. var _this = this;
  107044. return Promise.resolve().then(function () {
  107045. _this._loadExtensions();
  107046. _this._babylonScene = scene;
  107047. _this._rootUrl = rootUrl;
  107048. _this._progressCallback = onProgress;
  107049. _this._state = BABYLON.GLTFLoaderState.Loading;
  107050. _this._loadData(data);
  107051. _this._checkExtensions();
  107052. var promises = new Array();
  107053. if (nodes) {
  107054. promises.push(_this._loadNodesAsync(nodes));
  107055. }
  107056. else {
  107057. var scene_1 = GLTFLoader._GetProperty("#/scene", _this._gltf.scenes, _this._gltf.scene || 0);
  107058. promises.push(_this._loadSceneAsync("#/scenes/" + scene_1._index, scene_1));
  107059. }
  107060. if (_this.compileMaterials) {
  107061. promises.push(_this._compileMaterialsAsync());
  107062. }
  107063. if (_this.compileShadowGenerators) {
  107064. promises.push(_this._compileShadowGeneratorsAsync());
  107065. }
  107066. return Promise.all(promises).then(function () {
  107067. _this._state = BABYLON.GLTFLoaderState.Ready;
  107068. _this._startAnimations();
  107069. BABYLON.Tools.SetImmediate(function () {
  107070. if (!_this._disposed) {
  107071. Promise.all(_this._completePromises).then(function () {
  107072. _this._state = BABYLON.GLTFLoaderState.Complete;
  107073. _this.onCompleteObservable.notifyObservers(_this);
  107074. _this.onCompleteObservable.clear();
  107075. _this._clear();
  107076. }).catch(function (error) {
  107077. BABYLON.Tools.Error("glTF Loader: " + error.message);
  107078. _this._clear();
  107079. });
  107080. }
  107081. });
  107082. });
  107083. }).catch(function (error) {
  107084. BABYLON.Tools.Error("glTF Loader: " + error.message);
  107085. _this._clear();
  107086. throw error;
  107087. });
  107088. };
  107089. GLTFLoader.prototype._loadExtensions = function () {
  107090. for (var _i = 0, _a = GLTFLoader._Names; _i < _a.length; _i++) {
  107091. var name_1 = _a[_i];
  107092. var extension = GLTFLoader._Factories[name_1](this);
  107093. this._extensions[name_1] = extension;
  107094. this.onExtensionLoadedObservable.notifyObservers(extension);
  107095. }
  107096. this.onExtensionLoadedObservable.clear();
  107097. };
  107098. GLTFLoader.prototype._loadData = function (data) {
  107099. this._gltf = data.json;
  107100. this._setupData();
  107101. if (data.bin) {
  107102. var buffers = this._gltf.buffers;
  107103. if (buffers && buffers[0] && !buffers[0].uri) {
  107104. var binaryBuffer = buffers[0];
  107105. if (binaryBuffer.byteLength < data.bin.byteLength - 3 || binaryBuffer.byteLength > data.bin.byteLength) {
  107106. BABYLON.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  107107. }
  107108. binaryBuffer._data = Promise.resolve(data.bin);
  107109. }
  107110. else {
  107111. BABYLON.Tools.Warn("Unexpected BIN chunk");
  107112. }
  107113. }
  107114. };
  107115. GLTFLoader.prototype._setupData = function () {
  107116. GLTF2.ArrayItem.Assign(this._gltf.accessors);
  107117. GLTF2.ArrayItem.Assign(this._gltf.animations);
  107118. GLTF2.ArrayItem.Assign(this._gltf.buffers);
  107119. GLTF2.ArrayItem.Assign(this._gltf.bufferViews);
  107120. GLTF2.ArrayItem.Assign(this._gltf.cameras);
  107121. GLTF2.ArrayItem.Assign(this._gltf.images);
  107122. GLTF2.ArrayItem.Assign(this._gltf.materials);
  107123. GLTF2.ArrayItem.Assign(this._gltf.meshes);
  107124. GLTF2.ArrayItem.Assign(this._gltf.nodes);
  107125. GLTF2.ArrayItem.Assign(this._gltf.samplers);
  107126. GLTF2.ArrayItem.Assign(this._gltf.scenes);
  107127. GLTF2.ArrayItem.Assign(this._gltf.skins);
  107128. GLTF2.ArrayItem.Assign(this._gltf.textures);
  107129. if (this._gltf.nodes) {
  107130. var nodeParents = {};
  107131. for (var _i = 0, _a = this._gltf.nodes; _i < _a.length; _i++) {
  107132. var node = _a[_i];
  107133. if (node.children) {
  107134. for (var _b = 0, _c = node.children; _b < _c.length; _b++) {
  107135. var index = _c[_b];
  107136. nodeParents[index] = node._index;
  107137. }
  107138. }
  107139. }
  107140. var rootNode = this._createRootNode();
  107141. for (var _d = 0, _e = this._gltf.nodes; _d < _e.length; _d++) {
  107142. var node = _e[_d];
  107143. var parentIndex = nodeParents[node._index];
  107144. node._parent = parentIndex === undefined ? rootNode : this._gltf.nodes[parentIndex];
  107145. }
  107146. }
  107147. };
  107148. GLTFLoader.prototype._checkExtensions = function () {
  107149. if (this._gltf.extensionsRequired) {
  107150. for (var _i = 0, _a = this._gltf.extensionsRequired; _i < _a.length; _i++) {
  107151. var name_2 = _a[_i];
  107152. var extension = this._extensions[name_2];
  107153. if (!extension || !extension.enabled) {
  107154. throw new Error("Require extension " + name_2 + " is not available");
  107155. }
  107156. }
  107157. }
  107158. };
  107159. GLTFLoader.prototype._createRootNode = function () {
  107160. this._rootBabylonMesh = new BABYLON.Mesh("__root__", this._babylonScene);
  107161. var rootNode = { _babylonMesh: this._rootBabylonMesh };
  107162. switch (this.coordinateSystemMode) {
  107163. case BABYLON.GLTFLoaderCoordinateSystemMode.AUTO: {
  107164. if (!this._babylonScene.useRightHandedSystem) {
  107165. rootNode.rotation = [0, 1, 0, 0];
  107166. rootNode.scale = [1, 1, -1];
  107167. GLTFLoader._LoadTransform(rootNode, this._rootBabylonMesh);
  107168. }
  107169. break;
  107170. }
  107171. case BABYLON.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED: {
  107172. this._babylonScene.useRightHandedSystem = true;
  107173. break;
  107174. }
  107175. default: {
  107176. throw new Error("Invalid coordinate system mode " + this.coordinateSystemMode);
  107177. }
  107178. }
  107179. this.onMeshLoadedObservable.notifyObservers(this._rootBabylonMesh);
  107180. return rootNode;
  107181. };
  107182. GLTFLoader.prototype._loadNodesAsync = function (nodes) {
  107183. var promises = new Array();
  107184. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  107185. var node = nodes_1[_i];
  107186. promises.push(this._loadNodeAsync("#/nodes/" + node._index, node));
  107187. }
  107188. promises.push(this._loadAnimationsAsync());
  107189. return Promise.all(promises).then(function () { });
  107190. };
  107191. GLTFLoader.prototype._loadSceneAsync = function (context, scene) {
  107192. var promise = GLTF2.GLTFLoaderExtension._LoadSceneAsync(this, context, scene);
  107193. if (promise) {
  107194. return promise;
  107195. }
  107196. var promises = new Array();
  107197. for (var _i = 0, _a = scene.nodes; _i < _a.length; _i++) {
  107198. var index = _a[_i];
  107199. var node = GLTFLoader._GetProperty(context + "/nodes/" + index, this._gltf.nodes, index);
  107200. promises.push(this._loadNodeAsync("#/nodes/" + node._index, node));
  107201. }
  107202. promises.push(this._loadAnimationsAsync());
  107203. return Promise.all(promises).then(function () { });
  107204. };
  107205. GLTFLoader.prototype._getMeshes = function () {
  107206. var meshes = new Array();
  107207. // Root mesh is always first.
  107208. meshes.push(this._rootBabylonMesh);
  107209. var nodes = this._gltf.nodes;
  107210. if (nodes) {
  107211. for (var _i = 0, nodes_2 = nodes; _i < nodes_2.length; _i++) {
  107212. var node = nodes_2[_i];
  107213. if (node._babylonMesh) {
  107214. meshes.push(node._babylonMesh);
  107215. }
  107216. if (node._primitiveBabylonMeshes) {
  107217. for (var _a = 0, _b = node._primitiveBabylonMeshes; _a < _b.length; _a++) {
  107218. var babylonMesh = _b[_a];
  107219. meshes.push(babylonMesh);
  107220. }
  107221. }
  107222. }
  107223. }
  107224. return meshes;
  107225. };
  107226. GLTFLoader.prototype._getSkeletons = function () {
  107227. var skeletons = new Array();
  107228. var skins = this._gltf.skins;
  107229. if (skins) {
  107230. for (var _i = 0, skins_1 = skins; _i < skins_1.length; _i++) {
  107231. var skin = skins_1[_i];
  107232. if (skin._babylonSkeleton) {
  107233. skeletons.push(skin._babylonSkeleton);
  107234. }
  107235. }
  107236. }
  107237. return skeletons;
  107238. };
  107239. GLTFLoader.prototype._startAnimations = function () {
  107240. var animations = this._gltf.animations;
  107241. if (!animations) {
  107242. return;
  107243. }
  107244. switch (this.animationStartMode) {
  107245. case BABYLON.GLTFLoaderAnimationStartMode.NONE: {
  107246. // do nothing
  107247. break;
  107248. }
  107249. case BABYLON.GLTFLoaderAnimationStartMode.FIRST: {
  107250. var animation = animations[0];
  107251. animation._babylonAnimationGroup.start(true);
  107252. break;
  107253. }
  107254. case BABYLON.GLTFLoaderAnimationStartMode.ALL: {
  107255. for (var _i = 0, animations_1 = animations; _i < animations_1.length; _i++) {
  107256. var animation = animations_1[_i];
  107257. animation._babylonAnimationGroup.start(true);
  107258. }
  107259. break;
  107260. }
  107261. default: {
  107262. BABYLON.Tools.Error("Invalid animation start mode " + this.animationStartMode);
  107263. return;
  107264. }
  107265. }
  107266. };
  107267. GLTFLoader.prototype._loadNodeAsync = function (context, node) {
  107268. var promise = GLTF2.GLTFLoaderExtension._LoadNodeAsync(this, context, node);
  107269. if (promise) {
  107270. return promise;
  107271. }
  107272. if (node._babylonMesh) {
  107273. throw new Error(context + ": Invalid recursive node hierarchy");
  107274. }
  107275. var promises = new Array();
  107276. var babylonMesh = new BABYLON.Mesh(node.name || "node" + node._index, this._babylonScene, node._parent._babylonMesh);
  107277. node._babylonMesh = babylonMesh;
  107278. node._babylonAnimationTargets = node._babylonAnimationTargets || [];
  107279. node._babylonAnimationTargets.push(babylonMesh);
  107280. GLTFLoader._LoadTransform(node, babylonMesh);
  107281. if (node.mesh != undefined) {
  107282. var mesh = GLTFLoader._GetProperty(context + "/mesh", this._gltf.meshes, node.mesh);
  107283. promises.push(this._loadMeshAsync("#/meshes/" + mesh._index, node, mesh));
  107284. }
  107285. if (node.children) {
  107286. for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
  107287. var index = _a[_i];
  107288. var childNode = GLTFLoader._GetProperty(context + "/children/" + index, this._gltf.nodes, index);
  107289. promises.push(this._loadNodeAsync("#/nodes/" + index, childNode));
  107290. }
  107291. }
  107292. this.onMeshLoadedObservable.notifyObservers(babylonMesh);
  107293. return Promise.all(promises).then(function () { });
  107294. };
  107295. GLTFLoader.prototype._loadMeshAsync = function (context, node, mesh) {
  107296. // TODO: instancing
  107297. var promises = new Array();
  107298. var primitives = mesh.primitives;
  107299. if (!primitives || primitives.length === 0) {
  107300. throw new Error(context + ": Primitives are missing");
  107301. }
  107302. GLTF2.ArrayItem.Assign(primitives);
  107303. for (var _i = 0, primitives_1 = primitives; _i < primitives_1.length; _i++) {
  107304. var primitive = primitives_1[_i];
  107305. promises.push(this._loadPrimitiveAsync(context + "/primitives/" + primitive._index, node, mesh, primitive));
  107306. }
  107307. if (node.skin != undefined) {
  107308. var skin = GLTFLoader._GetProperty(context + "/skin", this._gltf.skins, node.skin);
  107309. promises.push(this._loadSkinAsync("#/skins/" + skin._index, node, mesh, skin));
  107310. }
  107311. return Promise.all(promises).then(function () {
  107312. if (node._primitiveBabylonMeshes) {
  107313. for (var _i = 0, _a = node._primitiveBabylonMeshes; _i < _a.length; _i++) {
  107314. var primitiveBabylonMesh = _a[_i];
  107315. primitiveBabylonMesh._refreshBoundingInfo(true);
  107316. }
  107317. }
  107318. });
  107319. };
  107320. GLTFLoader.prototype._loadPrimitiveAsync = function (context, node, mesh, primitive) {
  107321. var _this = this;
  107322. var promises = new Array();
  107323. var babylonMesh = new BABYLON.Mesh((mesh.name || node._babylonMesh.name) + "_" + primitive._index, this._babylonScene, node._babylonMesh);
  107324. babylonMesh.setEnabled(false);
  107325. node._primitiveBabylonMeshes = node._primitiveBabylonMeshes || [];
  107326. node._primitiveBabylonMeshes[primitive._index] = babylonMesh;
  107327. this._createMorphTargets(context, node, mesh, primitive, babylonMesh);
  107328. promises.push(this._loadVertexDataAsync(context, primitive, babylonMesh).then(function (babylonVertexData) {
  107329. new BABYLON.Geometry(babylonMesh.name, _this._babylonScene, babylonVertexData, false, babylonMesh);
  107330. return _this._loadMorphTargetsAsync(context, primitive, babylonMesh, babylonVertexData);
  107331. }));
  107332. if (primitive.material == undefined) {
  107333. babylonMesh.material = this._getDefaultMaterial();
  107334. }
  107335. else {
  107336. var material = GLTFLoader._GetProperty(context + "/material", this._gltf.materials, primitive.material);
  107337. promises.push(this._loadMaterialAsync("#/materials/" + material._index, material, babylonMesh));
  107338. }
  107339. this.onMeshLoadedObservable.notifyObservers(babylonMesh);
  107340. return Promise.all(promises).then(function () {
  107341. babylonMesh.setEnabled(true);
  107342. });
  107343. };
  107344. GLTFLoader.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  107345. var _this = this;
  107346. var promise = GLTF2.GLTFLoaderExtension._LoadVertexDataAsync(this, context, primitive, babylonMesh);
  107347. if (promise) {
  107348. return promise;
  107349. }
  107350. var attributes = primitive.attributes;
  107351. if (!attributes) {
  107352. throw new Error(context + ": Attributes are missing");
  107353. }
  107354. if (primitive.mode != undefined && primitive.mode !== 4 /* TRIANGLES */) {
  107355. // TODO: handle other primitive modes
  107356. throw new Error(context + ": Mode " + primitive.mode + " is not currently supported");
  107357. }
  107358. var promises = new Array();
  107359. var babylonVertexData = new BABYLON.VertexData();
  107360. if (primitive.indices == undefined) {
  107361. var positionAccessorIndex = attributes["POSITION"];
  107362. if (positionAccessorIndex != undefined) {
  107363. var accessor = GLTFLoader._GetProperty(context + "/attributes/POSITION", this._gltf.accessors, positionAccessorIndex);
  107364. babylonVertexData.indices = new Uint32Array(accessor.count);
  107365. for (var i = 0; i < babylonVertexData.indices.length; i++) {
  107366. babylonVertexData.indices[i] = i;
  107367. }
  107368. }
  107369. }
  107370. else {
  107371. var indicesAccessor = GLTFLoader._GetProperty(context + "/indices", this._gltf.accessors, primitive.indices);
  107372. promises.push(this._loadAccessorAsync("#/accessors/" + indicesAccessor._index, indicesAccessor).then(function (data) {
  107373. babylonVertexData.indices = data;
  107374. }));
  107375. }
  107376. var loadAttribute = function (attribute, kind) {
  107377. if (attributes[attribute] == undefined) {
  107378. return;
  107379. }
  107380. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  107381. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  107382. babylonMesh._delayInfo.push(kind);
  107383. }
  107384. var accessor = GLTFLoader._GetProperty(context + "/attributes/" + attribute, _this._gltf.accessors, attributes[attribute]);
  107385. promises.push(_this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  107386. var attributeData = GLTFLoader._ConvertToFloat32Array(context, accessor, data);
  107387. if (attribute === "COLOR_0") {
  107388. // Assume vertex color has alpha on the mesh. The alphaMode of the material controls whether the material should use alpha or not.
  107389. babylonMesh.hasVertexAlpha = true;
  107390. if (accessor.type === "VEC3") {
  107391. attributeData = GLTFLoader._ConvertVec3ToVec4(context, attributeData);
  107392. }
  107393. }
  107394. babylonVertexData.set(attributeData, kind);
  107395. }));
  107396. };
  107397. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind);
  107398. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind);
  107399. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind);
  107400. loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind);
  107401. loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind);
  107402. loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind);
  107403. loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind);
  107404. loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind);
  107405. return Promise.all(promises).then(function () {
  107406. return babylonVertexData;
  107407. });
  107408. };
  107409. GLTFLoader.prototype._createMorphTargets = function (context, node, mesh, primitive, babylonMesh) {
  107410. if (!primitive.targets) {
  107411. return;
  107412. }
  107413. if (node._numMorphTargets == undefined) {
  107414. node._numMorphTargets = primitive.targets.length;
  107415. }
  107416. else if (primitive.targets.length !== node._numMorphTargets) {
  107417. throw new Error(context + ": Primitives do not have the same number of targets");
  107418. }
  107419. babylonMesh.morphTargetManager = new BABYLON.MorphTargetManager();
  107420. for (var index = 0; index < primitive.targets.length; index++) {
  107421. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  107422. babylonMesh.morphTargetManager.addTarget(new BABYLON.MorphTarget("morphTarget" + index, weight));
  107423. // TODO: tell the target whether it has positions, normals, tangents
  107424. }
  107425. };
  107426. GLTFLoader.prototype._loadMorphTargetsAsync = function (context, primitive, babylonMesh, babylonVertexData) {
  107427. if (!primitive.targets) {
  107428. return Promise.resolve();
  107429. }
  107430. var promises = new Array();
  107431. var morphTargetManager = babylonMesh.morphTargetManager;
  107432. for (var index = 0; index < morphTargetManager.numTargets; index++) {
  107433. var babylonMorphTarget = morphTargetManager.getTarget(index);
  107434. promises.push(this._loadMorphTargetVertexDataAsync(context + "/targets/" + index, babylonVertexData, primitive.targets[index], babylonMorphTarget));
  107435. }
  107436. return Promise.all(promises).then(function () { });
  107437. };
  107438. GLTFLoader.prototype._loadMorphTargetVertexDataAsync = function (context, babylonVertexData, attributes, babylonMorphTarget) {
  107439. var _this = this;
  107440. var promises = new Array();
  107441. var loadAttribute = function (attribute, setData) {
  107442. if (attributes[attribute] == undefined) {
  107443. return;
  107444. }
  107445. var accessor = GLTFLoader._GetProperty(context + "/" + attribute, _this._gltf.accessors, attributes[attribute]);
  107446. promises.push(_this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  107447. setData(data);
  107448. }));
  107449. };
  107450. loadAttribute("POSITION", function (data) {
  107451. if (babylonVertexData.positions) {
  107452. for (var i = 0; i < data.length; i++) {
  107453. data[i] += babylonVertexData.positions[i];
  107454. }
  107455. babylonMorphTarget.setPositions(data);
  107456. }
  107457. });
  107458. loadAttribute("NORMAL", function (data) {
  107459. if (babylonVertexData.normals) {
  107460. for (var i = 0; i < data.length; i++) {
  107461. data[i] += babylonVertexData.normals[i];
  107462. }
  107463. babylonMorphTarget.setNormals(data);
  107464. }
  107465. });
  107466. loadAttribute("TANGENT", function (data) {
  107467. if (babylonVertexData.tangents) {
  107468. // Tangent data for morph targets is stored as xyz delta.
  107469. // The vertexData.tangent is stored as xyzw.
  107470. // So we need to skip every fourth vertexData.tangent.
  107471. for (var i = 0, j = 0; i < data.length; i++) {
  107472. data[i] += babylonVertexData.tangents[j++];
  107473. if ((i + 1) % 3 == 0) {
  107474. j++;
  107475. }
  107476. }
  107477. babylonMorphTarget.setTangents(data);
  107478. }
  107479. });
  107480. return Promise.all(promises).then(function () { });
  107481. };
  107482. GLTFLoader._ConvertToFloat32Array = function (context, accessor, data) {
  107483. if (accessor.componentType == 5126 /* FLOAT */) {
  107484. return data;
  107485. }
  107486. var factor = 1;
  107487. if (accessor.normalized) {
  107488. switch (accessor.componentType) {
  107489. case 5121 /* UNSIGNED_BYTE */: {
  107490. factor = 1 / 255;
  107491. break;
  107492. }
  107493. case 5123 /* UNSIGNED_SHORT */: {
  107494. factor = 1 / 65535;
  107495. break;
  107496. }
  107497. default: {
  107498. throw new Error(context + ": Invalid component type " + accessor.componentType);
  107499. }
  107500. }
  107501. }
  107502. var result = new Float32Array(accessor.count * GLTFLoader._GetNumComponents(context, accessor.type));
  107503. for (var i = 0; i < result.length; i++) {
  107504. result[i] = data[i] * factor;
  107505. }
  107506. return result;
  107507. };
  107508. GLTFLoader._ConvertVec3ToVec4 = function (context, data) {
  107509. var result = new Float32Array(data.length / 3 * 4);
  107510. var offset = 0;
  107511. for (var i = 0; i < result.length; i++) {
  107512. if ((i + 1) % 4 === 0) {
  107513. result[i] = 1;
  107514. }
  107515. else {
  107516. result[i] = data[offset++];
  107517. }
  107518. }
  107519. return result;
  107520. };
  107521. GLTFLoader._LoadTransform = function (node, babylonNode) {
  107522. var position = BABYLON.Vector3.Zero();
  107523. var rotation = BABYLON.Quaternion.Identity();
  107524. var scaling = BABYLON.Vector3.One();
  107525. if (node.matrix) {
  107526. var matrix = BABYLON.Matrix.FromArray(node.matrix);
  107527. matrix.decompose(scaling, rotation, position);
  107528. }
  107529. else {
  107530. if (node.translation)
  107531. position = BABYLON.Vector3.FromArray(node.translation);
  107532. if (node.rotation)
  107533. rotation = BABYLON.Quaternion.FromArray(node.rotation);
  107534. if (node.scale)
  107535. scaling = BABYLON.Vector3.FromArray(node.scale);
  107536. }
  107537. babylonNode.position = position;
  107538. babylonNode.rotationQuaternion = rotation;
  107539. babylonNode.scaling = scaling;
  107540. };
  107541. GLTFLoader.prototype._loadSkinAsync = function (context, node, mesh, skin) {
  107542. var _this = this;
  107543. var assignSkeleton = function () {
  107544. for (var _i = 0, _a = node._primitiveBabylonMeshes; _i < _a.length; _i++) {
  107545. var babylonMesh = _a[_i];
  107546. babylonMesh.skeleton = skin._babylonSkeleton;
  107547. }
  107548. node._babylonMesh.parent = _this._rootBabylonMesh;
  107549. node._babylonMesh.position = BABYLON.Vector3.Zero();
  107550. node._babylonMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  107551. node._babylonMesh.scaling = BABYLON.Vector3.One();
  107552. };
  107553. if (skin._loaded) {
  107554. assignSkeleton();
  107555. return skin._loaded;
  107556. }
  107557. // TODO: split into two parts so that bones are created before inverseBindMatricesData is loaded (for compiling materials).
  107558. return (skin._loaded = this._loadSkinInverseBindMatricesDataAsync(context, skin).then(function (inverseBindMatricesData) {
  107559. var skeletonId = "skeleton" + skin._index;
  107560. var babylonSkeleton = new BABYLON.Skeleton(skin.name || skeletonId, skeletonId, _this._babylonScene);
  107561. skin._babylonSkeleton = babylonSkeleton;
  107562. _this._loadBones(context, skin, inverseBindMatricesData);
  107563. assignSkeleton();
  107564. }));
  107565. };
  107566. GLTFLoader.prototype._loadSkinInverseBindMatricesDataAsync = function (context, skin) {
  107567. if (skin.inverseBindMatrices == undefined) {
  107568. return Promise.resolve(null);
  107569. }
  107570. var accessor = GLTFLoader._GetProperty(context + "/inverseBindMatrices", this._gltf.accessors, skin.inverseBindMatrices);
  107571. return this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  107572. return data;
  107573. });
  107574. };
  107575. GLTFLoader.prototype._createBone = function (node, skin, parent, localMatrix, baseMatrix, index) {
  107576. var babylonBone = new BABYLON.Bone(node.name || "joint" + node._index, skin._babylonSkeleton, parent, localMatrix, null, baseMatrix, index);
  107577. node._babylonAnimationTargets = node._babylonAnimationTargets || [];
  107578. node._babylonAnimationTargets.push(babylonBone);
  107579. return babylonBone;
  107580. };
  107581. GLTFLoader.prototype._loadBones = function (context, skin, inverseBindMatricesData) {
  107582. var babylonBones = {};
  107583. for (var _i = 0, _a = skin.joints; _i < _a.length; _i++) {
  107584. var index = _a[_i];
  107585. var node = GLTFLoader._GetProperty(context + "/joints/" + index, this._gltf.nodes, index);
  107586. this._loadBone(node, skin, inverseBindMatricesData, babylonBones);
  107587. }
  107588. };
  107589. GLTFLoader.prototype._loadBone = function (node, skin, inverseBindMatricesData, babylonBones) {
  107590. var babylonBone = babylonBones[node._index];
  107591. if (babylonBone) {
  107592. return babylonBone;
  107593. }
  107594. var boneIndex = skin.joints.indexOf(node._index);
  107595. var baseMatrix = BABYLON.Matrix.Identity();
  107596. if (inverseBindMatricesData && boneIndex !== -1) {
  107597. baseMatrix = BABYLON.Matrix.FromArray(inverseBindMatricesData, boneIndex * 16);
  107598. baseMatrix.invertToRef(baseMatrix);
  107599. }
  107600. var babylonParentBone = null;
  107601. if (node._parent._babylonMesh !== this._rootBabylonMesh) {
  107602. babylonParentBone = this._loadBone(node._parent, skin, inverseBindMatricesData, babylonBones);
  107603. baseMatrix.multiplyToRef(babylonParentBone.getInvertedAbsoluteTransform(), baseMatrix);
  107604. }
  107605. babylonBone = this._createBone(node, skin, babylonParentBone, this._getNodeMatrix(node), baseMatrix, boneIndex);
  107606. babylonBones[node._index] = babylonBone;
  107607. return babylonBone;
  107608. };
  107609. GLTFLoader.prototype._getNodeMatrix = function (node) {
  107610. return node.matrix ?
  107611. BABYLON.Matrix.FromArray(node.matrix) :
  107612. BABYLON.Matrix.Compose(node.scale ? BABYLON.Vector3.FromArray(node.scale) : BABYLON.Vector3.One(), node.rotation ? BABYLON.Quaternion.FromArray(node.rotation) : BABYLON.Quaternion.Identity(), node.translation ? BABYLON.Vector3.FromArray(node.translation) : BABYLON.Vector3.Zero());
  107613. };
  107614. GLTFLoader.prototype._loadAnimationsAsync = function () {
  107615. var animations = this._gltf.animations;
  107616. if (!animations) {
  107617. return Promise.resolve();
  107618. }
  107619. var promises = new Array();
  107620. for (var index = 0; index < animations.length; index++) {
  107621. var animation = animations[index];
  107622. promises.push(this._loadAnimationAsync("#/animations/" + index, animation));
  107623. }
  107624. return Promise.all(promises).then(function () { });
  107625. };
  107626. GLTFLoader.prototype._loadAnimationAsync = function (context, animation) {
  107627. var babylonAnimationGroup = new BABYLON.AnimationGroup(animation.name || "animation" + animation._index, this._babylonScene);
  107628. animation._babylonAnimationGroup = babylonAnimationGroup;
  107629. var promises = new Array();
  107630. GLTF2.ArrayItem.Assign(animation.channels);
  107631. GLTF2.ArrayItem.Assign(animation.samplers);
  107632. for (var _i = 0, _a = animation.channels; _i < _a.length; _i++) {
  107633. var channel = _a[_i];
  107634. promises.push(this._loadAnimationChannelAsync(context + "/channels/" + channel._index, context, animation, channel, babylonAnimationGroup));
  107635. }
  107636. return Promise.all(promises).then(function () {
  107637. babylonAnimationGroup.normalize();
  107638. });
  107639. };
  107640. GLTFLoader.prototype._loadAnimationChannelAsync = function (context, animationContext, animation, channel, babylonAnimationGroup) {
  107641. var targetNode = GLTFLoader._GetProperty(context + "/target/node", this._gltf.nodes, channel.target.node);
  107642. if (!targetNode._babylonMesh) {
  107643. return Promise.resolve();
  107644. }
  107645. var sampler = GLTFLoader._GetProperty(context + "/sampler", animation.samplers, channel.sampler);
  107646. return this._loadAnimationSamplerAsync(animationContext + "/samplers/" + channel.sampler, sampler).then(function (data) {
  107647. var targetPath;
  107648. var animationType;
  107649. switch (channel.target.path) {
  107650. case "translation" /* TRANSLATION */: {
  107651. targetPath = "position";
  107652. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  107653. break;
  107654. }
  107655. case "rotation" /* ROTATION */: {
  107656. targetPath = "rotationQuaternion";
  107657. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  107658. break;
  107659. }
  107660. case "scale" /* SCALE */: {
  107661. targetPath = "scaling";
  107662. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  107663. break;
  107664. }
  107665. case "weights" /* WEIGHTS */: {
  107666. targetPath = "influence";
  107667. animationType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  107668. break;
  107669. }
  107670. default: {
  107671. throw new Error(context + ": Invalid target path " + channel.target.path);
  107672. }
  107673. }
  107674. var outputBufferOffset = 0;
  107675. var getNextOutputValue;
  107676. switch (targetPath) {
  107677. case "position": {
  107678. getNextOutputValue = function () {
  107679. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  107680. outputBufferOffset += 3;
  107681. return value;
  107682. };
  107683. break;
  107684. }
  107685. case "rotationQuaternion": {
  107686. getNextOutputValue = function () {
  107687. var value = BABYLON.Quaternion.FromArray(data.output, outputBufferOffset);
  107688. outputBufferOffset += 4;
  107689. return value;
  107690. };
  107691. break;
  107692. }
  107693. case "scaling": {
  107694. getNextOutputValue = function () {
  107695. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  107696. outputBufferOffset += 3;
  107697. return value;
  107698. };
  107699. break;
  107700. }
  107701. case "influence": {
  107702. getNextOutputValue = function () {
  107703. var value = new Array(targetNode._numMorphTargets);
  107704. for (var i = 0; i < targetNode._numMorphTargets; i++) {
  107705. value[i] = data.output[outputBufferOffset++];
  107706. }
  107707. return value;
  107708. };
  107709. break;
  107710. }
  107711. }
  107712. var getNextKey;
  107713. switch (data.interpolation) {
  107714. case "STEP" /* STEP */: {
  107715. getNextKey = function (frameIndex) { return ({
  107716. frame: data.input[frameIndex],
  107717. value: getNextOutputValue(),
  107718. interpolation: BABYLON.AnimationKeyInterpolation.STEP
  107719. }); };
  107720. break;
  107721. }
  107722. case "LINEAR" /* LINEAR */: {
  107723. getNextKey = function (frameIndex) { return ({
  107724. frame: data.input[frameIndex],
  107725. value: getNextOutputValue()
  107726. }); };
  107727. break;
  107728. }
  107729. case "CUBICSPLINE" /* CUBICSPLINE */: {
  107730. getNextKey = function (frameIndex) { return ({
  107731. frame: data.input[frameIndex],
  107732. inTangent: getNextOutputValue(),
  107733. value: getNextOutputValue(),
  107734. outTangent: getNextOutputValue()
  107735. }); };
  107736. break;
  107737. }
  107738. }
  107739. var keys;
  107740. if (data.input.length === 1) {
  107741. var key = getNextKey(0);
  107742. keys = [
  107743. { frame: key.frame, value: key.value },
  107744. { frame: key.frame + 1, value: key.value }
  107745. ];
  107746. }
  107747. else {
  107748. keys = new Array(data.input.length);
  107749. for (var frameIndex = 0; frameIndex < data.input.length; frameIndex++) {
  107750. keys[frameIndex] = getNextKey(frameIndex);
  107751. }
  107752. }
  107753. if (targetPath === "influence") {
  107754. var _loop_1 = function (targetIndex) {
  107755. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  107756. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  107757. babylonAnimation.setKeys(keys.map(function (key) { return ({
  107758. frame: key.frame,
  107759. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  107760. value: key.value[targetIndex],
  107761. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  107762. }); }));
  107763. for (var _i = 0, _a = targetNode._primitiveBabylonMeshes; _i < _a.length; _i++) {
  107764. var babylonMesh = _a[_i];
  107765. var morphTarget = babylonMesh.morphTargetManager.getTarget(targetIndex);
  107766. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, morphTarget);
  107767. }
  107768. };
  107769. for (var targetIndex = 0; targetIndex < targetNode._numMorphTargets; targetIndex++) {
  107770. _loop_1(targetIndex);
  107771. }
  107772. }
  107773. else {
  107774. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  107775. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  107776. babylonAnimation.setKeys(keys);
  107777. if (targetNode._babylonAnimationTargets) {
  107778. for (var _i = 0, _a = targetNode._babylonAnimationTargets; _i < _a.length; _i++) {
  107779. var target = _a[_i];
  107780. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, target);
  107781. }
  107782. }
  107783. }
  107784. });
  107785. };
  107786. GLTFLoader.prototype._loadAnimationSamplerAsync = function (context, sampler) {
  107787. if (sampler._data) {
  107788. return sampler._data;
  107789. }
  107790. var interpolation = sampler.interpolation || "LINEAR" /* LINEAR */;
  107791. switch (interpolation) {
  107792. case "STEP" /* STEP */:
  107793. case "LINEAR" /* LINEAR */:
  107794. case "CUBICSPLINE" /* CUBICSPLINE */: {
  107795. break;
  107796. }
  107797. default: {
  107798. throw new Error(context + ": Invalid interpolation " + sampler.interpolation);
  107799. }
  107800. }
  107801. var inputData;
  107802. var outputData;
  107803. var inputAccessor = GLTFLoader._GetProperty(context + "/input", this._gltf.accessors, sampler.input);
  107804. var outputAccessor = GLTFLoader._GetProperty(context + "/output", this._gltf.accessors, sampler.output);
  107805. sampler._data = Promise.all([
  107806. this._loadAccessorAsync("#/accessors/" + inputAccessor._index, inputAccessor).then(function (data) {
  107807. inputData = data;
  107808. }),
  107809. this._loadAccessorAsync("#/accessors/" + outputAccessor._index, outputAccessor).then(function (data) {
  107810. outputData = data;
  107811. })
  107812. ]).then(function () {
  107813. return {
  107814. input: inputData,
  107815. interpolation: interpolation,
  107816. output: outputData,
  107817. };
  107818. });
  107819. return sampler._data;
  107820. };
  107821. GLTFLoader.prototype._loadBufferAsync = function (context, buffer) {
  107822. if (buffer._data) {
  107823. return buffer._data;
  107824. }
  107825. if (!buffer.uri) {
  107826. throw new Error(context + ": Uri is missing");
  107827. }
  107828. buffer._data = this._loadUriAsync(context, buffer.uri);
  107829. return buffer._data;
  107830. };
  107831. GLTFLoader.prototype._loadBufferViewAsync = function (context, bufferView) {
  107832. if (bufferView._data) {
  107833. return bufferView._data;
  107834. }
  107835. var buffer = GLTFLoader._GetProperty(context + "/buffer", this._gltf.buffers, bufferView.buffer);
  107836. bufferView._data = this._loadBufferAsync("#/buffers/" + buffer._index, buffer).then(function (bufferData) {
  107837. try {
  107838. return new Uint8Array(bufferData.buffer, bufferData.byteOffset + (bufferView.byteOffset || 0), bufferView.byteLength);
  107839. }
  107840. catch (e) {
  107841. throw new Error(context + ": " + e.message);
  107842. }
  107843. });
  107844. return bufferView._data;
  107845. };
  107846. GLTFLoader.prototype._loadAccessorAsync = function (context, accessor) {
  107847. var _this = this;
  107848. if (accessor.sparse) {
  107849. throw new Error(context + ": Sparse accessors are not currently supported");
  107850. }
  107851. if (accessor._data) {
  107852. return accessor._data;
  107853. }
  107854. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, accessor.bufferView);
  107855. accessor._data = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (bufferViewData) {
  107856. var numComponents = GLTFLoader._GetNumComponents(context, accessor.type);
  107857. var byteOffset = accessor.byteOffset || 0;
  107858. var byteStride = bufferView.byteStride;
  107859. if (byteStride === 0) {
  107860. BABYLON.Tools.Warn(context + ": Byte stride of 0 is not valid");
  107861. }
  107862. try {
  107863. switch (accessor.componentType) {
  107864. case 5120 /* BYTE */: {
  107865. return _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  107866. }
  107867. case 5121 /* UNSIGNED_BYTE */: {
  107868. return _this._buildArrayBuffer(Uint8Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  107869. }
  107870. case 5122 /* SHORT */: {
  107871. return _this._buildArrayBuffer(Int16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  107872. }
  107873. case 5123 /* UNSIGNED_SHORT */: {
  107874. return _this._buildArrayBuffer(Uint16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  107875. }
  107876. case 5125 /* UNSIGNED_INT */: {
  107877. return _this._buildArrayBuffer(Uint32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  107878. }
  107879. case 5126 /* FLOAT */: {
  107880. return _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  107881. }
  107882. default: {
  107883. throw new Error(context + ": Invalid component type " + accessor.componentType);
  107884. }
  107885. }
  107886. }
  107887. catch (e) {
  107888. throw new Error(context + ": " + e);
  107889. }
  107890. });
  107891. return accessor._data;
  107892. };
  107893. GLTFLoader.prototype._buildArrayBuffer = function (typedArray, data, byteOffset, count, numComponents, byteStride) {
  107894. byteOffset += data.byteOffset;
  107895. var targetLength = count * numComponents;
  107896. if (!byteStride || byteStride === numComponents * typedArray.BYTES_PER_ELEMENT) {
  107897. return new typedArray(data.buffer, byteOffset, targetLength);
  107898. }
  107899. var elementStride = byteStride / typedArray.BYTES_PER_ELEMENT;
  107900. var sourceBuffer = new typedArray(data.buffer, byteOffset, elementStride * count);
  107901. var targetBuffer = new typedArray(targetLength);
  107902. var sourceIndex = 0;
  107903. var targetIndex = 0;
  107904. while (targetIndex < targetLength) {
  107905. for (var componentIndex = 0; componentIndex < numComponents; componentIndex++) {
  107906. targetBuffer[targetIndex] = sourceBuffer[sourceIndex + componentIndex];
  107907. targetIndex++;
  107908. }
  107909. sourceIndex += elementStride;
  107910. }
  107911. return targetBuffer;
  107912. };
  107913. GLTFLoader.prototype._getDefaultMaterial = function () {
  107914. var id = "__gltf_default";
  107915. var babylonMaterial = this._babylonScene.getMaterialByName(id);
  107916. if (!babylonMaterial) {
  107917. babylonMaterial = new BABYLON.PBRMaterial(id, this._babylonScene);
  107918. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  107919. babylonMaterial.sideOrientation = this._babylonScene.useRightHandedSystem ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation;
  107920. babylonMaterial.metallic = 1;
  107921. babylonMaterial.roughness = 1;
  107922. this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  107923. }
  107924. return babylonMaterial;
  107925. };
  107926. GLTFLoader.prototype._loadMaterialMetallicRoughnessPropertiesAsync = function (context, material) {
  107927. var promises = new Array();
  107928. var babylonMaterial = material._babylonMaterial;
  107929. // Ensure metallic workflow
  107930. babylonMaterial.metallic = 1;
  107931. babylonMaterial.roughness = 1;
  107932. var properties = material.pbrMetallicRoughness;
  107933. if (properties) {
  107934. if (properties.baseColorFactor) {
  107935. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.baseColorFactor);
  107936. babylonMaterial.alpha = properties.baseColorFactor[3];
  107937. }
  107938. else {
  107939. babylonMaterial.albedoColor = BABYLON.Color3.White();
  107940. }
  107941. babylonMaterial.metallic = properties.metallicFactor == undefined ? 1 : properties.metallicFactor;
  107942. babylonMaterial.roughness = properties.roughnessFactor == undefined ? 1 : properties.roughnessFactor;
  107943. if (properties.baseColorTexture) {
  107944. promises.push(this._loadTextureAsync(context + "/baseColorTexture", properties.baseColorTexture, function (texture) {
  107945. babylonMaterial.albedoTexture = texture;
  107946. }));
  107947. }
  107948. if (properties.metallicRoughnessTexture) {
  107949. promises.push(this._loadTextureAsync(context + "/metallicRoughnessTexture", properties.metallicRoughnessTexture, function (texture) {
  107950. babylonMaterial.metallicTexture = texture;
  107951. }));
  107952. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  107953. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  107954. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  107955. }
  107956. }
  107957. this._loadMaterialAlphaProperties(context, material);
  107958. return Promise.all(promises).then(function () { });
  107959. };
  107960. GLTFLoader.prototype._loadMaterialAsync = function (context, material, babylonMesh) {
  107961. var promise = GLTF2.GLTFLoaderExtension._LoadMaterialAsync(this, context, material, babylonMesh);
  107962. if (promise) {
  107963. return promise;
  107964. }
  107965. material._babylonMeshes = material._babylonMeshes || [];
  107966. material._babylonMeshes.push(babylonMesh);
  107967. if (material._loaded) {
  107968. babylonMesh.material = material._babylonMaterial;
  107969. return material._loaded;
  107970. }
  107971. var promises = new Array();
  107972. var babylonMaterial = this._createMaterial(material);
  107973. material._babylonMaterial = babylonMaterial;
  107974. promises.push(this._loadMaterialBasePropertiesAsync(context, material));
  107975. promises.push(this._loadMaterialMetallicRoughnessPropertiesAsync(context, material));
  107976. this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  107977. babylonMesh.material = babylonMaterial;
  107978. return (material._loaded = Promise.all(promises).then(function () { }));
  107979. };
  107980. GLTFLoader.prototype._createMaterial = function (material) {
  107981. var babylonMaterial = new BABYLON.PBRMaterial(material.name || "material" + material._index, this._babylonScene);
  107982. babylonMaterial.sideOrientation = this._babylonScene.useRightHandedSystem ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation;
  107983. return babylonMaterial;
  107984. };
  107985. GLTFLoader.prototype._loadMaterialBasePropertiesAsync = function (context, material) {
  107986. var promises = new Array();
  107987. var babylonMaterial = material._babylonMaterial;
  107988. babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
  107989. if (material.doubleSided) {
  107990. babylonMaterial.backFaceCulling = false;
  107991. babylonMaterial.twoSidedLighting = true;
  107992. }
  107993. if (material.normalTexture) {
  107994. promises.push(this._loadTextureAsync(context + "/normalTexture", material.normalTexture, function (texture) {
  107995. babylonMaterial.bumpTexture = texture;
  107996. }));
  107997. babylonMaterial.invertNormalMapX = !this._babylonScene.useRightHandedSystem;
  107998. babylonMaterial.invertNormalMapY = this._babylonScene.useRightHandedSystem;
  107999. if (material.normalTexture.scale != undefined) {
  108000. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  108001. }
  108002. }
  108003. if (material.occlusionTexture) {
  108004. promises.push(this._loadTextureAsync(context + "/occlusionTexture", material.occlusionTexture, function (texture) {
  108005. babylonMaterial.ambientTexture = texture;
  108006. }));
  108007. babylonMaterial.useAmbientInGrayScale = true;
  108008. if (material.occlusionTexture.strength != undefined) {
  108009. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  108010. }
  108011. }
  108012. if (material.emissiveTexture) {
  108013. promises.push(this._loadTextureAsync(context + "/emissiveTexture", material.emissiveTexture, function (texture) {
  108014. babylonMaterial.emissiveTexture = texture;
  108015. }));
  108016. }
  108017. return Promise.all(promises).then(function () { });
  108018. };
  108019. GLTFLoader.prototype._loadMaterialAlphaProperties = function (context, material) {
  108020. var babylonMaterial = material._babylonMaterial;
  108021. var alphaMode = material.alphaMode || "OPAQUE" /* OPAQUE */;
  108022. switch (alphaMode) {
  108023. case "OPAQUE" /* OPAQUE */: {
  108024. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  108025. break;
  108026. }
  108027. case "MASK" /* MASK */: {
  108028. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  108029. babylonMaterial.alphaCutOff = (material.alphaCutoff == undefined ? 0.5 : material.alphaCutoff);
  108030. if (babylonMaterial.alpha) {
  108031. if (babylonMaterial.alpha === 0) {
  108032. babylonMaterial.alphaCutOff = 1;
  108033. }
  108034. else {
  108035. babylonMaterial.alphaCutOff /= babylonMaterial.alpha;
  108036. }
  108037. babylonMaterial.alpha = 1;
  108038. }
  108039. if (babylonMaterial.albedoTexture) {
  108040. babylonMaterial.albedoTexture.hasAlpha = true;
  108041. }
  108042. break;
  108043. }
  108044. case "BLEND" /* BLEND */: {
  108045. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND;
  108046. if (babylonMaterial.albedoTexture) {
  108047. babylonMaterial.albedoTexture.hasAlpha = true;
  108048. babylonMaterial.useAlphaFromAlbedoTexture = true;
  108049. }
  108050. break;
  108051. }
  108052. default: {
  108053. throw new Error(context + ": Invalid alpha mode " + material.alphaMode);
  108054. }
  108055. }
  108056. };
  108057. GLTFLoader.prototype._loadTextureAsync = function (context, textureInfo, assign) {
  108058. var _this = this;
  108059. var texture = GLTFLoader._GetProperty(context + "/index", this._gltf.textures, textureInfo.index);
  108060. context = "#/textures/" + textureInfo.index;
  108061. var promises = new Array();
  108062. var sampler = (texture.sampler == undefined ? this._defaultSampler : GLTFLoader._GetProperty(context + "/sampler", this._gltf.samplers, texture.sampler));
  108063. var samplerData = this._loadSampler("#/samplers/" + sampler._index, sampler);
  108064. var deferred = new BABYLON.Deferred();
  108065. var babylonTexture = new BABYLON.Texture(null, this._babylonScene, samplerData.noMipMaps, false, samplerData.samplingMode, function () {
  108066. if (!_this._disposed) {
  108067. deferred.resolve();
  108068. }
  108069. }, function (message, exception) {
  108070. if (!_this._disposed) {
  108071. deferred.reject(new Error(context + ": " + (exception && exception.message) ? exception.message : message || "Failed to load texture"));
  108072. }
  108073. });
  108074. promises.push(deferred.promise);
  108075. babylonTexture.name = texture.name || "texture" + texture._index;
  108076. babylonTexture.wrapU = samplerData.wrapU;
  108077. babylonTexture.wrapV = samplerData.wrapV;
  108078. babylonTexture.coordinatesIndex = textureInfo.texCoord || 0;
  108079. var image = GLTFLoader._GetProperty(context + "/source", this._gltf.images, texture.source);
  108080. promises.push(this._loadImageAsync("#/images/" + image._index, image).then(function (objectURL) {
  108081. babylonTexture.updateURL(objectURL);
  108082. }));
  108083. assign(babylonTexture);
  108084. this.onTextureLoadedObservable.notifyObservers(babylonTexture);
  108085. return Promise.all(promises).then(function () { });
  108086. };
  108087. GLTFLoader.prototype._loadSampler = function (context, sampler) {
  108088. if (!sampler._data) {
  108089. sampler._data = {
  108090. noMipMaps: (sampler.minFilter === 9728 /* NEAREST */ || sampler.minFilter === 9729 /* LINEAR */),
  108091. samplingMode: GLTFLoader._GetTextureSamplingMode(context, sampler.magFilter, sampler.minFilter),
  108092. wrapU: GLTFLoader._GetTextureWrapMode(context, sampler.wrapS),
  108093. wrapV: GLTFLoader._GetTextureWrapMode(context, sampler.wrapT)
  108094. };
  108095. }
  108096. ;
  108097. return sampler._data;
  108098. };
  108099. GLTFLoader.prototype._loadImageAsync = function (context, image) {
  108100. if (image._objectURL) {
  108101. return image._objectURL;
  108102. }
  108103. var promise;
  108104. if (image.uri) {
  108105. promise = this._loadUriAsync(context, image.uri);
  108106. }
  108107. else {
  108108. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, image.bufferView);
  108109. promise = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView);
  108110. }
  108111. image._objectURL = promise.then(function (data) {
  108112. return URL.createObjectURL(new Blob([data], { type: image.mimeType }));
  108113. });
  108114. return image._objectURL;
  108115. };
  108116. GLTFLoader.prototype._loadUriAsync = function (context, uri) {
  108117. var _this = this;
  108118. var promise = GLTF2.GLTFLoaderExtension._LoadUriAsync(this, context, uri);
  108119. if (promise) {
  108120. return promise;
  108121. }
  108122. if (!GLTFLoader._ValidateUri(uri)) {
  108123. throw new Error(context + ": Uri '" + uri + "' is invalid");
  108124. }
  108125. if (BABYLON.Tools.IsBase64(uri)) {
  108126. return Promise.resolve(new Uint8Array(BABYLON.Tools.DecodeBase64(uri)));
  108127. }
  108128. return new Promise(function (resolve, reject) {
  108129. var request = BABYLON.Tools.LoadFile(_this._rootUrl + uri, function (data) {
  108130. if (!_this._disposed) {
  108131. resolve(new Uint8Array(data));
  108132. }
  108133. }, function (event) {
  108134. if (!_this._disposed) {
  108135. try {
  108136. if (request && _this._state === BABYLON.GLTFLoaderState.Loading) {
  108137. request._lengthComputable = event.lengthComputable;
  108138. request._loaded = event.loaded;
  108139. request._total = event.total;
  108140. _this._onProgress();
  108141. }
  108142. }
  108143. catch (e) {
  108144. reject(e);
  108145. }
  108146. }
  108147. }, _this._babylonScene.database, true, function (request, exception) {
  108148. if (!_this._disposed) {
  108149. reject(new BABYLON.LoadFileError(context + ": Failed to load '" + uri + "'" + (request ? ": " + request.status + " " + request.statusText : ""), request));
  108150. }
  108151. });
  108152. _this._requests.push(request);
  108153. });
  108154. };
  108155. GLTFLoader.prototype._onProgress = function () {
  108156. if (!this._progressCallback) {
  108157. return;
  108158. }
  108159. var lengthComputable = true;
  108160. var loaded = 0;
  108161. var total = 0;
  108162. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  108163. var request = _a[_i];
  108164. if (request._lengthComputable === undefined || request._loaded === undefined || request._total === undefined) {
  108165. return;
  108166. }
  108167. lengthComputable = lengthComputable && request._lengthComputable;
  108168. loaded += request._loaded;
  108169. total += request._total;
  108170. }
  108171. this._progressCallback(new BABYLON.SceneLoaderProgressEvent(lengthComputable, loaded, lengthComputable ? total : 0));
  108172. };
  108173. GLTFLoader._GetProperty = function (context, array, index) {
  108174. if (!array || index == undefined || !array[index]) {
  108175. throw new Error(context + ": Failed to find index " + index);
  108176. }
  108177. return array[index];
  108178. };
  108179. GLTFLoader._GetTextureWrapMode = function (context, mode) {
  108180. // Set defaults if undefined
  108181. mode = mode == undefined ? 10497 /* REPEAT */ : mode;
  108182. switch (mode) {
  108183. case 33071 /* CLAMP_TO_EDGE */: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  108184. case 33648 /* MIRRORED_REPEAT */: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  108185. case 10497 /* REPEAT */: return BABYLON.Texture.WRAP_ADDRESSMODE;
  108186. default:
  108187. BABYLON.Tools.Warn(context + ": Invalid texture wrap mode " + mode);
  108188. return BABYLON.Texture.WRAP_ADDRESSMODE;
  108189. }
  108190. };
  108191. GLTFLoader._GetTextureSamplingMode = function (context, magFilter, minFilter) {
  108192. // Set defaults if undefined
  108193. magFilter = magFilter == undefined ? 9729 /* LINEAR */ : magFilter;
  108194. minFilter = minFilter == undefined ? 9987 /* LINEAR_MIPMAP_LINEAR */ : minFilter;
  108195. if (magFilter === 9729 /* LINEAR */) {
  108196. switch (minFilter) {
  108197. case 9728 /* NEAREST */: return BABYLON.Texture.LINEAR_NEAREST;
  108198. case 9729 /* LINEAR */: return BABYLON.Texture.LINEAR_LINEAR;
  108199. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST;
  108200. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST;
  108201. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR;
  108202. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  108203. default:
  108204. BABYLON.Tools.Warn(context + ": Invalid texture minification filter " + minFilter);
  108205. return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  108206. }
  108207. }
  108208. else {
  108209. if (magFilter !== 9728 /* NEAREST */) {
  108210. BABYLON.Tools.Warn(context + ": Invalid texture magnification filter " + magFilter);
  108211. }
  108212. switch (minFilter) {
  108213. case 9728 /* NEAREST */: return BABYLON.Texture.NEAREST_NEAREST;
  108214. case 9729 /* LINEAR */: return BABYLON.Texture.NEAREST_LINEAR;
  108215. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  108216. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST;
  108217. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_NEAREST_MIPLINEAR;
  108218. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR;
  108219. default:
  108220. BABYLON.Tools.Warn(context + ": Invalid texture minification filter " + minFilter);
  108221. return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  108222. }
  108223. }
  108224. };
  108225. GLTFLoader._GetNumComponents = function (context, type) {
  108226. switch (type) {
  108227. case "SCALAR": return 1;
  108228. case "VEC2": return 2;
  108229. case "VEC3": return 3;
  108230. case "VEC4": return 4;
  108231. case "MAT2": return 4;
  108232. case "MAT3": return 9;
  108233. case "MAT4": return 16;
  108234. }
  108235. throw new Error(context + ": Invalid type " + type);
  108236. };
  108237. GLTFLoader._ValidateUri = function (uri) {
  108238. return (BABYLON.Tools.IsBase64(uri) || uri.indexOf("..") === -1);
  108239. };
  108240. GLTFLoader.prototype._compileMaterialsAsync = function () {
  108241. var promises = new Array();
  108242. if (this._gltf.materials) {
  108243. for (var _i = 0, _a = this._gltf.materials; _i < _a.length; _i++) {
  108244. var material = _a[_i];
  108245. var babylonMaterial = material._babylonMaterial;
  108246. var babylonMeshes = material._babylonMeshes;
  108247. if (babylonMaterial && babylonMeshes) {
  108248. for (var _b = 0, babylonMeshes_1 = babylonMeshes; _b < babylonMeshes_1.length; _b++) {
  108249. var babylonMesh = babylonMeshes_1[_b];
  108250. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh));
  108251. if (this.useClipPlane) {
  108252. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh, { clipPlane: true }));
  108253. }
  108254. }
  108255. }
  108256. }
  108257. }
  108258. return Promise.all(promises).then(function () { });
  108259. };
  108260. GLTFLoader.prototype._compileShadowGeneratorsAsync = function () {
  108261. var promises = new Array();
  108262. var lights = this._babylonScene.lights;
  108263. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  108264. var light = lights_1[_i];
  108265. var generator = light.getShadowGenerator();
  108266. if (generator) {
  108267. promises.push(generator.forceCompilationAsync());
  108268. }
  108269. }
  108270. return Promise.all(promises).then(function () { });
  108271. };
  108272. GLTFLoader.prototype._clear = function () {
  108273. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  108274. var request = _a[_i];
  108275. request.abort();
  108276. }
  108277. this._requests.length = 0;
  108278. if (this._gltf && this._gltf.images) {
  108279. for (var _b = 0, _c = this._gltf.images; _b < _c.length; _b++) {
  108280. var image = _c[_b];
  108281. if (image._objectURL) {
  108282. image._objectURL.then(function (value) {
  108283. URL.revokeObjectURL(value);
  108284. });
  108285. image._objectURL = undefined;
  108286. }
  108287. }
  108288. }
  108289. delete this._gltf;
  108290. delete this._babylonScene;
  108291. this._completePromises.length = 0;
  108292. for (var name_3 in this._extensions) {
  108293. this._extensions[name_3].dispose();
  108294. }
  108295. this._extensions = {};
  108296. delete this._rootBabylonMesh;
  108297. delete this._progressCallback;
  108298. this.onMeshLoadedObservable.clear();
  108299. this.onTextureLoadedObservable.clear();
  108300. this.onMaterialLoadedObservable.clear();
  108301. };
  108302. GLTFLoader.prototype._applyExtensions = function (actionAsync) {
  108303. for (var _i = 0, _a = GLTFLoader._Names; _i < _a.length; _i++) {
  108304. var name_4 = _a[_i];
  108305. var extension = this._extensions[name_4];
  108306. if (extension.enabled) {
  108307. var promise = actionAsync(extension);
  108308. if (promise) {
  108309. return promise;
  108310. }
  108311. }
  108312. }
  108313. return null;
  108314. };
  108315. GLTFLoader._Names = new Array();
  108316. GLTFLoader._Factories = {};
  108317. return GLTFLoader;
  108318. }());
  108319. GLTF2.GLTFLoader = GLTFLoader;
  108320. BABYLON.GLTFFileLoader.CreateGLTFLoaderV2 = function () { return new GLTFLoader(); };
  108321. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  108322. })(BABYLON || (BABYLON = {}));
  108323. //# sourceMappingURL=babylon.glTFLoader.js.map
  108324. var BABYLON;
  108325. (function (BABYLON) {
  108326. var GLTF2;
  108327. (function (GLTF2) {
  108328. var GLTFLoaderExtension = /** @class */ (function () {
  108329. function GLTFLoaderExtension(loader) {
  108330. this.enabled = true;
  108331. this._loader = loader;
  108332. }
  108333. GLTFLoaderExtension.prototype.dispose = function () {
  108334. delete this._loader;
  108335. };
  108336. // #region Overridable Methods
  108337. /** Override this method to modify the default behavior for loading scenes. */
  108338. GLTFLoaderExtension.prototype._loadSceneAsync = function (context, node) { return null; };
  108339. /** Override this method to modify the default behavior for loading nodes. */
  108340. GLTFLoaderExtension.prototype._loadNodeAsync = function (context, node) { return null; };
  108341. /** Override this method to modify the default behavior for loading mesh primitive vertex data. */
  108342. GLTFLoaderExtension.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) { return null; };
  108343. /** Override this method to modify the default behavior for loading materials. */
  108344. GLTFLoaderExtension.prototype._loadMaterialAsync = function (context, material, babylonMesh) { return null; };
  108345. /** Override this method to modify the default behavior for loading uris. */
  108346. GLTFLoaderExtension.prototype._loadUriAsync = function (context, uri) { return null; };
  108347. // #endregion
  108348. /** Helper method called by a loader extension to load an glTF extension. */
  108349. GLTFLoaderExtension.prototype._loadExtensionAsync = function (context, property, actionAsync) {
  108350. if (!property.extensions) {
  108351. return null;
  108352. }
  108353. var extensions = property.extensions;
  108354. var extension = extensions[this.name];
  108355. if (!extension) {
  108356. return null;
  108357. }
  108358. // Clear out the extension before executing the action to avoid recursing into the same property.
  108359. delete extensions[this.name];
  108360. try {
  108361. return actionAsync(context + "/extensions/" + this.name, extension);
  108362. }
  108363. finally {
  108364. // Restore the extension after executing the action.
  108365. extensions[this.name] = extension;
  108366. }
  108367. };
  108368. /** Helper method called by the loader to allow extensions to override loading scenes. */
  108369. GLTFLoaderExtension._LoadSceneAsync = function (loader, context, scene) {
  108370. return loader._applyExtensions(function (extension) { return extension._loadSceneAsync(context, scene); });
  108371. };
  108372. /** Helper method called by the loader to allow extensions to override loading nodes. */
  108373. GLTFLoaderExtension._LoadNodeAsync = function (loader, context, node) {
  108374. return loader._applyExtensions(function (extension) { return extension._loadNodeAsync(context, node); });
  108375. };
  108376. /** Helper method called by the loader to allow extensions to override loading mesh primitive vertex data. */
  108377. GLTFLoaderExtension._LoadVertexDataAsync = function (loader, context, primitive, babylonMesh) {
  108378. return loader._applyExtensions(function (extension) { return extension._loadVertexDataAsync(context, primitive, babylonMesh); });
  108379. };
  108380. /** Helper method called by the loader to allow extensions to override loading materials. */
  108381. GLTFLoaderExtension._LoadMaterialAsync = function (loader, context, material, babylonMesh) {
  108382. return loader._applyExtensions(function (extension) { return extension._loadMaterialAsync(context, material, babylonMesh); });
  108383. };
  108384. /** Helper method called by the loader to allow extensions to override loading uris. */
  108385. GLTFLoaderExtension._LoadUriAsync = function (loader, context, uri) {
  108386. return loader._applyExtensions(function (extension) { return extension._loadUriAsync(context, uri); });
  108387. };
  108388. return GLTFLoaderExtension;
  108389. }());
  108390. GLTF2.GLTFLoaderExtension = GLTFLoaderExtension;
  108391. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  108392. })(BABYLON || (BABYLON = {}));
  108393. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  108394. var BABYLON;
  108395. (function (BABYLON) {
  108396. var GLTF2;
  108397. (function (GLTF2) {
  108398. var Extensions;
  108399. (function (Extensions) {
  108400. // https://github.com/sbtron/glTF/tree/MSFT_lod/extensions/Vendor/MSFT_lod
  108401. var NAME = "MSFT_lod";
  108402. var MSFT_lod = /** @class */ (function (_super) {
  108403. __extends(MSFT_lod, _super);
  108404. function MSFT_lod() {
  108405. var _this = _super !== null && _super.apply(this, arguments) || this;
  108406. _this.name = NAME;
  108407. /**
  108408. * Maximum number of LODs to load, starting from the lowest LOD.
  108409. */
  108410. _this.maxLODsToLoad = Number.MAX_VALUE;
  108411. _this._loadingNodeLOD = null;
  108412. _this._loadNodeSignals = {};
  108413. _this._loadingMaterialLOD = null;
  108414. _this._loadMaterialSignals = {};
  108415. return _this;
  108416. }
  108417. MSFT_lod.prototype._loadNodeAsync = function (context, node) {
  108418. var _this = this;
  108419. return this._loadExtensionAsync(context, node, function (context, extension) {
  108420. var firstPromise;
  108421. var nodeLODs = _this._getLODs(context, node, _this._loader._gltf.nodes, extension.ids);
  108422. var _loop_1 = function (indexLOD) {
  108423. var nodeLOD = nodeLODs[indexLOD];
  108424. if (indexLOD !== 0) {
  108425. _this._loadingNodeLOD = nodeLOD;
  108426. _this._loadNodeSignals[nodeLOD._index] = new BABYLON.Deferred();
  108427. }
  108428. var promise = _this._loader._loadNodeAsync("#/nodes/" + nodeLOD._index, nodeLOD).then(function () {
  108429. if (indexLOD !== 0) {
  108430. var previousNodeLOD = nodeLODs[indexLOD - 1];
  108431. previousNodeLOD._babylonMesh.setEnabled(false);
  108432. }
  108433. if (indexLOD !== nodeLODs.length - 1) {
  108434. var nodeIndex = nodeLODs[indexLOD + 1]._index;
  108435. _this._loadNodeSignals[nodeIndex].resolve();
  108436. delete _this._loadNodeSignals[nodeIndex];
  108437. }
  108438. });
  108439. if (indexLOD === 0) {
  108440. firstPromise = promise;
  108441. }
  108442. else {
  108443. _this._loader._completePromises.push(promise);
  108444. _this._loadingNodeLOD = null;
  108445. }
  108446. };
  108447. for (var indexLOD = 0; indexLOD < nodeLODs.length; indexLOD++) {
  108448. _loop_1(indexLOD);
  108449. }
  108450. return firstPromise;
  108451. });
  108452. };
  108453. MSFT_lod.prototype._loadMaterialAsync = function (context, material, babylonMesh) {
  108454. var _this = this;
  108455. // Don't load material LODs if already loading a node LOD.
  108456. if (this._loadingNodeLOD) {
  108457. return null;
  108458. }
  108459. return this._loadExtensionAsync(context, material, function (context, extension) {
  108460. var firstPromise;
  108461. var materialLODs = _this._getLODs(context, material, _this._loader._gltf.materials, extension.ids);
  108462. var _loop_2 = function (indexLOD) {
  108463. var materialLOD = materialLODs[indexLOD];
  108464. if (indexLOD !== 0) {
  108465. _this._loadingMaterialLOD = materialLOD;
  108466. _this._loadMaterialSignals[materialLOD._index] = new BABYLON.Deferred();
  108467. }
  108468. var promise = _this._loader._loadMaterialAsync("#/materials/" + materialLOD._index, materialLOD, babylonMesh).then(function () {
  108469. if (indexLOD !== materialLODs.length - 1) {
  108470. var materialIndex = materialLODs[indexLOD + 1]._index;
  108471. _this._loadMaterialSignals[materialIndex].resolve();
  108472. delete _this._loadMaterialSignals[materialIndex];
  108473. }
  108474. });
  108475. if (indexLOD === 0) {
  108476. firstPromise = promise;
  108477. }
  108478. else {
  108479. _this._loader._completePromises.push(promise);
  108480. _this._loadingMaterialLOD = null;
  108481. }
  108482. };
  108483. for (var indexLOD = 0; indexLOD < materialLODs.length; indexLOD++) {
  108484. _loop_2(indexLOD);
  108485. }
  108486. return firstPromise;
  108487. });
  108488. };
  108489. MSFT_lod.prototype._loadUriAsync = function (context, uri) {
  108490. var _this = this;
  108491. // Defer the loading of uris if loading a material or node LOD.
  108492. if (this._loadingMaterialLOD) {
  108493. var index = this._loadingMaterialLOD._index;
  108494. return this._loadMaterialSignals[index].promise.then(function () {
  108495. return _this._loader._loadUriAsync(context, uri);
  108496. });
  108497. }
  108498. else if (this._loadingNodeLOD) {
  108499. var index = this._loadingNodeLOD._index;
  108500. return this._loadNodeSignals[index].promise.then(function () {
  108501. return _this._loader._loadUriAsync(context, uri);
  108502. });
  108503. }
  108504. return null;
  108505. };
  108506. /**
  108507. * Gets an array of LOD properties from lowest to highest.
  108508. */
  108509. MSFT_lod.prototype._getLODs = function (context, property, array, ids) {
  108510. if (this.maxLODsToLoad <= 0) {
  108511. throw new Error("maxLODsToLoad must be greater than zero");
  108512. }
  108513. var properties = new Array();
  108514. for (var i = ids.length - 1; i >= 0; i--) {
  108515. properties.push(GLTF2.GLTFLoader._GetProperty(context + "/ids/" + ids[i], array, ids[i]));
  108516. if (properties.length === this.maxLODsToLoad) {
  108517. return properties;
  108518. }
  108519. }
  108520. properties.push(property);
  108521. return properties;
  108522. };
  108523. return MSFT_lod;
  108524. }(GLTF2.GLTFLoaderExtension));
  108525. Extensions.MSFT_lod = MSFT_lod;
  108526. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new MSFT_lod(loader); });
  108527. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  108528. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  108529. })(BABYLON || (BABYLON = {}));
  108530. //# sourceMappingURL=MSFT_lod.js.map
  108531. var BABYLON;
  108532. (function (BABYLON) {
  108533. var GLTF2;
  108534. (function (GLTF2) {
  108535. var Extensions;
  108536. (function (Extensions) {
  108537. // https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_draco_mesh_compression
  108538. var NAME = "KHR_draco_mesh_compression";
  108539. var KHR_draco_mesh_compression = /** @class */ (function (_super) {
  108540. __extends(KHR_draco_mesh_compression, _super);
  108541. function KHR_draco_mesh_compression(loader) {
  108542. var _this = _super.call(this, loader) || this;
  108543. _this.name = NAME;
  108544. _this._dracoCompression = null;
  108545. // Disable extension if decoder is not available.
  108546. if (!BABYLON.DracoCompression.DecoderUrl) {
  108547. _this.enabled = false;
  108548. }
  108549. return _this;
  108550. }
  108551. KHR_draco_mesh_compression.prototype.dispose = function () {
  108552. if (this._dracoCompression) {
  108553. this._dracoCompression.dispose();
  108554. }
  108555. _super.prototype.dispose.call(this);
  108556. };
  108557. KHR_draco_mesh_compression.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  108558. var _this = this;
  108559. return this._loadExtensionAsync(context, primitive, function (extensionContext, extension) {
  108560. if (primitive.mode != undefined) {
  108561. if (primitive.mode !== 5 /* TRIANGLE_STRIP */ &&
  108562. primitive.mode !== 4 /* TRIANGLES */) {
  108563. throw new Error(context + ": Unsupported mode " + primitive.mode);
  108564. }
  108565. // TODO: handle triangle strips
  108566. if (primitive.mode === 5 /* TRIANGLE_STRIP */) {
  108567. throw new Error(context + ": Mode " + primitive.mode + " is not currently supported");
  108568. }
  108569. }
  108570. var attributes = {};
  108571. var loadAttribute = function (name, kind) {
  108572. var uniqueId = extension.attributes[name];
  108573. if (uniqueId == undefined) {
  108574. return;
  108575. }
  108576. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  108577. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  108578. babylonMesh._delayInfo.push(kind);
  108579. }
  108580. attributes[kind] = uniqueId;
  108581. };
  108582. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind);
  108583. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind);
  108584. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind);
  108585. loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind);
  108586. loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind);
  108587. loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind);
  108588. loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind);
  108589. loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind);
  108590. var bufferView = GLTF2.GLTFLoader._GetProperty(extensionContext, _this._loader._gltf.bufferViews, extension.bufferView);
  108591. return _this._loader._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (data) {
  108592. try {
  108593. if (!_this._dracoCompression) {
  108594. _this._dracoCompression = new BABYLON.DracoCompression();
  108595. }
  108596. return _this._dracoCompression.decodeMeshAsync(data, attributes);
  108597. }
  108598. catch (e) {
  108599. throw new Error(context + ": " + e.message);
  108600. }
  108601. });
  108602. });
  108603. };
  108604. return KHR_draco_mesh_compression;
  108605. }(GLTF2.GLTFLoaderExtension));
  108606. Extensions.KHR_draco_mesh_compression = KHR_draco_mesh_compression;
  108607. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_draco_mesh_compression(loader); });
  108608. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  108609. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  108610. })(BABYLON || (BABYLON = {}));
  108611. //# sourceMappingURL=KHR_draco_mesh_compression.js.map
  108612. var BABYLON;
  108613. (function (BABYLON) {
  108614. var GLTF2;
  108615. (function (GLTF2) {
  108616. var Extensions;
  108617. (function (Extensions) {
  108618. // https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness
  108619. var NAME = "KHR_materials_pbrSpecularGlossiness";
  108620. var KHR_materials_pbrSpecularGlossiness = /** @class */ (function (_super) {
  108621. __extends(KHR_materials_pbrSpecularGlossiness, _super);
  108622. function KHR_materials_pbrSpecularGlossiness() {
  108623. var _this = _super !== null && _super.apply(this, arguments) || this;
  108624. _this.name = NAME;
  108625. return _this;
  108626. }
  108627. KHR_materials_pbrSpecularGlossiness.prototype._loadMaterialAsync = function (context, material, babylonMesh) {
  108628. var _this = this;
  108629. return this._loadExtensionAsync(context, material, function (context, extension) {
  108630. material._babylonMeshes = material._babylonMeshes || [];
  108631. material._babylonMeshes.push(babylonMesh);
  108632. if (material._loaded) {
  108633. babylonMesh.material = material._babylonMaterial;
  108634. return material._loaded;
  108635. }
  108636. var promises = new Array();
  108637. var babylonMaterial = _this._loader._createMaterial(material);
  108638. material._babylonMaterial = babylonMaterial;
  108639. promises.push(_this._loader._loadMaterialBasePropertiesAsync(context, material));
  108640. promises.push(_this._loadSpecularGlossinessPropertiesAsync(_this._loader, context, material, extension));
  108641. _this._loader.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  108642. babylonMesh.material = babylonMaterial;
  108643. return (material._loaded = Promise.all(promises).then(function () { }));
  108644. });
  108645. };
  108646. KHR_materials_pbrSpecularGlossiness.prototype._loadSpecularGlossinessPropertiesAsync = function (loader, context, material, properties) {
  108647. var promises = new Array();
  108648. var babylonMaterial = material._babylonMaterial;
  108649. if (properties.diffuseFactor) {
  108650. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.diffuseFactor);
  108651. babylonMaterial.alpha = properties.diffuseFactor[3];
  108652. }
  108653. else {
  108654. babylonMaterial.albedoColor = BABYLON.Color3.White();
  108655. }
  108656. babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : BABYLON.Color3.White();
  108657. babylonMaterial.microSurface = properties.glossinessFactor == undefined ? 1 : properties.glossinessFactor;
  108658. if (properties.diffuseTexture) {
  108659. promises.push(loader._loadTextureAsync(context + "/diffuseTexture", properties.diffuseTexture, function (texture) {
  108660. babylonMaterial.albedoTexture = texture;
  108661. }));
  108662. }
  108663. if (properties.specularGlossinessTexture) {
  108664. promises.push(loader._loadTextureAsync(context + "/specularGlossinessTexture", properties.specularGlossinessTexture, function (texture) {
  108665. babylonMaterial.reflectivityTexture = texture;
  108666. }));
  108667. babylonMaterial.reflectivityTexture.hasAlpha = true;
  108668. babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  108669. }
  108670. loader._loadMaterialAlphaProperties(context, material);
  108671. return Promise.all(promises).then(function () { });
  108672. };
  108673. return KHR_materials_pbrSpecularGlossiness;
  108674. }(GLTF2.GLTFLoaderExtension));
  108675. Extensions.KHR_materials_pbrSpecularGlossiness = KHR_materials_pbrSpecularGlossiness;
  108676. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_materials_pbrSpecularGlossiness(loader); });
  108677. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  108678. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  108679. })(BABYLON || (BABYLON = {}));
  108680. //# sourceMappingURL=KHR_materials_pbrSpecularGlossiness.js.map
  108681. var BABYLON;
  108682. (function (BABYLON) {
  108683. var GLTF2;
  108684. (function (GLTF2) {
  108685. var Extensions;
  108686. (function (Extensions) {
  108687. // https://github.com/MiiBond/glTF/tree/khr_lights_v1/extensions/Khronos/KHR_lights
  108688. var NAME = "KHR_lights";
  108689. var LightType;
  108690. (function (LightType) {
  108691. LightType["AMBIENT"] = "ambient";
  108692. LightType["DIRECTIONAL"] = "directional";
  108693. LightType["POINT"] = "point";
  108694. LightType["SPOT"] = "spot";
  108695. })(LightType || (LightType = {}));
  108696. var KHR_lights = /** @class */ (function (_super) {
  108697. __extends(KHR_lights, _super);
  108698. function KHR_lights() {
  108699. var _this = _super !== null && _super.apply(this, arguments) || this;
  108700. _this.name = NAME;
  108701. return _this;
  108702. }
  108703. KHR_lights.prototype._loadSceneAsync = function (context, scene) {
  108704. var _this = this;
  108705. return this._loadExtensionAsync(context, scene, function (context, extension) {
  108706. var promise = _this._loader._loadSceneAsync(context, scene);
  108707. var light = GLTF2.GLTFLoader._GetProperty(context, _this._lights, extension.light);
  108708. if (light.type !== LightType.AMBIENT) {
  108709. throw new Error(context + ": Only ambient lights are allowed on a scene");
  108710. }
  108711. _this._loader._babylonScene.ambientColor = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.Black();
  108712. return promise;
  108713. });
  108714. };
  108715. KHR_lights.prototype._loadNodeAsync = function (context, node) {
  108716. var _this = this;
  108717. return this._loadExtensionAsync(context, node, function (context, extension) {
  108718. var promise = _this._loader._loadNodeAsync(context, node);
  108719. var babylonLight;
  108720. var light = GLTF2.GLTFLoader._GetProperty(context, _this._lights, extension.light);
  108721. var name = node._babylonMesh.name;
  108722. switch (light.type) {
  108723. case LightType.AMBIENT: {
  108724. throw new Error(context + ": Ambient lights are not allowed on a node");
  108725. }
  108726. case LightType.DIRECTIONAL: {
  108727. babylonLight = new BABYLON.DirectionalLight(name, BABYLON.Vector3.Forward(), _this._loader._babylonScene);
  108728. break;
  108729. }
  108730. case LightType.POINT: {
  108731. babylonLight = new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), _this._loader._babylonScene);
  108732. break;
  108733. }
  108734. case LightType.SPOT: {
  108735. var spotLight = light;
  108736. // TODO: support inner and outer cone angles
  108737. //const innerConeAngle = spotLight.innerConeAngle || 0;
  108738. var outerConeAngle = spotLight.outerConeAngle || Math.PI / 4;
  108739. babylonLight = new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward(), outerConeAngle, 2, _this._loader._babylonScene);
  108740. break;
  108741. }
  108742. default: {
  108743. throw new Error(context + ": Invalid light type " + light.type);
  108744. }
  108745. }
  108746. babylonLight.diffuse = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.White();
  108747. babylonLight.intensity = light.intensity == undefined ? 1 : light.intensity;
  108748. babylonLight.parent = node._babylonMesh;
  108749. return promise;
  108750. });
  108751. };
  108752. Object.defineProperty(KHR_lights.prototype, "_lights", {
  108753. get: function () {
  108754. var extensions = this._loader._gltf.extensions;
  108755. if (!extensions || !extensions[this.name]) {
  108756. throw new Error("#/extensions: " + this.name + " not found");
  108757. }
  108758. var extension = extensions[this.name];
  108759. return extension.lights;
  108760. },
  108761. enumerable: true,
  108762. configurable: true
  108763. });
  108764. return KHR_lights;
  108765. }(GLTF2.GLTFLoaderExtension));
  108766. Extensions.KHR_lights = KHR_lights;
  108767. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_lights(loader); });
  108768. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  108769. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  108770. })(BABYLON || (BABYLON = {}));
  108771. //# sourceMappingURL=KHR_lights.js.map
  108772. (function universalModuleDefinition(root, factory) {
  108773. var f = factory();
  108774. if(true)
  108775. module.exports = f;
  108776. else if(typeof define === 'function' && define.amd)
  108777. define("babylonjs-loaders", ["BABYLON"], factory);
  108778. else if(typeof exports === 'object')
  108779. exports["babylonjs-loaders"] = f;
  108780. else {
  108781. root["BABYLON"] = f;
  108782. }
  108783. })(this, function() {
  108784. return BABYLON;
  108785. });
  108786. /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(2)))
  108787. /***/ }),
  108788. /* 31 */
  108789. /***/ (function(module, exports, __webpack_require__) {
  108790. /*!
  108791. * PEP v0.4.3 | https://github.com/jquery/PEP
  108792. * Copyright jQuery Foundation and other contributors | http://jquery.org/license
  108793. */
  108794. !function(a,b){ true?module.exports=b():"function"==typeof define&&define.amd?define(b):a.PointerEventsPolyfill=b()}(this,function(){"use strict";function a(a,b){b=b||Object.create(null);var c=document.createEvent("Event");c.initEvent(a,b.bubbles||!1,b.cancelable||!1);
  108795. // define inherited MouseEvent properties
  108796. // skip bubbles and cancelable since they're set above in initEvent()
  108797. for(var d,e=2;e<m.length;e++)d=m[e],c[d]=b[d]||n[e];c.buttons=b.buttons||0;
  108798. // Spec requires that pointers without pressure specified use 0.5 for down
  108799. // state and 0 for up state.
  108800. var f=0;
  108801. // add x/y properties aliased to clientX/Y
  108802. // define the properties of the PointerEvent interface
  108803. return f=b.pressure&&c.buttons?b.pressure:c.buttons?.5:0,c.x=c.clientX,c.y=c.clientY,c.pointerId=b.pointerId||0,c.width=b.width||0,c.height=b.height||0,c.pressure=f,c.tiltX=b.tiltX||0,c.tiltY=b.tiltY||0,c.twist=b.twist||0,c.tangentialPressure=b.tangentialPressure||0,c.pointerType=b.pointerType||"",c.hwTimestamp=b.hwTimestamp||0,c.isPrimary=b.isPrimary||!1,c}function b(){this.array=[],this.size=0}function c(a,b,c,d){this.addCallback=a.bind(d),this.removeCallback=b.bind(d),this.changedCallback=c.bind(d),A&&(this.observer=new A(this.mutationWatcher.bind(this)))}function d(a){return"body /shadow-deep/ "+e(a)}function e(a){return'[touch-action="'+a+'"]'}function f(a){return"{ -ms-touch-action: "+a+"; touch-action: "+a+"; }"}function g(){if(F){D.forEach(function(a){String(a)===a?(E+=e(a)+f(a)+"\n",G&&(E+=d(a)+f(a)+"\n")):(E+=a.selectors.map(e)+f(a.rule)+"\n",G&&(E+=a.selectors.map(d)+f(a.rule)+"\n"))});var a=document.createElement("style");a.textContent=E,document.head.appendChild(a)}}function h(){
  108804. // only activate if this platform does not have pointer events
  108805. if(!window.PointerEvent){if(window.PointerEvent=a,window.navigator.msPointerEnabled){var b=window.navigator.msMaxTouchPoints;Object.defineProperty(window.navigator,"maxTouchPoints",{value:b,enumerable:!0}),u.registerSource("ms",_)}else Object.defineProperty(window.navigator,"maxTouchPoints",{value:0,enumerable:!0}),u.registerSource("mouse",N),void 0!==window.ontouchstart&&u.registerSource("touch",V);u.register(document)}}function i(a){if(!u.pointermap.has(a)){var b=new Error("InvalidPointerId");throw b.name="InvalidPointerId",b}}function j(a){for(var b=a.parentNode;b&&b!==a.ownerDocument;)b=b.parentNode;if(!b){var c=new Error("InvalidStateError");throw c.name="InvalidStateError",c}}function k(a){var b=u.pointermap.get(a);return 0!==b.buttons}function l(){window.Element&&!Element.prototype.setPointerCapture&&Object.defineProperties(Element.prototype,{setPointerCapture:{value:W},releasePointerCapture:{value:X},hasPointerCapture:{value:Y}})}/**
  108806. * This is the constructor for new PointerEvents.
  108807. *
  108808. * New Pointer Events must be given a type, and an optional dictionary of
  108809. * initialization properties.
  108810. *
  108811. * Due to certain platform requirements, events returned from the constructor
  108812. * identify as MouseEvents.
  108813. *
  108814. * @constructor
  108815. * @param {String} inType The type of the event to create.
  108816. * @param {Object} [inDict] An optional dictionary of initial event properties.
  108817. * @return {Event} A new PointerEvent of type `inType`, initialized with properties from `inDict`.
  108818. */
  108819. var m=["bubbles","cancelable","view","detail","screenX","screenY","clientX","clientY","ctrlKey","altKey","shiftKey","metaKey","button","relatedTarget","pageX","pageY"],n=[!1,!1,null,null,0,0,0,0,!1,!1,!1,!1,0,null,0,0],o=window.Map&&window.Map.prototype.forEach,p=o?Map:b;b.prototype={set:function(a,b){return void 0===b?this["delete"](a):(this.has(a)||this.size++,void(this.array[a]=b))},has:function(a){return void 0!==this.array[a]},"delete":function(a){this.has(a)&&(delete this.array[a],this.size--)},get:function(a){return this.array[a]},clear:function(){this.array.length=0,this.size=0},
  108820. // return value, key, map
  108821. forEach:function(a,b){return this.array.forEach(function(c,d){a.call(b,c,d,this)},this)}};var q=[
  108822. // MouseEvent
  108823. "bubbles","cancelable","view","detail","screenX","screenY","clientX","clientY","ctrlKey","altKey","shiftKey","metaKey","button","relatedTarget",
  108824. // DOM Level 3
  108825. "buttons",
  108826. // PointerEvent
  108827. "pointerId","width","height","pressure","tiltX","tiltY","pointerType","hwTimestamp","isPrimary",
  108828. // event instance
  108829. "type","target","currentTarget","which","pageX","pageY","timeStamp"],r=[
  108830. // MouseEvent
  108831. !1,!1,null,null,0,0,0,0,!1,!1,!1,!1,0,null,
  108832. // DOM Level 3
  108833. 0,
  108834. // PointerEvent
  108835. 0,0,0,0,0,0,"",0,!1,
  108836. // event instance
  108837. "",null,null,0,0,0,0],s={pointerover:1,pointerout:1,pointerenter:1,pointerleave:1},t="undefined"!=typeof SVGElementInstance,u={pointermap:new p,eventMap:Object.create(null),captureInfo:Object.create(null),
  108838. // Scope objects for native events.
  108839. // This exists for ease of testing.
  108840. eventSources:Object.create(null),eventSourceList:[],/**
  108841. * Add a new event source that will generate pointer events.
  108842. *
  108843. * `inSource` must contain an array of event names named `events`, and
  108844. * functions with the names specified in the `events` array.
  108845. * @param {string} name A name for the event source
  108846. * @param {Object} source A new source of platform events.
  108847. */
  108848. registerSource:function(a,b){var c=b,d=c.events;d&&(d.forEach(function(a){c[a]&&(this.eventMap[a]=c[a].bind(c))},this),this.eventSources[a]=c,this.eventSourceList.push(c))},register:function(a){for(var b,c=this.eventSourceList.length,d=0;d<c&&(b=this.eventSourceList[d]);d++)
  108849. // call eventsource register
  108850. b.register.call(b,a)},unregister:function(a){for(var b,c=this.eventSourceList.length,d=0;d<c&&(b=this.eventSourceList[d]);d++)
  108851. // call eventsource register
  108852. b.unregister.call(b,a)},contains:/*scope.external.contains || */function(a,b){try{return a.contains(b)}catch(c){
  108853. // most likely: https://bugzilla.mozilla.org/show_bug.cgi?id=208427
  108854. return!1}},
  108855. // EVENTS
  108856. down:function(a){a.bubbles=!0,this.fireEvent("pointerdown",a)},move:function(a){a.bubbles=!0,this.fireEvent("pointermove",a)},up:function(a){a.bubbles=!0,this.fireEvent("pointerup",a)},enter:function(a){a.bubbles=!1,this.fireEvent("pointerenter",a)},leave:function(a){a.bubbles=!1,this.fireEvent("pointerleave",a)},over:function(a){a.bubbles=!0,this.fireEvent("pointerover",a)},out:function(a){a.bubbles=!0,this.fireEvent("pointerout",a)},cancel:function(a){a.bubbles=!0,this.fireEvent("pointercancel",a)},leaveOut:function(a){this.out(a),this.propagate(a,this.leave,!1)},enterOver:function(a){this.over(a),this.propagate(a,this.enter,!0)},
  108857. // LISTENER LOGIC
  108858. eventHandler:function(a){
  108859. // This is used to prevent multiple dispatch of pointerevents from
  108860. // platform events. This can happen when two elements in different scopes
  108861. // are set up to create pointer events, which is relevant to Shadow DOM.
  108862. if(!a._handledByPE){var b=a.type,c=this.eventMap&&this.eventMap[b];c&&c(a),a._handledByPE=!0}},
  108863. // set up event listeners
  108864. listen:function(a,b){b.forEach(function(b){this.addEvent(a,b)},this)},
  108865. // remove event listeners
  108866. unlisten:function(a,b){b.forEach(function(b){this.removeEvent(a,b)},this)},addEvent:/*scope.external.addEvent || */function(a,b){a.addEventListener(b,this.boundHandler)},removeEvent:/*scope.external.removeEvent || */function(a,b){a.removeEventListener(b,this.boundHandler)},
  108867. // EVENT CREATION AND TRACKING
  108868. /**
  108869. * Creates a new Event of type `inType`, based on the information in
  108870. * `inEvent`.
  108871. *
  108872. * @param {string} inType A string representing the type of event to create
  108873. * @param {Event} inEvent A platform event with a target
  108874. * @return {Event} A PointerEvent of type `inType`
  108875. */
  108876. makeEvent:function(b,c){
  108877. // relatedTarget must be null if pointer is captured
  108878. this.captureInfo[c.pointerId]&&(c.relatedTarget=null);var d=new a(b,c);return c.preventDefault&&(d.preventDefault=c.preventDefault),d._target=d._target||c.target,d},
  108879. // make and dispatch an event in one call
  108880. fireEvent:function(a,b){var c=this.makeEvent(a,b);return this.dispatchEvent(c)},/**
  108881. * Returns a snapshot of inEvent, with writable properties.
  108882. *
  108883. * @param {Event} inEvent An event that contains properties to copy.
  108884. * @return {Object} An object containing shallow copies of `inEvent`'s
  108885. * properties.
  108886. */
  108887. cloneEvent:function(a){for(var b,c=Object.create(null),d=0;d<q.length;d++)b=q[d],c[b]=a[b]||r[d],
  108888. // Work around SVGInstanceElement shadow tree
  108889. // Return the <use> element that is represented by the instance for Safari, Chrome, IE.
  108890. // This is the behavior implemented by Firefox.
  108891. !t||"target"!==b&&"relatedTarget"!==b||c[b]instanceof SVGElementInstance&&(c[b]=c[b].correspondingUseElement);
  108892. // keep the semantics of preventDefault
  108893. return a.preventDefault&&(c.preventDefault=function(){a.preventDefault()}),c},getTarget:function(a){var b=this.captureInfo[a.pointerId];return b?a._target!==b&&a.type in s?void 0:b:a._target},propagate:function(a,b,c){
  108894. // Order of conditions due to document.contains() missing in IE.
  108895. for(var d=a.target,e=[];d!==document&&!d.contains(a.relatedTarget);)
  108896. // Touch: Do not propagate if node is detached.
  108897. if(e.push(d),d=d.parentNode,!d)return;c&&e.reverse(),e.forEach(function(c){a.target=c,b.call(this,a)},this)},setCapture:function(b,c,d){this.captureInfo[b]&&this.releaseCapture(b,d),this.captureInfo[b]=c,this.implicitRelease=this.releaseCapture.bind(this,b,d),document.addEventListener("pointerup",this.implicitRelease),document.addEventListener("pointercancel",this.implicitRelease);var e=new a("gotpointercapture");e.pointerId=b,e._target=c,d||this.asyncDispatchEvent(e)},releaseCapture:function(b,c){var d=this.captureInfo[b];if(d){this.captureInfo[b]=void 0,document.removeEventListener("pointerup",this.implicitRelease),document.removeEventListener("pointercancel",this.implicitRelease);var e=new a("lostpointercapture");e.pointerId=b,e._target=d,c||this.asyncDispatchEvent(e)}},/**
  108898. * Dispatches the event to its target.
  108899. *
  108900. * @param {Event} inEvent The event to be dispatched.
  108901. * @return {Boolean} True if an event handler returns true, false otherwise.
  108902. */
  108903. dispatchEvent:/*scope.external.dispatchEvent || */function(a){var b=this.getTarget(a);if(b)return b.dispatchEvent(a)},asyncDispatchEvent:function(a){requestAnimationFrame(this.dispatchEvent.bind(this,a))}};u.boundHandler=u.eventHandler.bind(u);var v={shadow:function(a){if(a)return a.shadowRoot||a.webkitShadowRoot},canTarget:function(a){return a&&Boolean(a.elementFromPoint)},targetingShadow:function(a){var b=this.shadow(a);if(this.canTarget(b))return b},olderShadow:function(a){var b=a.olderShadowRoot;if(!b){var c=a.querySelector("shadow");c&&(b=c.olderShadowRoot)}return b},allShadows:function(a){for(var b=[],c=this.shadow(a);c;)b.push(c),c=this.olderShadow(c);return b},searchRoot:function(a,b,c){if(a){var d,e,f=a.elementFromPoint(b,c);for(
  108904. // is element a shadow host?
  108905. e=this.targetingShadow(f);e;){if(
  108906. // find the the element inside the shadow root
  108907. d=e.elementFromPoint(b,c)){
  108908. // shadowed element may contain a shadow root
  108909. var g=this.targetingShadow(d);return this.searchRoot(g,b,c)||d}
  108910. // check for older shadows
  108911. e=this.olderShadow(e)}
  108912. // light dom element is the target
  108913. return f}},owner:function(a){
  108914. // walk up until you hit the shadow root or document
  108915. for(var b=a;b.parentNode;)b=b.parentNode;
  108916. // the owner element is expected to be a Document or ShadowRoot
  108917. return b.nodeType!==Node.DOCUMENT_NODE&&b.nodeType!==Node.DOCUMENT_FRAGMENT_NODE&&(b=document),b},findTarget:function(a){var b=a.clientX,c=a.clientY,d=this.owner(a.target);
  108918. // if x, y is not in this root, fall back to document search
  108919. return d.elementFromPoint(b,c)||(d=document),this.searchRoot(d,b,c)}},w=Array.prototype.forEach.call.bind(Array.prototype.forEach),x=Array.prototype.map.call.bind(Array.prototype.map),y=Array.prototype.slice.call.bind(Array.prototype.slice),z=Array.prototype.filter.call.bind(Array.prototype.filter),A=window.MutationObserver||window.WebKitMutationObserver,B="[touch-action]",C={subtree:!0,childList:!0,attributes:!0,attributeOldValue:!0,attributeFilter:["touch-action"]};c.prototype={watchSubtree:function(a){
  108920. // Only watch scopes that can target find, as these are top-level.
  108921. // Otherwise we can see duplicate additions and removals that add noise.
  108922. //
  108923. // TODO(dfreedman): For some instances with ShadowDOMPolyfill, we can see
  108924. // a removal without an insertion when a node is redistributed among
  108925. // shadows. Since it all ends up correct in the document, watching only
  108926. // the document will yield the correct mutations to watch.
  108927. this.observer&&v.canTarget(a)&&this.observer.observe(a,C)},enableOnSubtree:function(a){this.watchSubtree(a),a===document&&"complete"!==document.readyState?this.installOnLoad():this.installNewSubtree(a)},installNewSubtree:function(a){w(this.findElements(a),this.addElement,this)},findElements:function(a){return a.querySelectorAll?a.querySelectorAll(B):[]},removeElement:function(a){this.removeCallback(a)},addElement:function(a){this.addCallback(a)},elementChanged:function(a,b){this.changedCallback(a,b)},concatLists:function(a,b){return a.concat(y(b))},
  108928. // register all touch-action = none nodes on document load
  108929. installOnLoad:function(){document.addEventListener("readystatechange",function(){"complete"===document.readyState&&this.installNewSubtree(document)}.bind(this))},isElement:function(a){return a.nodeType===Node.ELEMENT_NODE},flattenMutationTree:function(a){
  108930. // find children with touch-action
  108931. var b=x(a,this.findElements,this);
  108932. // flatten the list
  108933. // make sure the added nodes are accounted for
  108934. return b.push(z(a,this.isElement)),b.reduce(this.concatLists,[])},mutationWatcher:function(a){a.forEach(this.mutationHandler,this)},mutationHandler:function(a){if("childList"===a.type){var b=this.flattenMutationTree(a.addedNodes);b.forEach(this.addElement,this);var c=this.flattenMutationTree(a.removedNodes);c.forEach(this.removeElement,this)}else"attributes"===a.type&&this.elementChanged(a.target,a.oldValue)}};var D=["none","auto","pan-x","pan-y",{rule:"pan-x pan-y",selectors:["pan-x pan-y","pan-y pan-x"]}],E="",F=window.PointerEvent||window.MSPointerEvent,G=!window.ShadowDOMPolyfill&&document.head.createShadowRoot,H=u.pointermap,I=25,J=[1,4,2,8,16],K=!1;try{K=1===new MouseEvent("test",{buttons:1}).buttons}catch(L){}
  108935. // handler block for native mouse events
  108936. var M,N={POINTER_ID:1,POINTER_TYPE:"mouse",events:["mousedown","mousemove","mouseup","mouseover","mouseout"],register:function(a){u.listen(a,this.events)},unregister:function(a){u.unlisten(a,this.events)},lastTouches:[],
  108937. // collide with the global mouse listener
  108938. isEventSimulatedFromTouch:function(a){for(var b,c=this.lastTouches,d=a.clientX,e=a.clientY,f=0,g=c.length;f<g&&(b=c[f]);f++){
  108939. // simulated mouse events will be swallowed near a primary touchend
  108940. var h=Math.abs(d-b.x),i=Math.abs(e-b.y);if(h<=I&&i<=I)return!0}},prepareEvent:function(a){var b=u.cloneEvent(a),c=b.preventDefault;return b.preventDefault=function(){a.preventDefault(),c()},b.pointerId=this.POINTER_ID,b.isPrimary=!0,b.pointerType=this.POINTER_TYPE,b},prepareButtonsForMove:function(a,b){var c=H.get(this.POINTER_ID);
  108941. // Update buttons state after possible out-of-document mouseup.
  108942. 0!==b.which&&c?a.buttons=c.buttons:a.buttons=0,b.buttons=a.buttons},mousedown:function(a){if(!this.isEventSimulatedFromTouch(a)){var b=H.get(this.POINTER_ID),c=this.prepareEvent(a);K||(c.buttons=J[c.button],b&&(c.buttons|=b.buttons),a.buttons=c.buttons),H.set(this.POINTER_ID,a),b&&0!==b.buttons?u.move(c):u.down(c)}},mousemove:function(a){if(!this.isEventSimulatedFromTouch(a)){var b=this.prepareEvent(a);K||this.prepareButtonsForMove(b,a),b.button=-1,H.set(this.POINTER_ID,a),u.move(b)}},mouseup:function(a){if(!this.isEventSimulatedFromTouch(a)){var b=H.get(this.POINTER_ID),c=this.prepareEvent(a);if(!K){var d=J[c.button];
  108943. // Produces wrong state of buttons in Browsers without `buttons` support
  108944. // when a mouse button that was pressed outside the document is released
  108945. // inside and other buttons are still pressed down.
  108946. c.buttons=b?b.buttons&~d:0,a.buttons=c.buttons}H.set(this.POINTER_ID,a),
  108947. // Support: Firefox <=44 only
  108948. // FF Ubuntu includes the lifted button in the `buttons` property on
  108949. // mouseup.
  108950. // https://bugzilla.mozilla.org/show_bug.cgi?id=1223366
  108951. c.buttons&=~J[c.button],0===c.buttons?u.up(c):u.move(c)}},mouseover:function(a){if(!this.isEventSimulatedFromTouch(a)){var b=this.prepareEvent(a);K||this.prepareButtonsForMove(b,a),b.button=-1,H.set(this.POINTER_ID,a),u.enterOver(b)}},mouseout:function(a){if(!this.isEventSimulatedFromTouch(a)){var b=this.prepareEvent(a);K||this.prepareButtonsForMove(b,a),b.button=-1,u.leaveOut(b)}},cancel:function(a){var b=this.prepareEvent(a);u.cancel(b),this.deactivateMouse()},deactivateMouse:function(){H["delete"](this.POINTER_ID)}},O=u.captureInfo,P=v.findTarget.bind(v),Q=v.allShadows.bind(v),R=u.pointermap,S=2500,T=200,U="touch-action",V={events:["touchstart","touchmove","touchend","touchcancel"],register:function(a){M.enableOnSubtree(a)},unregister:function(){},elementAdded:function(a){var b=a.getAttribute(U),c=this.touchActionToScrollType(b);c&&(a._scrollType=c,u.listen(a,this.events),
  108952. // set touch-action on shadows as well
  108953. Q(a).forEach(function(a){a._scrollType=c,u.listen(a,this.events)},this))},elementRemoved:function(a){a._scrollType=void 0,u.unlisten(a,this.events),
  108954. // remove touch-action from shadow
  108955. Q(a).forEach(function(a){a._scrollType=void 0,u.unlisten(a,this.events)},this)},elementChanged:function(a,b){var c=a.getAttribute(U),d=this.touchActionToScrollType(c),e=this.touchActionToScrollType(b);
  108956. // simply update scrollType if listeners are already established
  108957. d&&e?(a._scrollType=d,Q(a).forEach(function(a){a._scrollType=d},this)):e?this.elementRemoved(a):d&&this.elementAdded(a)},scrollTypes:{EMITTER:"none",XSCROLLER:"pan-x",YSCROLLER:"pan-y",SCROLLER:/^(?:pan-x pan-y)|(?:pan-y pan-x)|auto$/},touchActionToScrollType:function(a){var b=a,c=this.scrollTypes;return"none"===b?"none":b===c.XSCROLLER?"X":b===c.YSCROLLER?"Y":c.SCROLLER.exec(b)?"XY":void 0},POINTER_TYPE:"touch",firstTouch:null,isPrimaryTouch:function(a){return this.firstTouch===a.identifier},setPrimaryTouch:function(a){
  108958. // set primary touch if there no pointers, or the only pointer is the mouse
  108959. (0===R.size||1===R.size&&R.has(1))&&(this.firstTouch=a.identifier,this.firstXY={X:a.clientX,Y:a.clientY},this.scrolling=!1,this.cancelResetClickCount())},removePrimaryPointer:function(a){a.isPrimary&&(this.firstTouch=null,this.firstXY=null,this.resetClickCount())},clickCount:0,resetId:null,resetClickCount:function(){var a=function(){this.clickCount=0,this.resetId=null}.bind(this);this.resetId=setTimeout(a,T)},cancelResetClickCount:function(){this.resetId&&clearTimeout(this.resetId)},typeToButtons:function(a){var b=0;return"touchstart"!==a&&"touchmove"!==a||(b=1),b},touchToPointer:function(a){var b=this.currentTouchEvent,c=u.cloneEvent(a),d=c.pointerId=a.identifier+2;c.target=O[d]||P(c),c.bubbles=!0,c.cancelable=!0,c.detail=this.clickCount,c.button=0,c.buttons=this.typeToButtons(b.type),c.width=2*(a.radiusX||a.webkitRadiusX||0),c.height=2*(a.radiusY||a.webkitRadiusY||0),c.pressure=a.force||a.webkitForce||.5,c.isPrimary=this.isPrimaryTouch(a),c.pointerType=this.POINTER_TYPE,
  108960. // forward modifier keys
  108961. c.altKey=b.altKey,c.ctrlKey=b.ctrlKey,c.metaKey=b.metaKey,c.shiftKey=b.shiftKey;
  108962. // forward touch preventDefaults
  108963. var e=this;return c.preventDefault=function(){e.scrolling=!1,e.firstXY=null,b.preventDefault()},c},processTouches:function(a,b){var c=a.changedTouches;this.currentTouchEvent=a;for(var d,e=0;e<c.length;e++)d=c[e],b.call(this,this.touchToPointer(d))},
  108964. // For single axis scrollers, determines whether the element should emit
  108965. // pointer events or behave as a scroller
  108966. shouldScroll:function(a){if(this.firstXY){var b,c=a.currentTarget._scrollType;if("none"===c)
  108967. // this element is a touch-action: none, should never scroll
  108968. b=!1;else if("XY"===c)
  108969. // this element should always scroll
  108970. b=!0;else{var d=a.changedTouches[0],e=c,f="Y"===c?"X":"Y",g=Math.abs(d["client"+e]-this.firstXY[e]),h=Math.abs(d["client"+f]-this.firstXY[f]);
  108971. // if delta in the scroll axis > delta other axis, scroll instead of
  108972. // making events
  108973. b=g>=h}return this.firstXY=null,b}},findTouch:function(a,b){for(var c,d=0,e=a.length;d<e&&(c=a[d]);d++)if(c.identifier===b)return!0},
  108974. // In some instances, a touchstart can happen without a touchend. This
  108975. // leaves the pointermap in a broken state.
  108976. // Therefore, on every touchstart, we remove the touches that did not fire a
  108977. // touchend event.
  108978. // To keep state globally consistent, we fire a
  108979. // pointercancel for this "abandoned" touch
  108980. vacuumTouches:function(a){var b=a.touches;
  108981. // pointermap.size should be < tl.length here, as the touchstart has not
  108982. // been processed yet.
  108983. if(R.size>=b.length){var c=[];R.forEach(function(a,d){
  108984. // Never remove pointerId == 1, which is mouse.
  108985. // Touch identifiers are 2 smaller than their pointerId, which is the
  108986. // index in pointermap.
  108987. if(1!==d&&!this.findTouch(b,d-2)){var e=a.out;c.push(e)}},this),c.forEach(this.cancelOut,this)}},touchstart:function(a){this.vacuumTouches(a),this.setPrimaryTouch(a.changedTouches[0]),this.dedupSynthMouse(a),this.scrolling||(this.clickCount++,this.processTouches(a,this.overDown))},overDown:function(a){R.set(a.pointerId,{target:a.target,out:a,outTarget:a.target}),u.enterOver(a),u.down(a)},touchmove:function(a){this.scrolling||(this.shouldScroll(a)?(this.scrolling=!0,this.touchcancel(a)):(a.preventDefault(),this.processTouches(a,this.moveOverOut)))},moveOverOut:function(a){var b=a,c=R.get(b.pointerId);
  108988. // a finger drifted off the screen, ignore it
  108989. if(c){var d=c.out,e=c.outTarget;u.move(b),d&&e!==b.target&&(d.relatedTarget=b.target,b.relatedTarget=e,
  108990. // recover from retargeting by shadow
  108991. d.target=e,b.target?(u.leaveOut(d),u.enterOver(b)):(
  108992. // clean up case when finger leaves the screen
  108993. b.target=e,b.relatedTarget=null,this.cancelOut(b))),c.out=b,c.outTarget=b.target}},touchend:function(a){this.dedupSynthMouse(a),this.processTouches(a,this.upOut)},upOut:function(a){this.scrolling||(u.up(a),u.leaveOut(a)),this.cleanUpPointer(a)},touchcancel:function(a){this.processTouches(a,this.cancelOut)},cancelOut:function(a){u.cancel(a),u.leaveOut(a),this.cleanUpPointer(a)},cleanUpPointer:function(a){R["delete"](a.pointerId),this.removePrimaryPointer(a)},
  108994. // prevent synth mouse events from creating pointer events
  108995. dedupSynthMouse:function(a){var b=N.lastTouches,c=a.changedTouches[0];
  108996. // only the primary finger will synth mouse events
  108997. if(this.isPrimaryTouch(c)){
  108998. // remember x/y of last touch
  108999. var d={x:c.clientX,y:c.clientY};b.push(d);var e=function(a,b){var c=a.indexOf(b);c>-1&&a.splice(c,1)}.bind(null,b,d);setTimeout(e,S)}}};M=new c(V.elementAdded,V.elementRemoved,V.elementChanged,V);var W,X,Y,Z=u.pointermap,$=window.MSPointerEvent&&"number"==typeof window.MSPointerEvent.MSPOINTER_TYPE_MOUSE,_={events:["MSPointerDown","MSPointerMove","MSPointerUp","MSPointerOut","MSPointerOver","MSPointerCancel","MSGotPointerCapture","MSLostPointerCapture"],register:function(a){u.listen(a,this.events)},unregister:function(a){u.unlisten(a,this.events)},POINTER_TYPES:["","unavailable","touch","pen","mouse"],prepareEvent:function(a){var b=a;return $&&(b=u.cloneEvent(a),b.pointerType=this.POINTER_TYPES[a.pointerType]),b},cleanup:function(a){Z["delete"](a)},MSPointerDown:function(a){Z.set(a.pointerId,a);var b=this.prepareEvent(a);u.down(b)},MSPointerMove:function(a){var b=this.prepareEvent(a);u.move(b)},MSPointerUp:function(a){var b=this.prepareEvent(a);u.up(b),this.cleanup(a.pointerId)},MSPointerOut:function(a){var b=this.prepareEvent(a);u.leaveOut(b)},MSPointerOver:function(a){var b=this.prepareEvent(a);u.enterOver(b)},MSPointerCancel:function(a){var b=this.prepareEvent(a);u.cancel(b),this.cleanup(a.pointerId)},MSLostPointerCapture:function(a){var b=u.makeEvent("lostpointercapture",a);u.dispatchEvent(b)},MSGotPointerCapture:function(a){var b=u.makeEvent("gotpointercapture",a);u.dispatchEvent(b)}},aa=window.navigator;aa.msPointerEnabled?(W=function(a){i(a),j(this),k(a)&&(u.setCapture(a,this,!0),this.msSetPointerCapture(a))},X=function(a){i(a),u.releaseCapture(a,!0),this.msReleasePointerCapture(a)}):(W=function(a){i(a),j(this),k(a)&&u.setCapture(a,this)},X=function(a){i(a),u.releaseCapture(a)}),Y=function(a){return!!u.captureInfo[a]},g(),h(),l();var ba={dispatcher:u,Installer:c,PointerEvent:a,PointerMap:p,targetFinding:v};return ba});
  109000. /***/ }),
  109001. /* 32 */
  109002. /***/ (function(module, exports, __webpack_require__) {
  109003. "use strict";
  109004. Object.defineProperty(exports, "__esModule", { value: true });
  109005. var defaultViewer_1 = __webpack_require__(5);
  109006. var mappers_1 = __webpack_require__(1);
  109007. function InitTags(selector) {
  109008. if (selector === void 0) { selector = 'babylon'; }
  109009. var elements = document.querySelectorAll(selector);
  109010. for (var i = 0; i < elements.length; ++i) {
  109011. var element = elements.item(i);
  109012. var configMapper = mappers_1.mapperManager.getMapper('dom');
  109013. var config = configMapper.map(element);
  109014. var viewer = new defaultViewer_1.DefaultViewer(element, config);
  109015. }
  109016. }
  109017. exports.InitTags = InitTags;
  109018. /***/ })
  109019. /******/ ]);
  109020. (function universalModuleDefinition(root, factory) {
  109021. var f = factory();
  109022. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  109023. globalObject["undefined"] = f;
  109024. if(typeof exports === 'object' && typeof module === 'object')
  109025. module.exports = f;
  109026. else if(typeof define === 'function' && define.amd)
  109027. define("babylonjs-viewer", factory);
  109028. else if(typeof exports === 'object')
  109029. exports["babylonjs-viewer"] = f;
  109030. else {
  109031. root["undefined"] = f;
  109032. }
  109033. })(this, function() {
  109034. return undefined;
  109035. });